diff --git a/CHANGELOG.md b/CHANGELOG.md index 04ec0d3a..07058995 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased +- **A saved repeat order is never replaced by an abandoned *Yes* (review of #546 at e40f1ad).** On a reopened per-repeat draft, picking *Yes*, filling its row with rep1's order and going back to *No, per repeat folder* showed rep1's order in every repeat row, under "Pre-answered from your saved tags", and one Submit published it for every unit. A row's own saved tags now rank above a broader choice of the session (`channel_scope.seed`: the row's choice, its saved tags, a broader choice, the header names), and the "Pre-answered" note goes at the first change of the answer or of a row. Tests: `tests/test_notebook_channel_guide_reopen.py`, `tests/test_channel_scope.py`. +- **A reopened strict channel draft is never turned into fast mode (review of #546, F1).** The guided step's fast-mode tick is hidden and only Submit sets it, so an unpublished draft does not hold it: reopened, a per-repeat, per-unit or one-list-per-count draft was ticked by default and opening Channels wrote `channel_layout` = the first unit's order with every unit `channels_from = "experiment"`, and *Check and save* published every unit in that order. Opening the guided step now writes nothing, an unpublished draft with saved per-unit tags and no `channel_layout` reopens unticked (`TagMatrix.tick_for_draft`), and the question is answered as the draft is (`channel_scope.scope_of_draft`: fast mode *Yes*; a strict draft the broadest answer whose rows reproduce every saved tag, "Pre-answered from your saved tags"; else "Saved per-unit tags are kept"). Every folder colour still states R, G, B, now right after the image-type answer instead of on opening. The per-unit grid of the Python-interface pages keeps its behaviour (its fast mode tags from headers on opening by design; see the PR). Also: a unit whose images disagree records no other row's tags in its refusal; *Same order within each biological repeat folder*; a row filled from a broader choice says so; per unit, a blank row keeps that unit as it is; the image type's button reads *Validated ✓* after a save. Tests: `tests/test_notebook_channel_guide_reopen.py`, and the #281, #279, mode-switch alias and #257 flows through the guided step in `tests/test_notebook_channel_guide_flows.py`. +- **The channel step is a question, a few rows and one Submit (owner design of 25 November 2026).** The owner's Colab test of the v0.9.0 candidate found the tagging widget buggy: every dropdown change saved the draft and redrew the page (lag), there was one row per unit even when every image had the same channels, and values jumped after being picked. The shipped notebook (the stepper) now asks **Is the channel order the same for the whole dataset?** (with the channel counts when they differ). *Yes* opens one row of dropdowns per channel count; *No* asks **Same order within each biological repeat** (one row per repeat folder and count) or **Tag every imaging unit** (one row per unit). Dropdowns change only the form (no draft write, no redraw; choices are kept across redraws and answer switches, and a narrower row starts from the broader choice). **Submit** checks every row and the image headers with the #376 rules (`repeat_tags.repeat_fill`, the same refusal snapshot) and saves the tags, their aliases, the tag review and the statement in ONE draft write through `TagGrid.commit(..., then)` (`R_DRAFT_CHANGED` and every other save refusal apply). A unit whose header contradicts its row is listed and released only by an action on it (the override, a one-click confirmation, or a row of its own that fits its header). Recording: *Yes* with one count is fast mode (`channel_layout`, Spec ADR 0006); several counts, per repeat and per unit are strict per-unit files, each unit holding its row's list (no Spec change). Header names are evidence only and no longer tag a unit with no click in this step. New modules `channel_scope` (pure), `notebook_channels_guide`, `notebook_channels_submit`, `notebook_channels_summary` (split from the grid). The pages of the Python interface (`channels_step()`) keep the per-unit grid; the override editor now updates its highlights in place instead of redrawing the page. Tests: `tests/test_notebook_channel_step_acceptance.py` (eight scenarios clicked through the stepper, each published file checked by the Spec reference validator), `tests/test_notebook_channel_guide.py`, `tests/test_channel_scope.py`; the stepper tests of the per-unit grid pin it with the `legacy_grid` fixture. Human script: `docs/colab-release-check.md` step 10. +- **The image type is answered once for all folders, whatever their channel or image counts (owner, 25 November 2026).** **Use for all folders** stays the one answer when the headers differ (nothing pre-filled; the line now says to choose one type for all folders, and **Set per folder…** opens only when the answers differ). After the answer, every folder whose header does not fit it is listed under the line with its next step (a colour header answered separate channels: `R_IMAGE_TYPE_CONTRADICTS_HEADER`; three interleaved samples under a non-colour header answered colour: the RGB header override, Spec RH1) instead of the whole answer being blocked; the rules themselves are unchanged. *Colour (RGB)* for all is recorded only when every folder has three channels, and its refusal names every folder that cannot be colour. In the shipped notebook the image type is a form like the channel step: the box, each folder's radio buttons and the RGB header override box only change the form (no draft write, no redraw; each folder's note says *Not validated yet*), and **Validate** (the former *Use for all folders* button) checks that every folder has a type and saves every folder's type and the override in ONE draft write, then the channel step opens (asking first when it replaces saved answers). The pages of the Python interface keep saving each choice. Acceptance scenarios 9a-9c and 10 in `tests/test_notebook_channel_step_acceptance.py`. - **The notebook restores an output folder's earlier work as soon as the folder is set (v0.9.0, owner decisions of 25 November 2026).** When the output folder is typed or chosen (or follows a new experiment folder) and no check is on screen, `notebook_restore` looks at what it holds (`earlier_work.earlier_work`) and restores it through the existing paths: (1) the folder check runs as **Check folder** runs it, but each image whose fingerprint equals the one recorded in the new `check_headers.json` (written by every notebook check, `check_record`) keeps its recorded header and is not opened (`preflight(..., recorded=...)`, `Preflight.headers_reused`); a record of another experiment folder, of other software versions (this package, normalization, NumPy, tifffile, Python, zarr), of other header fields, or that cannot be read reuses nothing, and the message says why; (2) the saved draft, the saved description and the earlier run's settings are read as Check folder reads them, and the steps open on the first step still to do (nothing is confirmed for the user); (3) a run whose manifest is of this experiment and of the saved description as it is, with exactly the images analysed now, each unchanged, and that opens as a brick opens it (`RunInputs.open`: manifest version, table, design, `calibration.csv`, conversion record, images and masks; its refusal is shown otherwise; `earlier_work.run_mismatch`), is shown on **Run** with its report, intensity checks and next steps, and the combined notebook's cell 4 takes it (`notebook_cellpose_app.app_folders` falls back to `restored_run`; `RunInputs` checks it again). A message says what was restored, from when, and what was read again; **Start fresh** forgets the restore without changing or deleting any file; another output folder clears what was restored from the first; an error while restoring clears it and says so. The experiment folder, when empty, is taken from the record or the manifest; when the two name different folders nothing is restored and the message says they disagree. The folder boxes are read once typed (`continuous_update=False`: Enter, Browse or leaving the box), so a folder passed through while typing is never restored or written to. Once the user answers, confirms, saves or runs after a restore, the state is theirs: another output folder then behaves as after a manual Check folder (#98). An embedding brick without the output folder restores nothing. User guide §4 and §6. `tests/test_notebook_restore.py`, `tests/test_check_record.py`. - **Cellpose: a compact four-step widget (owner, 25 November 2026).** `segmentation_app` (the combined notebook's cell 4) now shows the segmentation with the Preprocessing app's stepper (`notebook_stepper.Stepper`: a strip of chips, Back and Next, one step on screen, answers kept): **Folders**, **Output and channels**, **Model and preview**, **Segment**. Step 1 checks the masks folder at once with the guard every write uses (`segmentation_handoff.check_masks_folder`, formerly `_check_folders`: not the run's output folder or the experiment, nor inside or around either) and shows the run's images with the preprocessing image viewer (`notebook_cellpose_view`, read with the axes, channel IDs and fingerprint the run recorded). Step 3 has no load button: **Preview** loads the model the first time and reuses it for other images, other settings and Segment; it loads again only when the model, its file, the device or the nuclei's own model changed (`CellposeNotebook.load_on_preview`). The output choice lists what each output writes and reads beside it, the nuclei's own model and settings sit in a visible box shown for Both, and each Cellpose setting has a one-line help saying which way to move it (Cellpose 4.2.1.1's docstrings and GUI tooltips). A weights download shows as one `tqdm.auto` bar and Cellpose's INFO log lines are dropped, its warnings shown in a card (`notebook_cellpose_download.quiet_cellpose`); what is loaded is unchanged. The *What to do next* form and cell are removed. The Segment step shows one line of exactly what it will use (model, device, every setting, and the nuclei's own model and settings for Both), amber with what differs when that is not what the last Preview used (not blocked; `notebook_cellpose_summary`). A model file overwritten at the same path is loaded again (its size and modification time are part of `model_choice`), and the model step's chip is not done while the form shows another model than the one loaded. Cellpose's import-time advice to install DINOv3 unpinned is replaced by a note naming the notebook's pinned *Install DINOv3 now* tick. Records and outputs are unchanged. - **`segmentation_cellpose.next_steps_lines` is replaced by `next_step_line` (API change).** `next_steps_lines` (several numbered lines, re-exported from `segmentation_cellpose`) is removed; `next_step_line(mask_types, masks_root, *, register_with=None)` returns the one line shown after a batch. Callers of `next_steps_lines` must switch to it. `tests/test_notebook_cellpose_stepper.py`; human test script `docs/testing/cellpose-stepper-human-test.md`. diff --git a/docs/colab-release-check.md b/docs/colab-release-check.md index 7e2592f2..07b77d1f 100644 --- a/docs/colab-release-check.md +++ b/docs/colab-release-check.md @@ -94,27 +94,80 @@ again on the tagged commit. `different_channel_counts` across folders). 10. **Channels** (step 3). - [ ] First the image type in one line, pre-filled only when every header agrees and - recorded only by **Use for all folders** (or each folder under **Set per folder…**, whose - pictures appear once it is opened; folders of different types are refused, - `R_HETEROGENEOUS_LAYOUT_NOT_ENABLED`). + recorded only by **Validate** (formerly *Use for all folders*; or each folder under + **Set per folder…**, whose pictures appear once it is opened; folders of different types + are refused, `R_HETEROGENEOUS_LAYOUT_NOT_ENABLED`). - [ ] v0.6.1 (#313, Spec RH1): with a folder whose images have three interleaved samples under a header that does not say colour, answered colour (RGB), the Image type card shows one unticked box for the RGB header override; ticking it records `rgb_header_override = true` for those folders, and it is never pre-ticked. - [ ] Then name the stains, then tag each folder's channels; the extra-stain folder gets its own list. The viewer shows each channel with its header name and its folder's tag. - - [ ] v0.7.0 (fast mode, owner decisions of 16 November 2026): **Every imaging unit - has the same channels in the same order** is ticked. On a tree whose headers name every - channel with the labels exactly, every folder is tagged on opening with no click. On the - 2 x 2 x 2 tree without header names, tagging the row *Tags of every imaging unit* once - fills every unit (rows grouped by condition / biological repeat, then technical repeat; - one column per C index), each *same as the first tagged unit*; changing one cell of one - unit marks only that unit *edited*. The extra-stain folder (another channel count) and a - folder whose header names are swapped are not filled: *Stopped* lists both with the fix, - and **Tag this unit on its own** gives the swapped one its own dropdowns. Unticking the - statement gives the blocks of identical headers exactly as before: the folders tagged - from their headers with no click are untagged again and their header is a proposal to - confirm. + - [ ] v0.9.0 (guided step, owner design of 25 November 2026). After the labels, one + question: **Is the channel order the same for the whole dataset?** No row of dropdowns + before it is answered, and never one row per folder unless asked. Choosing in a dropdown + saves nothing (the draft file's time in the Files panel does not change) and nothing + jumps or lags; only **Submit** saves. Check these on small trees (the acceptance tests + `tests/test_notebook_channel_step_acceptance.py` click the same): + 1. *Owner's layout*: 3 channels everywhere, a 4th in some biological repeats. The + question says "3 and 4 channels". **Yes**: two rows, *3 channels* and *4 channels*. + Tag both, **Submit**: "Saved". Finish and **Check and save** publishes; each folder + has its own list (3 or 4 labels), no `channel_layout`. + 2. *One count, same order*: **Yes**: one row. Tag it, **Submit**, publish: one + `channel_layout` and every unit `channels_from = "experiment"`. + 3. *One count, order per repeat*: **No**, then **Same order within each biological + repeat folder**: one row per repeat folder. Give `rep2` another order, **Submit**, publish: + each folder of a repeat has that repeat's order. + 4. *One count, every unit*: **No**, **Tag every imaging unit**: one row per folder; + **Submit**, publish: each folder has its own list. + 5. *Mixed counts, per repeat*: **No**, **Same order within each biological repeat + folder**: one row per repeat folder and channel count. **Submit**, publish. + 6. *A swapped header*: one folder's header names in another order. **Yes**, tag the row + in the order of the others, **Submit**: "Saved; 1 imaging unit(s) not tagged", the + folder listed with "C0: header … is …, the row says …", untagged. **Check and save** + refuses. **Override this unit**, set its order, **Confirm these tags**: the list is + empty; publish (that folder `channels_from = "unit"`). + 7. *Colour*: every folder colour: after **Validate**, "Every folder is colour + (RGB): nothing to tag", no question; publish with R, G, B. Colour and separate + channels mixed: Axes does not confirm and Channels waits for the axis roles. + 8. *Changing your mind*: pick, change, change back; **Yes** → **No** → **Yes** before + Submit: the same choices come back, a row per repeat starts from the *Yes* choice of + its count, no stale row is left, and nothing was saved. + 9. *One image type for all folders* (before the rows; the button is **Validate**): (a) on + the owner's layout (3 and 4 channels) choose *separate stains or markers, one per + channel* in the box, click **Validate** once: every folder is answered and the guided + question appears. (b) With folders holding different numbers of images: the same one + click. (c) Colour images whose headers differ (one says colour, the others are a + scanner's three samples without the colour header): nothing is pre-filled, **Set per + folder…** stays folded, and the line says to choose one type for all folders. Choose + *separate stains*, **Validate**: every folder is answered and *Another step + for 1 folder* names the one whose header says colour + (`R_IMAGE_TYPE_CONTRADICTS_HEADER`); the others go on. Or choose *colour (RGB)*: + *Another step for 5 folders* names the scanner folders; tick the RGB header + override and **Validate**: it clears and the description publishes with R, G, B. + 10. *The image type is a form*: open **Set per folder…**, change the box, change one + folder to colour, back, and again: nothing jumps, the rows are not redrawn, the + draft file's time does not change, and each folder's note says "Not validated yet". + **Validate** with a folder left without a type is refused and names it; with every + folder answered it saves once and the labels and the channel question follow. + 11. *Reopening* (review of #546): save a per-repeat answer (3., without publishing), + close and run the notebook again on the same output folder, open Channels: the + question shows **No** and **Same order within each biological repeat folder**, the + rows show your orders and "Pre-answered from your saved tags"; the draft file's time + does not change on opening; **Check and save** publishes each repeat's own order (no + `channel_layout`). The same for a per-unit answer and for *Yes* with 3 and 4 channels. + With a folder still listed: "Saved per-unit tags are kept; answer the question to + change them". On the reopened per-repeat answer, pick **Yes**, fill its row with + `rep1`'s order, then go back to **No** and **Same order within each biological repeat + folder**: every repeat row shows its own saved order ("as saved"), not `rep1`'s, and + "Pre-answered from your saved tags" is gone since the first change; **Submit** and + publish keep each repeat's order. A row with no saved list pre-filled from a broader + choice says so ("check it before Submit"); per unit, a row left blank keeps that folder as it is. After **Validate** + the button reads **Validated ✓** until a choice changes. A folder whose own images + name their channels differently is in no row: **Submit** lists it untagged ("its + images disagree") and records no other folder's tags for it; once its images agree + and the folder is checked again, **Override this unit** opens with every dropdown + blank ("no row's tags were recorded for it"). 11. **Masks** (step 4). - [ ] **Check the masks** runs with progress. *Your masks* offers separate objects, regions and *grouped labels (one value per parent, e.g. mitochondria by cell)*, none diff --git a/docs/contract.md b/docs/contract.md index 9339e52e..258f94ae 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1494,8 +1494,8 @@ One JSON object, UTF-8, two-space indent, sorted keys, LF, a final newline, no d | `channels` | Channel ID → `{display_name?, header_names?}` (the label list of the notebook's *Your channels* screen; `header_names` are the raw header names of the cells the user tagged with that label: the tag is the alias confirmation, of the name the cell's header has when it is tagged. At each tag the names no tagged cell has any more are dropped, and only the names of the cells just tagged are added: a tag saved while the header had another name never confirms the name it has now, so `R_HEADER_CONTRADICTION` stays until that cell is tagged again) | | `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 | +| `switch_mode` | `true` only when the user switched a published file between fast and strict mode (the notebook's tick, or in the guided channel step the answer to *Is the channel order the same for the whole dataset?*: fast mode only for *Yes* with one channel count); 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*, or the guided channel step's **Submit** (`notebook_channels_submit.py`, the same rules, written in the same draft write as the tags), 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 597cfee9..31f89571 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -510,8 +510,22 @@ editing, or the confirmed ones. An image that cannot be drawn gets a sentence sa imaging unit…**. 3. **Channels.** First the **image type**: what the channel dimension holds, *separate stains or markers* or *colour (RGB)*. It is proposed from the image headers (only when - they all agree) and recorded when you click **Use for all folders**. **Set per folder…** - holds one row per folder, with its picture; it opens when the headers differ. An + they all agree) and recorded when you click **Validate** (the pages of the Python + interface call it **Use for all folders** and save each folder's choice at once): choosing, + in the box or for a folder under **Set per folder…**, only changes the form, with no save + and no redraw; **Validate** checks every folder has a type and saves every folder's type + (and the RGB header override box below) in one write of the draft, then the channel step + opens, and the button reads **Validated ✓** until a choice changes. A folder chosen on its + own keeps its choice; the others take the box's. One answer for every + folder, whatever their numbers of channels or images, also when the headers differ (then + nothing is pre-filled: choose the type in the box). **Set per folder…** holds one row per + folder, with its picture; it opens when your answers differ. After the answer, every folder + whose header does not fit it is listed under the line with its next step (a header that + says colour answered *separate stains*: the run refuses it, `R_IMAGE_TYPE_CONTRADICTS_HEADER`, + so answer it colour or correct its header; three interleaved samples under a header that + does not say colour, answered colour: the RGB header override below), while the other + folders go on. *Colour (RGB)* for all folders is recorded only when every folder has three + channels; otherwise nothing is written and the folders that cannot be colour are named. An experiment that mixes colour and separate-channel folders is refused in this version. When a folder's images store three values per pixel side by side but their header does not say colour (some scanners save colour this way), the card explains it and offers @@ -523,7 +537,54 @@ editing, or the confirmed ones. An image that cannot be drawn gets a sentence sa stays unticked and the card names the folders that have it. Colour folders have the channels R, G and B. Otherwise name what you stained and confirm the list; then tag each folder's channels with those names, looking at any image in the viewer (each channel shows its header name - and the tag chosen for it). **Fast mode** is the default: **Every imaging unit has the same + and the tag chosen for it). + **Tagging the channels (the notebook, since v0.9.0; owner design of 25 November 2026).** + The step asks one question first: **Is the channel order the same for the whole + dataset?** When the images do not all have the same number of channels it says which + counts there are (for example *3 and 4 channels*). + - **Yes** opens **one row of dropdowns per channel count**: one row when every image has + the same number of channels, else one row for each count (one for the 3-channel images, + one for the 4-channel images). Each row tags every imaging unit with that many channels. + - **No** asks **Then how far does one channel order go?**: **Same order within each + biological repeat folder** opens one row per biological-repeat folder (and channel count), for + every condition's acquisitions in that folder; **Tag every imaging unit** opens one row + per imaging unit. + + Under each dropdown are the channel index (C0, C1, …) and the header name, as evidence. A + row is pre-filled only from what you chose in this session (switching from *Yes* to a row + per repeat starts each repeat from your choice for its channel count), from tags already + saved for every acquisition of the row, or from header names equal to your labels exactly + ("from the header names: check them before Submit"). **Choosing in a dropdown saves + nothing and redraws nothing**: switch the answers, change your mind, the choices stay. + **Submit** is the one save: every channel of every row must be tagged, each label once (else + nothing is saved and the rows at fault are named); then each acquisition's header names are + checked against its row, and the tags, the header names they confirm and the review of the + acquisitions it refused are saved in one write of the draft. An acquisition whose header names + contradict its row (another label at a channel, or other names than the row's first + acquisition) is not tagged: it is listed with the contradiction, and the override below + (**Override this unit**, **Confirm the same tags**, **Confirm all N like it**) or a row of + its own (*Tag every imaging unit*) whose tags fit its header releases it; nothing is + reordered or guessed, and the description is not saved while any acquisition is listed. An + acquisition whose own images disagree is in no row and is listed at Submit. **Saved tags** + then shows what every acquisition holds; to change them, change the rows and Submit again. + A row filled from your choice in a broader row says so ("check it before Submit"); a row + whose acquisitions already hold one saved list shows that list instead ("as saved"). With + *Tag every imaging unit*, a row left blank is no answer for that acquisition now: it keeps + what it holds, so the others can be saved while a listed one waits. When the notebook is + opened again on a saved draft, the step answers the question as the draft already is + (*Yes* for fast mode; for a per-unit draft, the broadest answer whose rows reproduce every + acquisition's saved tags exactly, said as "Pre-answered from your saved tags"; otherwise + "Saved per-unit tags are kept; answer the question to change them"; "Pre-answered" goes + as soon as you change the answer or a row), and opening it writes + nothing: a strict draft is never turned into fast mode without your Submit. + What is recorded: *Yes* with one channel count is fast mode (`channel_layout`, every + acquisition `channels_from = "experiment"`, Spec ADR 0006); every other answer is a strict + per-unit file in which each acquisition holds its row's list (several channel counts cannot be + one `channel_layout`). The image type is asked before the rows; when every folder is colour + there is nothing to tag. + + The pages of the Python interface (`channels_step()`, not the shipped notebook) keep the + per-unit grid, which saves at each choice. **Fast mode** is its default: **Every imaging unit has the same channels in the same order** is ticked, your declared assumption (never a guess). A folder whose image header names every channel with one of your labels, exactly as written (or with a header name already saved for that label), is tagged from its header with no click. Tag the diff --git a/pyproject.toml b/pyproject.toml index 1e30430f..35bf2bea 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -207,6 +207,9 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.repeat_tags" = "pure" "morphobricks_preprocessing.repeat_review" = "pure" "morphobricks_preprocessing.notebook_channels_rows" = "ui" +"morphobricks_preprocessing.notebook_channels_guide" = "ui" +"morphobricks_preprocessing.notebook_channels_submit" = "ui" +"morphobricks_preprocessing.notebook_channels_summary" = "ui" "morphobricks_preprocessing.notebook_channels_labels" = "ui" "morphobricks_preprocessing.notebook_channels_type" = "ui" "morphobricks_preprocessing.notebook_channels_view" = "ui" @@ -292,6 +295,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.channel_moves" = "pure" "morphobricks_preprocessing.channel_answers" = "pure" "morphobricks_preprocessing.channel_matrix" = "pure" +"morphobricks_preprocessing.channel_scope" = "pure" "morphobricks_preprocessing.channel_identity" = "pure" "morphobricks_preprocessing.channel_identity_model" = "pure" "morphobricks_preprocessing.channel_identity_text" = "pure" diff --git a/src/morphobricks_preprocessing/channel_scope.py b/src/morphobricks_preprocessing/channel_scope.py new file mode 100644 index 00000000..21d060bd --- /dev/null +++ b/src/morphobricks_preprocessing/channel_scope.py @@ -0,0 +1,262 @@ +"""The guided *Tag channels* step: which rows of dropdowns the user's answers open (pure). + +Owner design of 25 November 2026. Instead of one row of dropdowns per imaging unit, the step +asks how far one channel order goes, then opens only the rows that answer needs: + +- **Is the channel order the same for the whole dataset?** *Yes* opens one row (:data:`WHOLE`) + per channel count: one row when every image has the same number of channels, else one row + per count (owner decision: for example one for the 3-channel and one for the 4-channel + images). +- *No* asks whether the order is the same **within each biological repeat folder** (:data:`REPEAT`, + one row per repeat folder and channel count, as *Tag this repeat folder*) or whether + **every imaging unit** is tagged (:data:`UNIT`, one row per unit). + +The rows are a form: choosing in a dropdown changes the form only. **Submit** checks every row +against the image headers and saves the tags, with the tag review, in one draft write +(:mod:`.notebook_channels_submit`). Nothing here reads a file or a widget, and nothing is +guessed: a row is pre-filled only from what the user chose in it this session (:func:`seed`), +from the tags already saved for every unit of the row, from a broader row chosen this session, +or from header names that equal the labels exactly (:func:`.channel_labels.proposal_for`, a +suggestion shown as such). + +A unit whose own images disagree (another header or channel count within the unit, +:func:`.repeat_tags.repeat_apart`) is in no row: it is listed at Submit, never filled. +""" + +from __future__ import annotations + +from collections.abc import Collection, Mapping, Sequence +from dataclasses import dataclass + +from .channel_labels import UnitLayout, proposal_for, tags_of +from .channel_matrix import apart_reason +from .draft_answers import DraftAnswers, UnitAnswer, UnitKey +from .notebook_values import natural_key + +WHOLE = "whole" +"""The order is the same for the whole dataset: one row per channel count.""" +REPEAT = "repeat" +"""The order is the same within each biological repeat folder: one row per folder and count.""" +UNIT = "unit" +"""Every imaging unit is tagged on its own: one row per unit.""" +SCOPES = (WHOLE, REPEAT, UNIT) + +RowKey = tuple +"""A row: ``(WHOLE, count)``, ``(REPEAT, repeat folder, count)`` or ``(UNIT, unit key)``.""" + +FROM_CHOICE = "choice" +FROM_BROADER = "broader" +"""Pre-filled from the user's choice in a broader row (its repeat's, the whole dataset's).""" +FROM_SAVED = "saved" +FROM_HEADER = "header" +FROM_NONE = "" + + +@dataclass(frozen=True) +class FormRow: + """One row of dropdowns: the units it tags, their channel count, and its title.""" + + key: RowKey + units: tuple[UnitLayout, ...] + count: int + + @property + def scope(self) -> str: + """Return the scope of the row (:data:`WHOLE`, :data:`REPEAT` or :data:`UNIT`).""" + return str(self.key[0]) + + +def unit_order(layout: UnitLayout) -> tuple: + """Return the display order of a unit: its labels, numbers as numbers (rep2 before rep10).""" + return tuple(natural_key(part) for part in layout.key) + + +def colour_unit(layout: UnitLayout, units: Mapping[UnitKey, UnitAnswer]) -> bool: + """Return True for a unit the user answered colour (RGB): R, G and B, nothing to tag.""" + answer = units.get(layout.key) + return answer is not None and answer.image_type == "rgb" + + +def taggable( + layouts: Sequence[UnitLayout], units: Mapping[UnitKey, UnitAnswer] +) -> list[UnitLayout]: + """Return the units whose channels are tagged with labels: readable and not colour.""" + found = [u for u in layouts if u.usable and not colour_unit(u, units)] + return sorted(found, key=unit_order) + + +def apart(layouts: Sequence[UnitLayout]) -> list[UnitLayout]: + """Return the units whose own images disagree: in no row, listed at Submit.""" + return [u for u in layouts if apart_reason(u)] + + +def untyped(layouts: Sequence[UnitLayout], units: Mapping[UnitKey, UnitAnswer]) -> list[UnitKey]: + """Return the readable units whose image type is not answered yet (asked before tagging).""" + out = [] + for layout in layouts: + answer = units.get(layout.key) + if layout.usable and (answer is None or answer.image_type is None): + out.append(layout.key) + return out + + +def counts(layouts: Sequence[UnitLayout], units: Mapping[UnitKey, UnitAnswer]) -> list[int]: + """Return the channel counts of the units the rows tag, sorted (one entry: all the same).""" + rowed = [u for u in taggable(layouts, units) if not apart_reason(u)] + return sorted({u.channels for u in rowed}) + + +def form_rows( + layouts: Sequence[UnitLayout], units: Mapping[UnitKey, UnitAnswer], scope: str +) -> list[FormRow]: + """Return the rows of dropdowns the scope opens, in display order. + + Only taggable units whose images agree are in a row (:func:`taggable`, :func:`apart`). + """ + rowed = [u for u in taggable(layouts, units) if not apart_reason(u)] + if scope == WHOLE: + by_count: dict[int, list[UnitLayout]] = {} + for layout in rowed: + by_count.setdefault(layout.channels, []).append(layout) + return [FormRow((WHOLE, c), tuple(us), c) for c, us in sorted(by_count.items())] + if scope == REPEAT: + groups: dict[tuple[str, int], list[UnitLayout]] = {} + for layout in rowed: # every taggable unit, a header-colour one answered channels too + groups.setdefault((layout.key[1], layout.channels), []).append(layout) + ordered = sorted(groups.items(), key=lambda item: (natural_key(item[0][0]), item[0][1])) + return [FormRow((REPEAT, rep, c), tuple(g), c) for (rep, c), g in ordered] + if scope == UNIT: + return [FormRow((UNIT, u.key), (u,), u.channels) for u in rowed] + raise ValueError(f"unknown scope {scope!r}") + + +def broader(row: FormRow) -> list[RowKey]: + """Return the rows whose choice pre-fills this one when it has none: its repeat, the whole.""" + if row.scope == UNIT: + key = row.key[1] + return [(REPEAT, key[1], row.count), (WHOLE, row.count)] + if row.scope == REPEAT: + return [(WHOLE, row.count)] + return [] + + +def shared_saved(row: FormRow, answers: DraftAnswers) -> tuple[str, ...] | None: + """Return the tags every unit of the row has saved, when they are the same and complete.""" + found = {tags_of(u, answers.units.get(u.key)) for u in row.units} + if len(found) != 1: + return None + (tags,) = found + return None if None in tags else tuple(t for t in tags if t is not None) + + +def shared_proposal(row: FormRow, labels: Collection[str]) -> tuple[str, ...] | None: + """Return the tags every unit's header names propose, when exactly the same for all of them. + + The exact rule of :func:`.channel_labels.proposal_for` (NFC, no trimming): a suggestion the + user checks and submits, never saved on its own. + """ + found = {proposal_for(u, labels) for u in row.units} + if len(found) != 1: + return None + (tags,) = found + return tags + + +def seed( + row: FormRow, + pending: Mapping[RowKey, Sequence[str | None]], + answers: DraftAnswers, + labels: Collection[str], +) -> tuple[list[str | None], str]: + """Return what a row shows, and where it comes from (:data:`FROM_CHOICE` and so on). + + In order: what the user chose in this row; the tags every unit of the row has saved; what + the user chose in a broader row this session (its repeat, the whole dataset), so that + switching the answer keeps the choices that still apply; the labels its header names equal + exactly; nothing. A label no longer in the list is blank. + + The row's own saved tags rank above a broader choice (review of #546 at e40f1ad): on a + reopened per-repeat draft, *Yes* filled with rep1's order and then back to *No, per repeat* + showed rep1's order in every repeat row, and one Submit replaced every saved order with it. + A broader choice fills only a row whose units hold no common saved list. + """ + + def known(tags: Sequence[str | None]) -> list[str | None]: + if len(tags) != row.count: + return [None] * row.count + return [t if t in labels else None for t in tags] + + if row.key in pending: + return known(pending[row.key]), FROM_CHOICE + saved = shared_saved(row, answers) + if saved is not None: + return known(saved), FROM_SAVED + for key in broader(row): + if key in pending and any(pending[key]): + return known(pending[key]), FROM_BROADER + proposal = shared_proposal(row, labels) + if proposal is not None: + return known(proposal), FROM_HEADER + return [None] * row.count, FROM_NONE + + +def row_error(tags: Sequence[str | None]) -> str | None: + """Return why a row cannot be submitted (a channel untagged, a label twice), else None.""" + named = [t for t in tags if t] + if len(named) != len(tags): + return "tag every channel" + if len(set(named)) != len(named): + return "each label once" + return None + + +def scope_of_draft(answers: DraftAnswers, layouts: Sequence[UnitLayout] = ()) -> str | None: + """Return the answer that reproduces a draft's saved tags exactly, or None. + + A fast-mode draft (``channel_layout``, the user's statement, ADR 0006) is :data:`WHOLE`. + A strict draft whose every taggable unit holds complete saved tags is answered with the + broadest strict answer whose rows each hold one list that every unit of the row has saved: + :data:`WHOLE` only with several channel counts (with one count, *Yes* is fast mode, another + record), else :data:`REPEAT`, else :data:`UNIT`. These give the same strict file. Anything + else (a unit not tagged yet, no unit) is None: the question is asked. + """ + if answers.channel_layout is not None: + return WHOLE + units = answers.units + rowed = [u for u in taggable(layouts, units) if not apart_reason(u)] + if not rowed or any(None in tags_of(u, units.get(u.key)) for u in rowed): + return None + several = len(counts(layouts, units)) > 1 + for scope in ((WHOLE,) if several else ()) + (REPEAT, UNIT): + rows = form_rows(layouts, units, scope) + if all(shared_saved(row, answers) is not None for row in rows): + return scope + return None + + +__all__ = [ + "FROM_BROADER", + "FROM_CHOICE", + "FROM_HEADER", + "FROM_NONE", + "FROM_SAVED", + "REPEAT", + "SCOPES", + "UNIT", + "WHOLE", + "FormRow", + "RowKey", + "apart", + "broader", + "colour_unit", + "counts", + "form_rows", + "row_error", + "scope_of_draft", + "seed", + "shared_proposal", + "shared_saved", + "taggable", + "unit_order", + "untyped", +] diff --git a/src/morphobricks_preprocessing/notebook_channels.py b/src/morphobricks_preprocessing/notebook_channels.py index 75ea5a95..4139c26d 100644 --- a/src/morphobricks_preprocessing/notebook_channels.py +++ b/src/morphobricks_preprocessing/notebook_channels.py @@ -232,11 +232,17 @@ def _channel_labels_changed(self) -> None: self._refresh_masks_screen() def _types_changed(self) -> None: - """Redraw the grid after an image type (its rows hold the type cells).""" - self.channel_grid.matrix.sync_statement() # the statement's type is the lead's (ADR 0006) - if self._stains_not_applicable != self.channel_labels.not_applicable: + """Redraw the grid after an image type (its rows hold the type cells). + + The statement follows the user's type answer (ADR 0006: its type is the lead's; every + folder colour states R, G, B), once the grid is open on the units: the guided step + writes nothing when it opens (review of #546, F1), so the type click is what states it. + """ + switched = self._stains_not_applicable != self.channel_labels.not_applicable + if switched: self._channel_labels_changed() # every folder became colour, or no longer is - else: + self.channel_grid.matrix.sync_statement() + if not switched: self.channel_grid.refresh() self._channels_changed() diff --git a/src/morphobricks_preprocessing/notebook_channels_grid.py b/src/morphobricks_preprocessing/notebook_channels_grid.py index 29e18e76..055eab18 100644 --- a/src/morphobricks_preprocessing/notebook_channels_grid.py +++ b/src/morphobricks_preprocessing/notebook_channels_grid.py @@ -40,17 +40,17 @@ from .channel_labels import ( UnitLayout, named, - positions, proposal_for, remaining, tags_of, - usage, ) from .draft_answers import DraftAnswers, UnitKey from .notebook_channel_thumbs import COLOUR_TEXT, CONTRAST_TEXT, Thumbnails +from .notebook_channels_guide import ChannelGuide from .notebook_channels_matrix import STATEMENT, TagMatrix from .notebook_channels_repeat import RepeatRows from .notebook_channels_rows import FolderRows +from .notebook_channels_summary import _GridSummary from .notebook_channels_type import ImageTypeColumn from .notebook_channels_view import ( CHOOSE, @@ -65,6 +65,17 @@ from .notebook_row_fold import UNCHANGED, RowFold, row_status from .notebook_values import natural_key +GRID_HELP = ( + "Ticked (fast mode): a unit whose header names every channel with one of " + "your labels is tagged from it; tag the row of tags once and it fills every " + "unit without header names, then tune any cell; a unit that contradicts it " + "is refused and tagged on its own. Unticked: folders whose image headers are " + "identical are one block: say once which label each channel is, looking at " + "the pictures. The same label should be in the same column in every block; a " + "label used in only some folders is shown in orange. Every channel and every " + "image type must be answered." +) +"""The help of the per-unit grid (the pages; the stepper shows the guided step).""" FOLDERS_LISTED = 3 """Folders of a block listed at once where the page has the image viewer; more are folded.""" @@ -74,13 +85,18 @@ def folder_order(layout: UnitLayout) -> tuple: return tuple(natural_key(part) for part in layout.key) -class TagGrid: +class TagGrid(_GridSummary): """The tag grid: blocks of folders with identical headers, one answer per block.""" SAME_CHANNELS = True """The statement's default for a new description: ticked (owner, 16 November 2026, FC1). A published description reopens in its own mode (ADR 0006): only the user switches it.""" + GUIDED = True + """Whether the stepper (the shipped notebook) shows the guided step (owner, 25 November + 2026, :mod:`.notebook_channels_guide`): a question, a few rows of dropdowns, one Submit. + The stacked pages keep the per-unit grid.""" + def __init__( self, store: AnswerStore, @@ -112,6 +128,9 @@ def __init__( self.same_channels.observe(lambda _: self._statement_changed(), "value") self.matrix = TagMatrix(self) self.by_repeat = RepeatRows(self) + self.guided = False + """True while the guided step is shown instead of the blocks (:attr:`GUIDED`).""" + self.guide = ChannelGuide(self) self.blocks = widgets.VBox() self.usage_html = widgets.HTML() self.status = widgets.HTML() @@ -120,22 +139,15 @@ def __init__( self.rows = FolderRows(self.detail) self.contrast = widgets.HTML(f"
{CONTRAST_TEXT}
") self.plane = widgets.HTML() + self.legacy_help = ui.help_text(GRID_HELP) self.widget = ui.card( "Tag each channel", [ self.same_channels, - ui.help_text( - "Ticked (fast mode): a unit whose header names every channel with one of " - "your labels is tagged from it; tag the row of tags once and it fills every " - "unit without header names, then tune any cell; a unit that contradicts it " - "is refused and tagged on its own. Unticked: folders whose image headers are " - "identical are one block: say once which label each channel is, looking at " - "the pictures. The same label should be in the same column in every block; a " - "label used in only some folders is shown in orange. Every channel and every " - "image type must be answered." - ), + self.legacy_help, self.contrast, self.plane, + self.guide.widget, self.blocks, self.detail, self.matrix.stopped, @@ -161,12 +173,18 @@ def open(self, layouts: Sequence[UnitLayout], labels: list[str], thumbs: Thumbna self.matrix.reset() self.matrix.opening() self.matrix.tick_for_mode() + if self.guided: # the pages' fast mode tags with no click: a draft cannot tell + self.matrix.tick_for_draft() # a strict draft stays strict (review F1) self.by_repeat.restore(layouts) # refused units stay refused + self.guide.reset(layouts) self.layouts, self.labels, self.rows.thumbs = layouts, labels, thumbs if self.place_types: self.types.open(layouts) self.detail.children = [] - changed = self.matrix.trust_headers() | self.matrix.sync_statement() # fast mode + # guided: nothing is written on opening (no header tag, no statement): only Submit + changed = False + if not self.guided: + changed = self.matrix.trust_headers() | self.matrix.sync_statement() # fast mode self.by_repeat.reconcile() # refusals of units removed or changed by a re-check self.refresh() if changed: @@ -368,6 +386,10 @@ def tag_like(self, units: Sequence[UnitLayout], tags: tuple[str, ...]) -> None: def refresh(self) -> None: """Rebuild the blocks from the saved answers (pictures are kept, not read again).""" + self._show_mode() + if self.guided: + self._refresh_guided() + return self.building = True try: self.cells, self.confirm_buttons, self.split_buttons = {}, [], {} @@ -399,6 +421,27 @@ def refresh(self) -> None: self.building = False self._summary() + def _show_mode(self) -> None: + """Show the guided step or the per-unit grid, never both.""" + legacy = not self.guided + for part in (self.same_channels, self.legacy_help, self.blocks, self.detail): + ui.set_visible(part, legacy) + ui.set_visible(self.guide.widget, self.guided) + + def _refresh_guided(self) -> None: + """Rebuild the guided step, the listed units and the summary (no per-unit dropdown).""" + self.building = True + try: + self.cells, self.confirm_buttons, self.split_buttons = {}, [], {} + self.like_buttons, self.blocks.children = [], [] + self.matrix.stopped.value = "" + self.guide.render() + width = max((u.channels for u in self.layouts if u.usable), default=3) + self.by_repeat.build(width) # the listed units and their override, no repeat rows + finally: + self.building = False + self._summary() + def _status(self, units: Sequence[UnitLayout]) -> str: """Return whether a block's folders are as saved; it folds once fully answered.""" answered = remaining(units, self.store.answers().units, self.labels).done @@ -539,62 +582,5 @@ def _cell_mark(self, tag: str | None, proposed: bool) -> str: mark += " proposed, not confirmed" return mark - # Summary ----------------------------------------------------------------------------- - - def _summary(self) -> None: - """Say where each label is used and whether tagging is finished.""" - answers = self.store.answers() - total = len(self.layouts) - found = usage(self.layouts, answers.units, self.labels) - lines = [self._usage_line(label, len(found[label]), total) for label in self.labels] - for label, places in positions(self.layouts, answers.units, self.labels).items(): - if len(places) > 1: - where = ", ".join( - f"channel {i + 1} in {n} folder(s)" for i, n in sorted(places.items()) - ) - lines.append( - f"
{html.escape(label)} is not always in the same " - f"column: {where}.
" - ) - self.usage_html.value = ( - "
Where each label is used
" + "".join(lines) - ) - self.problem.value = self.message - self.status.value = self._progress(total) - - 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.""" - 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.""" - mark = chip(label, self.labels, self.shown_as(label)) - if used == total: - return f"
{mark} used in all {total} folders
" - if used == 0: - return ( - f"
{mark} not used in any folder yet
" - ) - return ( - "
{mark} " - f"{partial_text(label, used, total)} (A_SCOPE_INCOMPLETE)
" - ) - - def _progress(self, total: int) -> str: - """Return the status: what is still to answer, or that every channel is tagged.""" - answers = self.store.answers() - left = remaining(self.layouts, answers.units, self.labels) - if left.done: - return ui.status("ok", f"Every channel of every one of the {total} folders is tagged.") - parts = [] - if left.cells: - parts.append(f"{left.cells} channel(s) still to tag") - if left.types: - parts.append(f"{left.types} image type(s) still to choose") - if left.blocked: - parts.append(f"{left.blocked} folder(s) cannot be tagged") - return ui.status("warn", "Not finished: " + ", ".join(parts) + ".") - __all__ = ["TagGrid", "folder_order", "named", "partial_text"] diff --git a/src/morphobricks_preprocessing/notebook_channels_guide.py b/src/morphobricks_preprocessing/notebook_channels_guide.py new file mode 100644 index 00000000..3424f691 --- /dev/null +++ b/src/morphobricks_preprocessing/notebook_channels_guide.py @@ -0,0 +1,411 @@ +"""*Tag channels*, guided (owner design of 25 November 2026): a question, a few rows, Submit. + +The shipped notebook's channel step (the stepper turns it on, :attr:`.TagGrid.guided`). It +replaces the per-unit grid, where every dropdown change saved and redrew the page: + +1. **Is the channel order the same for the whole dataset?** (*Yes* / *No*), said with the + channel counts found when the images do not all have the same number of channels. +2. *Yes*: one row of dropdowns per channel count (one row when the count is the same + everywhere). *No*: **Same order within each biological repeat folder** (one row per repeat folder + and channel count) or **Tag every imaging unit** (one row per unit). +3. **Submit**: the only save. The dropdowns change this form only (no draft write, no redraw of + the page); Submit checks every row (each channel tagged, each label once) and the image + headers, and saves the tags, their review and the statement in one draft write + (:mod:`.notebook_channels_submit`). A unit whose header contradicts its row is listed with + the existing refusal flow (:mod:`.notebook_channels_override`), never reordered or guessed. + +The rows (:mod:`.channel_scope`) keep what was chosen: switching the answer and back, or any +redraw, shows the same choices, and a narrower row starts from the broader row's choice. +""" + +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_scope import ( + FROM_BROADER, + FROM_CHOICE, + FROM_HEADER, + FROM_SAVED, + REPEAT, + UNIT, + WHOLE, + FormRow, + RowKey, + apart, + colour_unit, + counts, + form_rows, + row_error, + scope_of_draft, + seed, + taggable, + untyped, +) +from .notebook_channels_submit import collisions, refused_text, submit +from .notebook_channels_view import CHOOSE, blank_chip, chip, columns, quoted, rgb_chip, unit_name + +if TYPE_CHECKING: + from .notebook_channels_grid import TagGrid + +SAME_QUESTION = "Is the channel order the same for the whole dataset?" +YES, NO = "yes", "no" +NARROW_QUESTION = "Then how far does one channel order go?" +NARROW_OPTIONS = [ + ("Same order within each biological repeat folder", REPEAT), + ("Tag every imaging unit", UNIT), +] +SUBMIT = "Submit" +SOURCE_TEXT = { + FROM_CHOICE: "", + FROM_BROADER: "from your choice for a broader row (its repeat folder or the whole " + "dataset): check it before Submit", + FROM_SAVED: "as saved", + FROM_HEADER: "from the header names: check them before Submit", +} +UNITS_LISTED = 6 +"""Units named in a row's line before the rest are counted.""" + + +class ChannelGuide: + """The guided channel step, drawn in the tag grid's card while the grid is guided.""" + + def __init__(self, grid: TagGrid) -> None: + self.grid = grid + self.pending: dict[RowKey, list[str | None]] = {} + """What the user chose in each row this session (never saved before Submit).""" + self.drops: dict[RowKey, list[widgets.Dropdown]] = {} + self.notes: dict[RowKey, widgets.HTML] = {} + self.rows: list[FormRow] = [] + self.renders = 0 + """How many times the form was rebuilt (a dropdown change never rebuilds it).""" + self._building = False + self.same = widgets.ToggleButtons(options=[("Yes", YES), ("No", NO)], value=None) + self.same.observe(lambda _: self._answered(), "value") + self.narrow = widgets.ToggleButtons(options=NARROW_OPTIONS, value=None) + self.narrow.observe(lambda _: self._answered(), "value") + self.same_text = widgets.HTML() + self.narrow_box = widgets.VBox([widgets.HTML(f"{NARROW_QUESTION}"), self.narrow]) + self.questions = widgets.VBox([self.same_text, self.same, self.narrow_box]) + self.rows_box = widgets.VBox() + self.submit_button = ui.button(f" {SUBMIT}", style="success", icon="check", main=True) + self.submit_button.on_click(lambda _: self.submit()) + self.message = widgets.HTML() + self.saved_box = widgets.HTML() + self.draft_note = widgets.HTML() + self.pre_answered = False + """True while the note says the answer and rows are the reopened draft's, unchanged.""" + self.widget = widgets.VBox( + [ + self.draft_note, + self.questions, + self.rows_box, + self.submit_button, + self.message, + self.saved_box, + ] + ) + + # State ------------------------------------------------------------------------------- + + def reset(self, layouts: Sequence = ()) -> None: + """Forget the form (another draft or other units) and answer as the draft already does. + + A fast-mode draft answers *Yes*; a strict draft whose saved tags one answer reproduces + exactly is pre-answered with it (:func:`.channel_scope.scope_of_draft`), its rows + showing the saved tags. Otherwise a draft with saved tags says they are kept until the + question is answered (review of #546, F1). + """ + self.pending = {} + self.message.value = "" + answers = self.grid.store.answers() + found = scope_of_draft(answers, layouts) + tagged = any(u.image_type != "rgb" and any(u.channels) for u in answers.units.values()) + self._building = True + try: + self.narrow.value = found if found in (REPEAT, UNIT) else None + self.same.value = None if found is None else (YES if found == WHOLE else NO) + finally: + self._building = False + self.pre_answered = found is not None and answers.channel_layout is None + if self.pre_answered: + self.draft_note.value = ui.status( + "info", + "Pre-answered from your saved tags: the rows show them.", + ["Change the answer or a row and Submit to change them."], + ) + elif found is None and tagged: + self.draft_note.value = ui.status( + "info", "Saved per-unit tags are kept; answer the question to change them." + ) + else: + self.draft_note.value = "" + + @property + def scope(self) -> str | None: + """Return the answer: :data:`WHOLE`, :data:`REPEAT`, :data:`UNIT`, or None (not yet).""" + if self.same.value == YES: + return WHOLE + if self.same.value == NO: + return self.narrow.value + return None + + def _answered(self) -> None: + """Open the rows of the new answer (the form only: nothing is saved).""" + if self._building: + return + self.message.value = "" + self._changed_from_draft() + self.render() + + def _changed_from_draft(self) -> None: + """Take back "Pre-answered from your saved tags" once the answer or a row changes. + + It said the rows show the saved tags: after a change some may not (review of #546 at + e40f1ad: it stayed while the rows showed another answer's choice). + """ + if self.pre_answered: + self.pre_answered = False + self.draft_note.value = "" + + # Building ---------------------------------------------------------------------------- + + def render(self) -> None: + """Rebuild the questions, the rows of the answer and the saved tags (no save).""" + self.renders += 1 + grid = self.grid + answers = grid.store.answers() + units = answers.units + found = counts(grid.layouts, units) + self.drops, self.notes = {}, {} + waiting = self._waiting(found) + ui.set_visible(self.questions, not waiting) + ui.set_visible(self.submit_button, not waiting and self.scope is not None) + if waiting: + self.rows, self.rows_box.children = [], [widgets.HTML(waiting)] + self.saved_box.value = self._saved_text() + return + self.same_text.value = self._same_text(found) + ui.set_visible(self.narrow_box, self.same.value == NO) + scope = self.scope + self.rows = form_rows(grid.layouts, units, scope) if scope else [] + width = max((r.count for r in self.rows), default=1) + built: list[widgets.Widget] = [] + if self.rows: + built.append(widgets.HTML(self._rows_text(scope, len(self.rows)))) + built += [self._row(row, width) for row in self.rows] + left = apart(taggable(grid.layouts, units)) + if left and scope: + names = ", ".join(html.escape(unit_name(u.key)) for u in left) + built.append( + widgets.HTML( + ui.status( + "warn", + f"{len(left)} imaging unit(s) in no row: their images disagree.", + [f"{names}: listed at Submit; correct or separate their images."], + raw=True, + ) + ) + ) + self.rows_box.children = built + self.saved_box.value = self._saved_text() + + def _waiting(self, found: Sequence[int]) -> str: + """Return why no row can be shown yet (HTML), or ``""``.""" + grid = self.grid + units = grid.store.answers().units + if untyped(grid.layouts, units): + return ui.status( + "info", + "Waiting for the image type.", + ["Confirm the image type above first: colour folders have R, G and B."], + ) + if not found: + if any(colour_unit(u, units) for u in grid.layouts): + return ui.status("ok", "Every folder is colour (RGB): R, G and B, nothing to tag.") + return ui.status("info", "No folder can be tagged.", ["See the folders above."]) + if not grid.labels: + return ui.status("info", "Waiting for the labels.", ["Confirm the label list first."]) + return "" + + @staticmethod + def _same_text(found: Sequence[int]) -> str: + """Return the first question, with the channel counts when they differ.""" + if len(found) == 1: + return f"{SAME_QUESTION}" + listed = " and ".join(str(c) for c in found) + return ( + f"{SAME_QUESTION}
The images have {listed} channels. " + "Yes opens one list per channel count (each number of channels has its own " + "order).
" + ) + + @staticmethod + def _rows_text(scope: str, count: int) -> str: + """Return the line above the rows.""" + what = { + WHOLE: "one list per channel count, for every imaging unit with that many channels", + REPEAT: "one list per biological-repeat folder (and channel count), for every " + "condition's imaging units in it", + UNIT: "one list per imaging unit", + }[scope] + return ( + f"
{count} row(s): {what}. Choosing changes only this " + f"form; {SUBMIT} checks the image headers and saves.
" + ) + + def _row(self, row: FormRow, width: int) -> widgets.Widget: + """Build one row: what it tags, a dropdown per C index with its header name, a note.""" + grid = self.grid + tags, source = seed(row, self.pending, grid.store.answers(), grid.labels) + options = [(CHOOSE, None), *((label, label) for label in grid.labels)] + drops: list[widgets.Dropdown] = [] + cells: list[widgets.Widget] = [widgets.HTML(self._row_title(row))] + for index in range(width): + if index >= row.count: + cells.append(widgets.HTML("")) + continue + drop = widgets.Dropdown( + options=options, value=tags[index], layout=widgets.Layout(width="99%") + ) + drop.observe(lambda c, k=row.key, i=index: self._picked(k, i, c["new"]), "value") + drops.append(drop) + cells.append(widgets.VBox([drop, widgets.HTML(self._header_text(row, index))])) + note = widgets.HTML(self._note(tags, source)) + cells.append(note) + self.drops[row.key], self.notes[row.key] = drops, note + return widgets.GridBox(cells, layout=columns(width)) + + @staticmethod + def _row_title(row: FormRow) -> str: + """Return the first cell of a row: what it tags.""" + names = [unit_name(u.key) for u in row.units] + shown = ", ".join(names[:UNITS_LISTED]) + if len(names) > UNITS_LISTED: + shown += f" and {len(names) - UNITS_LISTED} more" + if row.scope == WHOLE: + head = f"{row.count} channels" + elif row.scope == REPEAT: + head = f"{row.key[1]}, {row.count} channels" + else: + head = unit_name(row.key[1]) + return ( + f"{html.escape(head)}
{len(names)} imaging unit(s): " + f"{html.escape(shown)}
" + ) + + @staticmethod + def _header_text(row: FormRow, index: int) -> str: + """Return the C index and the header name under a dropdown (evidence, never a tag).""" + names = {u.name(index) for u in row.units} + if len(names) == 1: + return f"C{index} {quoted(next(iter(names)))}" + return f"C{index} header names differ" + + def _note(self, tags: Sequence[str | None], source: str) -> str: + """Return the note at the end of a row: what is still missing, or where it came from.""" + why = row_error(tags) + if why is not None and any(tags): + return f"{html.escape(why)}" + return f"{SOURCE_TEXT.get(source, '')}" + + def _picked(self, key: RowKey, index: int, value: str | None) -> None: + """Note one dropdown of a row in the form; no draft write, no redraw of the page.""" + drops = self.drops.get(key, []) + self.pending[key] = [d.value for d in drops] + self._changed_from_draft() + if key in self.notes: + self.notes[key].value = self._note(self.pending[key], FROM_CHOICE) + + def _saved_text(self) -> str: + """Return the saved tags of every imaging unit, read-only (empty before any save).""" + grid = self.grid + units = grid.store.answers().units + lines = [] + for layout in sorted(grid.layouts, key=lambda u: u.key): + answer = units.get(layout.key) + if colour_unit(layout, units): + shown = " ".join(rgb_chip(t) for t in ("R", "G", "B")) + elif layout.usable and answer is not None and any(answer.channels): + tags = tags_of(layout, answer) + shown = " ".join( + chip(t, grid.labels) if t else blank_chip("not tagged") for t in tags + ) + else: + continue + lines.append(f"{html.escape(unit_name(layout.key))}{shown}") + if not lines: + return "" + return ( + "
Saved tags (change them with " + f"the rows above and {SUBMIT})
{''.join(lines)}
" + ) + + # Submit ------------------------------------------------------------------------------ + + def values(self) -> dict[RowKey, list[str | None]]: + """Return what every row of the form shows now.""" + return {row.key: [d.value for d in self.drops.get(row.key, [])] for row in self.rows} + + def submit(self) -> bool: + """Check the form and save it in one draft write; nothing is saved when it is refused.""" + grid = self.grid + scope = self.scope + if scope is None: + return self._refuse(["Answer the question above first."]) + shown = self.values() + # one row per unit: a row left blank is no answer for that unit now (it keeps what it + # holds), so the others can be saved while a refused unit waits (review F5) + skipped = [r for r in self.rows if scope == UNIT and not any(shown[r.key])] + todo = [r for r in self.rows if r not in skipped] + if not todo: + return self._refuse(["Tag at least one row."]) + problems = [] + for row in todo: + why = row_error(shown[row.key]) + if why is not None: + problems.append(f"{html.escape(self._plain_title(row))}: {why}") + problems += collisions(grid, todo) + if problems: + return self._refuse(problems) + rows = [(row, [t for t in shown[row.key] if t]) for row in todo] + units = grid.store.answers().units + left = apart(taggable(grid.layouts, units)) + fast = scope == WHOLE and len(counts(grid.layouts, units)) == 1 + ok = submit(grid, rows, left, fast=fast) + if ok: + self.pending.update({key: list(value) for key, value in shown.items()}) + text = refused_text(grid) + if skipped: + names = ", ".join(html.escape(self._plain_title(r)) for r in skipped) + text += ui.status( + "info", f"Left as they were (their rows are blank): {names}.", raw=True + ) + self.message.value = text or ui.status("ok", "Saved: every row's tags are saved.") + else: + self.message.value = ( + grid.message or grid.by_repeat.notice or ui.status("error", "Not saved.") + ) + return ok + + @staticmethod + def _plain_title(row: FormRow) -> str: + if row.scope == WHOLE: + return f"{row.count} channels" + if row.scope == REPEAT: + return f"{row.key[1]}, {row.count} channels" + return unit_name(row.key[1]) + + def _refuse(self, lines: Sequence[str]) -> bool: + """Say why Submit saved nothing.""" + self.message.value = ui.status("error", "Not saved.", lines, raw=True) + return False + + +__all__ = ["NARROW_QUESTION", "SAME_QUESTION", "SUBMIT", "ChannelGuide"] diff --git a/src/morphobricks_preprocessing/notebook_channels_matrix.py b/src/morphobricks_preprocessing/notebook_channels_matrix.py index a78ef2bf..ff627dea 100644 --- a/src/morphobricks_preprocessing/notebook_channels_matrix.py +++ b/src/morphobricks_preprocessing/notebook_channels_matrix.py @@ -56,7 +56,7 @@ set_template, trusted, ) -from .draft_answers import ChannelAnswer, UnitKey +from .draft_answers import ChannelAnswer, DraftAnswers, UnitKey from .fast_statement import published_fast, statement_changed, with_statement from .notebook_channels_view import ( CHOOSE, @@ -151,13 +151,29 @@ def tick_for_mode(self) -> None: published = published_fast(answers) if published is None: return - mode = published != answers.switch_mode - if self.grid.same_channels.value != mode: - self.setting_tick = True - try: - self.grid.same_channels.value = mode - finally: - self.setting_tick = False + self.set_tick(published != answers.switch_mode) + + def tick_for_draft(self) -> None: + """Tick the statement as an unpublished draft's mode is (the guided step, F1). + + The tick is hidden in the guided step and only Submit sets it, so it is never saved + unless the draft was published (:meth:`tick_for_mode`). A draft whose units hold saved + tags of their own (not colour) and no ``channel_layout`` is a strict draft: it is + reopened unticked, never converted to fast mode by a statement written with no click + (review of #546, F1: a per-repeat draft was published with the first repeat's order). + A draft with ``channel_layout``, or with no such tags (new, or every folder colour), + keeps the tick. + """ + answers = self.grid.store.answers() + if published_fast(answers) is not None: + return # the published file's own mode (tick_for_mode) + tagged = any( + unit.image_type != "rgb" and any(unit.channels) for unit in answers.units.values() + ) + if answers.channel_layout is None and tagged: + self.set_tick(False) + elif answers.channel_layout is not None: + self.set_tick(True) def sync_statement(self, cells: Sequence[tuple[UnitKey, int]] = ()) -> bool: """Save the statement and the units' markers the tick and the tags give (ADR 0006). @@ -169,24 +185,46 @@ def sync_statement(self, cells: Sequence[tuple[UnitKey, int]] = ()) -> bool: """ self.clicked.update(key for key, _ in cells) answers = self.grid.store.answers() + new = self.stated(answers) + if not statement_changed(answers, new): + return False + return save_unattended(self.grid.store, new) + + def stated( + self, answers: DraftAnswers, cells: Sequence[tuple[UnitKey, int]] = () + ) -> DraftAnswers: + """Return ``answers`` with the statement and markers the tick and the tags give. + + The one computation of :meth:`sync_statement`; the guided step's Submit puts it in its + one draft write (:mod:`.notebook_channels_submit`), so the save after it changes + nothing. ``cells`` are the cells that write tags: their units are the user's tags. + """ groups, _ = self.groups() lead = groups[0][0] if groups else None - new = with_statement( + clicked = self.clicked | {key for key, _ in cells} + return with_statement( answers, self.grid.layouts, lead, self.template(groups[0]) if groups else (), ( self.own | self.marked_own, - self.clicked | user_units(self.grid.store, "tags"), + clicked | user_units(self.grid.store, "tags"), user_units(self.grid.store, "type"), ), ticked=bool(self.grid.same_channels.value), day=date.today().isoformat(), ) - if not statement_changed(answers, new): - return False - return save_unattended(self.grid.store, new) + + def set_tick(self, value: bool) -> None: + """Set the statement's tick without the redraw and save of a user's switch.""" + if self.grid.same_channels.value == value: + return + self.setting_tick = True + try: + self.grid.same_channels.value = value + finally: + self.setting_tick = False def take_back(self) -> None: """Write the strict page's draft back (the statement unticked). diff --git a/src/morphobricks_preprocessing/notebook_channels_override.py b/src/morphobricks_preprocessing/notebook_channels_override.py index dfa9cd45..ee905b31 100644 --- a/src/morphobricks_preprocessing/notebook_channels_override.py +++ b/src/morphobricks_preprocessing/notebook_channels_override.py @@ -74,10 +74,12 @@ def __init__(self, rows: RepeatRows) -> None: self.confirm_button: widgets.Button | None = None self.cancel_button: widgets.Button | None = None self.cells: dict[tuple[UnitKey, int], widgets.Dropdown] = {} + self.notes: dict[tuple[UnitKey, int], widgets.HTML] = {} 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.notes = {} self.confirm_button = self.cancel_button = None current = {u.key: u for u in self.rows.grid.layouts} offered = self._offered(current) @@ -198,28 +200,52 @@ def cancel(self) -> 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() + """Note one tag of the draft and update its highlights in place; nothing is saved. - 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.""" + Only the notes under the dropdowns change (no redraw of the page, owner 25 November + 2026: a choice never lags or resets the other choices). + """ + self.drafts[key][index] = value + layout = next((u for u in self.rows.grid.layouts if u.key == key), None) + if layout is None: + return + for (unit, at), text in zip( + [(key, i) for i in range(layout.channels)], self._notes(key, layout), strict=True + ): + if (unit, at) in self.notes: + self.notes[(unit, at)].value = text + + def _notes(self, key: UnitKey, layout: UnitLayout) -> list[str]: + """Return the note under each dropdown of the editor: disagreement, as the row, changed.""" rows = self.rows grid, refusal = rows.grid, rows.refused[key] - lead = refusal.lead - draft = self.drafts[key] = self._known(self.drafts[key], layout) # labels may change + draft = self.drafts[key] moved = recount(refusal.tags, layout) 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) + for d in differences(layout, draft, refusal.lead, grid.labels, refusal.channels) if moved is None } + return [ + self._note(index, draft, refusal.tags, found, grid.labels) + for index in range(layout.channels) + ] + + 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] + draft = self.drafts[key] = self._known(self.drafts[key], layout) # labels may change + moved = recount(refusal.tags, layout) + notes = self._notes(key, layout) options = [(CHOOSE, None), *((label, label) for label in grid.labels)] - info = f"{html.escape(unit_name(key))}: " + ( - html.escape(moved) - if moved - else "the row's tags are the start; change only what is different" - ) + if moved: + said = html.escape(moved) + elif not refusal.tags: # refused while its images disagreed: no row's tags recorded + said = "no row's tags were recorded for it: choose every channel" + else: + said = "the row's tags are the start; change only what is different" + info = f"{html.escape(unit_name(key))}: {said}" cells: list[widgets.Widget] = [widgets.HTML(info)] for index in range(width): if index >= layout.channels: @@ -230,12 +256,13 @@ def _editor(self, key: UnitKey, layout: UnitLayout, width: int) -> widgets.Widge ) drop.observe(lambda c, k=key, i=index: self._picked(k, i, c["new"]), "value") self.cells[(key, index)] = drop + self.notes[(key, index)] = widgets.HTML(notes[index]) 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.notes[(key, index)], ] ) ) diff --git a/src/morphobricks_preprocessing/notebook_channels_repeat.py b/src/morphobricks_preprocessing/notebook_channels_repeat.py index 9e48d612..82493d85 100644 --- a/src/morphobricks_preprocessing/notebook_channels_repeat.py +++ b/src/morphobricks_preprocessing/notebook_channels_repeat.py @@ -209,6 +209,9 @@ def reconcile(self) -> None: kept[key] = Refusal(html.escape(why), layout, None, old.tags, old.channels) continue lead = repeat_lead(group) or layout # the unit itself is not apart + if old.lead is None: # its images agree again: no confirmation came with that + kept[key] = Refusal(AGREED, layout, lead, old.tags, old.channels) + continue # before the count: it was refused with no row's tags to recount if (moved := recount(old.tags, layout)) is not None: kept[key] = Refusal(moved, layout, lead, old.tags, old.channels) continue # never compared, cut or padded: every channel is chosen again @@ -217,9 +220,6 @@ def reconcile(self) -> None: if relapsed(confirmed, layout): # checked before anything may drop the refusal kept[key] = Refusal(RELAPSED, layout, lead, old.tags, old.channels) continue - if old.lead is None: # its images agree again: no confirmation came with that - kept[key] = Refusal(AGREED, layout, lead, old.tags, old.channels) - continue found = self.contradictions(layout, old, lead) found = found or differences(layout, own, lead, grid.labels, answers.channels) why = UNTRUSTED if grid.same_channels.value else "its own tags are incomplete" @@ -293,7 +293,8 @@ def _offered(self) -> dict: def build(self, width: int) -> None: """Draw one row per offered repeat folder and channel count, and the current state.""" self.drops, self.buttons = {}, {} - groups = self._offered() if self.grid.labels else {} + # the guided step has its own rows (one per repeat when asked) and Submit + groups = self._offered() if self.grid.labels and not self.grid.guided else {} lines = [f"{html.escape(unit_name(k))}: {text}" for k, text in self.listed().items()] listed = ui.status( "error", diff --git a/src/morphobricks_preprocessing/notebook_channels_submit.py b/src/morphobricks_preprocessing/notebook_channels_submit.py new file mode 100644 index 00000000..883a2dad --- /dev/null +++ b/src/morphobricks_preprocessing/notebook_channels_submit.py @@ -0,0 +1,146 @@ +"""*Tag channels*, guided step: **Submit** checks the rows against the headers and saves them. + +Owner design of 25 November 2026 (:mod:`.channel_scope`). The dropdowns of the guided step only +change its form; Submit is the one action that saves, and it saves everything in ONE draft +write: the units' tags and their aliases, the tag review (the units it refused, the refusals it +released) and the statement of the answer (``channel_layout``, or a strict file): + +- every row is checked as a click on *Tag this repeat folder* is + (:func:`.repeat_tags.repeat_fill`, the same rule and the same aliases snapshot of a unit + already refused): a unit whose header names contradict the row's tags is listed with the + contradiction and not filled, never reordered or guessed; a unit of one row is checked + against its own header names only; +- a unit whose own images disagree is in no row and is listed (:func:`.repeat_tags. + repeat_apart`); a unit a row fills leaves the list (the owner kept that a row whose tags fit + the unit is an action on it); every other refusal and confirmation stays as it is; +- *the same order for the whole dataset* with one channel count is fast mode (Spec ADR 0006): + ``channel_layout`` is the row's list and every unit it fills follows it + (``channels_from = "experiment"``). Every other answer is a strict per-unit file: each unit + holds its own list, its row's (several channel counts, a row per repeat or per unit: no + single ``channel_layout`` can state them, and none is written). + +The write goes through :meth:`.TagGrid.commit` with ``then`` (:func:`.channel_answers.tagged`): +the draft generation check (``R_DRAFT_CHANGED``) and every other refusal of a save apply, and a +refused write leaves the draft, the review in memory and the tick as they were. +""" + +from __future__ import annotations + +import html +from collections.abc import Sequence +from dataclasses import replace +from typing import TYPE_CHECKING + +from . import notebook_style as ui +from .channel_matrix import difference_text +from .notebook_channels_memory import Refusal +from .notebook_channels_override import OTHER_DRAFT +from .repeat_tags import pairing_collision, repeat_apart, repeat_fill, repeat_lead, repeat_members + +if TYPE_CHECKING: + from .channel_labels import UnitLayout + from .channel_scope import FormRow + from .draft_answers import DraftAnswers + from .notebook_channels_grid import TagGrid + + +def collisions(grid: TagGrid, rows: Sequence[FormRow]) -> list[str]: + """Return a line per repeat row whose folder name the pairing puts into several repeats.""" + answers, out = grid.store.answers(), [] + for row in rows: + if row.scope != "repeat": + continue + found = pairing_collision(answers, repeat_members(grid.layouts, row.key[1])) + if found: + pairs = ", ".join(f"{c} → {r}" for c, r in found.items()) + out.append( + f"{html.escape(row.key[1])}: paired with different biological repeats " + f"({html.escape(pairs)}); tag every imaging unit instead" + ) + return list(dict.fromkeys(out)) + + +def submit( + grid: TagGrid, + rows: Sequence[tuple[FormRow, Sequence[str]]], + apart: Sequence[UnitLayout], + *, + fast: bool, +) -> bool: + """Check every row against the headers and save tags, review and statement in one write. + + ``rows`` are the rows with their complete tags (checked by the caller), ``apart`` the units + whose images disagree, ``fast`` whether the answer is fast mode. Returns True when the + write succeeded (refused units may then be listed); False when nothing was written. + """ + memory = grid.by_repeat + if memory.other_draft(): # the review in memory is another draft's: never written here + memory.notice = OTHER_DRAFT + grid.refresh() + return False + memory.sync() # the review is built from the draft's, never from memory behind it + answers, labels = grid.store.answers(), grid.labels + frozen = {key: old.channels for key, old in memory.refused.items()} + save: dict = {} + cells: list = [] + staged = dict(memory.refused) + for row, tags in rows: + tags = tuple(tags) + filled, clicked, refused = repeat_fill(answers, row.units, tags, labels, frozen) + lead = repeat_lead(row.units) + for key, found in refused.items(): + layout = next(u for u in row.units if u.key == key) + text = "; ".join(html.escape(difference_text(d)) for d in found) + staged[key] = Refusal(text, layout, lead, tags, frozen.get(key, answers.channels)) + save.update(filled) + cells += clicked + for layout in apart: # its images disagree: listed, never filled + # no row's tags are recorded for it (it is in no row, review F4): only its own reason + why = repeat_apart((layout,)).get(layout.key, "its images disagree") + snapshot = frozen.get(layout.key, answers.channels) + staged[layout.key] = Refusal(html.escape(why), layout, None, (), snapshot) + for key in save: # filled by this Submit: its refusal goes with the same write + staged.pop(key, None) + kept = {k: v for k, v in memory.override.confirmed.items() if k in staged} + review = memory._review(kept, staged) + matrix = grid.matrix + before = (bool(grid.same_channels.value), set(matrix.own), dict(matrix.templates)) + matrix.set_tick(fast) + if fast and rows: + matrix.own -= set(save) # they follow the list again + groups, _ = matrix.groups() + if groups: + matrix.templates[groups[0][0].key] = tuple(rows[0][1]) + + def then(new: DraftAnswers) -> DraftAnswers: + return matrix.stated(replace(new, tag_review=review), cells) + + memory.staged = staged # memory takes it in ``adopt``, once the write succeeded + try: + ok = grid.commit(save, cells, then) + finally: + memory.staged = None + if not ok: # nothing was written: the tick and the rows of the matrix are as before + matrix.set_tick(before[0]) + matrix.own, matrix.templates = before[1], before[2] + grid.refresh() + return ok + + +def refused_text(grid: TagGrid) -> str: + """Return what Submit says about the units it listed (empty when none is listed).""" + listed = grid.by_repeat.listed() + if not listed: + return "" + return ui.status( + "warn", + f"Saved; {len(listed)} imaging unit(s) not tagged: their image headers contradict " + "the tags you submitted, or their images disagree.", + [ + "Nothing is reordered or guessed. Each is listed below: confirm its tags (Override " + "this unit) or correct its images. The description is not saved while any is listed." + ], + ) + + +__all__ = ["collisions", "refused_text", "submit"] diff --git a/src/morphobricks_preprocessing/notebook_channels_summary.py b/src/morphobricks_preprocessing/notebook_channels_summary.py new file mode 100644 index 00000000..eaff7eaa --- /dev/null +++ b/src/morphobricks_preprocessing/notebook_channels_summary.py @@ -0,0 +1,93 @@ +"""The summary lines under *Tag channels*: where each label is used, and what is still open. + +Part of :class:`.notebook_channels_grid.TagGrid` (a mixin, so the grid stays one screen of +code); it reads the saved answers only. +""" + +from __future__ import annotations + +import html +from collections.abc import Sequence +from typing import TYPE_CHECKING + +from . import notebook_style as ui +from .channel_labels import positions, remaining, usage +from .notebook_channels_view import chip, partial_text + +if TYPE_CHECKING: + import ipywidgets as widgets + + from .channel_labels import UnitLayout + from .notebook_channels_view import AnswerStore + + +class _GridSummary: + """Where each label is used and whether tagging is finished (the grid's last lines).""" + + store: AnswerStore + layouts: Sequence[UnitLayout] + labels: list[str] + message: str + usage_html: widgets.HTML + problem: widgets.HTML + status: widgets.HTML + + # Summary ----------------------------------------------------------------------------- + + def _summary(self) -> None: + """Say where each label is used and whether tagging is finished.""" + answers = self.store.answers() + total = len(self.layouts) + found = usage(self.layouts, answers.units, self.labels) + lines = [self._usage_line(label, len(found[label]), total) for label in self.labels] + for label, places in positions(self.layouts, answers.units, self.labels).items(): + if len(places) > 1: + where = ", ".join( + f"channel {i + 1} in {n} folder(s)" for i, n in sorted(places.items()) + ) + lines.append( + f"
{html.escape(label)} is not always in the same " + f"column: {where}.
" + ) + self.usage_html.value = ( + "
Where each label is used
" + "".join(lines) + ) + self.problem.value = self.message + self.status.value = self._progress(total) + + 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.""" + 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.""" + mark = chip(label, self.labels, self.shown_as(label)) + if used == total: + return f"
{mark} used in all {total} folders
" + if used == 0: + return ( + f"
{mark} not used in any folder yet
" + ) + return ( + "
{mark} " + f"{partial_text(label, used, total)} (A_SCOPE_INCOMPLETE)
" + ) + + def _progress(self, total: int) -> str: + """Return the status: what is still to answer, or that every channel is tagged.""" + answers = self.store.answers() + left = remaining(self.layouts, answers.units, self.labels) + if left.done: + return ui.status("ok", f"Every channel of every one of the {total} folders is tagged.") + parts = [] + if left.cells: + parts.append(f"{left.cells} channel(s) still to tag") + if left.types: + parts.append(f"{left.types} image type(s) still to choose") + if left.blocked: + parts.append(f"{left.blocked} folder(s) cannot be tagged") + return ui.status("warn", "Not finished: " + ", ".join(parts) + ".") + + +__all__ = ["_GridSummary"] diff --git a/src/morphobricks_preprocessing/notebook_channels_type.py b/src/morphobricks_preprocessing/notebook_channels_type.py index c3f3559b..84f55de4 100644 --- a/src/morphobricks_preprocessing/notebook_channels_type.py +++ b/src/morphobricks_preprocessing/notebook_channels_type.py @@ -39,12 +39,36 @@ def __init__(self, store: AnswerStore, on_change: Callable[[], None]) -> None: self.notes: dict[UnitKey, widgets.HTML] = {} self.message = "" self._building = False + self.form: dict[UnitKey, str] | None = None + """The per-folder choices not validated yet; None: each choice saves at once (pages). + + The stepper (owner, 25 November 2026) sets it: a choice only changes the form and + :class:`.notebook_image_type_line.ImageTypeLine`'s **Validate** saves every answer in + one draft write. + """ + self.default: Callable[[], str | None] = lambda: None + """The type chosen for all folders in the form (the line's box), when there is one.""" + self.on_form: Callable[[], None] = lambda: None + """Called after a choice changed the form (no save, no redraw).""" def open(self, layouts: Sequence[UnitLayout]) -> None: """Take the units; cells are built by :meth:`cell`.""" + if self.form is not None and layouts is not self.layouts: + self.form.clear() # other folders: the form was for the ones before self.layouts = layouts self.radios, self.notes = {}, {} + def chosen(self, layout: UnitLayout) -> str | None: + """Return what the cell shows: the form's choice, else the box's, else :meth:`shown`. + + Without a form (the pages), the saved answer or the header's colour pre-tick. + """ + if self.form is None: + return self.shown(layout) + if not layout.usable: + return None + return self.form.get(layout.key) or self.default() or self.shown(layout) + def saved(self, key: UnitKey) -> str | None: """Return the type the user answered for a unit (``channels``, ``rgb``), else None.""" unit = self.store.answers().units.get(key) @@ -61,7 +85,7 @@ def proposed(self, layout: UnitLayout) -> bool: def cell(self, layout: UnitLayout) -> widgets.Widget: """Build the radio buttons and the note of one unit.""" radio = widgets.RadioButtons( - options=OPTIONS, value=self.shown(layout), layout=widgets.Layout(width="99%") + options=OPTIONS, value=self.chosen(layout), layout=widgets.Layout(width="99%") ) radio.disabled = not layout.usable note = widgets.HTML(self.note(layout)) @@ -70,10 +94,23 @@ def cell(self, layout: UnitLayout) -> widgets.Widget: return widgets.VBox([radio, note]) def note(self, layout: UnitLayout) -> str: - """Return what is said under a unit's radio buttons.""" + """Return what is said under a unit's radio buttons (the form's choice, if any).""" saved, shown = self.saved(layout.key), self.shown(layout) if not layout.usable: return "" + if self.form is not None and self.chosen(layout) != saved: + saved = shown = self.chosen(layout) # what Validate would record + if saved is None: + return blank_chip("choose one") + if saved == "rgb" and not layout.rgb and layout.three_samples: + return ( + "Not validated yet. The header " + "does not say colour: tick Read these folders as colour under Image " + "type." + ) + warn = (saved == "channels" and layout.rgb) or (saved == "rgb" and not layout.rgb) + said = " The header does not agree: the run refuses it." if warn else "" + return f"Not validated yet.{said}" if saved is None and shown == "rgb": return ( "Pre-ticked: the image header says colour. Not saved " @@ -110,8 +147,19 @@ def overridden(self, layout: UnitLayout) -> bool: return unit is not None and unit.rgb_header_override is True def _chosen(self, layout: UnitLayout, value: str | None) -> None: - """Save the type the user ticked; a refusal is said and the tick is taken back.""" - if self._building or value is None or value == self.saved(layout.key): + """Save the type the user ticked; a refusal is said and the tick is taken back. + + With a form (the stepper) the choice only changes the form and the note under it. + """ + if self._building or value is None: + return + if self.form is not None: + self.form[layout.key] = value + if layout.key in self.notes: + self.notes[layout.key].value = self.note(layout) + self.on_form() + return + if value == self.saved(layout.key): return layouts = self.layouts try: @@ -275,7 +323,7 @@ def _build_rows(self) -> None: [(self._row(u), row_status(units, [u.key], self._settled(u))) for u in ordered] ) proposed = [u.key for u in self.types.layouts if self.types.proposed(u)] - if proposed: + if proposed and self.types.form is None: # with a form, Validate records what is shown button = ui.button( f" Yes, colour (RGB) is right for these {len(proposed)} folder(s)", style="success", diff --git a/src/morphobricks_preprocessing/notebook_image_type_line.py b/src/morphobricks_preprocessing/notebook_image_type_line.py index 3db54d20..3710b351 100644 --- a/src/morphobricks_preprocessing/notebook_image_type_line.py +++ b/src/morphobricks_preprocessing/notebook_image_type_line.py @@ -13,8 +13,18 @@ - **Set per folder…**, collapsed, holds the row of each folder (:class:`.notebook_channels_type.ImageTypeRows`: the same cells, answers and refusals); the rows, and the picture of each folder, are built only once it is opened; -- when the headers **differ**, nothing is pre-filled, one line says how many folders say what, - and the per-folder part opens. +- when the headers **differ**, nothing is pre-filled and one line says how many folders say + what; the one answer for all folders is still offered (owner, 25 November 2026: *separate + stains or markers* answered once for every folder, whatever their channel or image counts), + and the per-folder part opens only when the answers themselves differ. + +After the answer, every folder whose header does not fit it is listed under the line +(:func:`followups`): a header that says colour answered *separate channels*, or one that does +not say colour answered *colour* (with three interleaved samples it is the RGB header override +below, Spec RH1; otherwise the run's ``R_IMAGE_TYPE_CONTRADICTS_HEADER``). They are listed, not +a reason to refuse the others' answer. *Colour (RGB)* for all folders is recorded only when +every folder has three channels; otherwise nothing is written and every folder that cannot be +colour is named. The answers are the per-unit ``image_type`` of the draft, saved through :func:`.channel_answers.with_type` exactly as the per-folder radio buttons save them: clicking @@ -35,7 +45,7 @@ import ipywidgets as widgets from . import notebook_style as ui -from .channel_answers import synced, with_type +from .channel_answers import synced, with_override, with_type from .channel_labels import UnitLayout from .draft_answers import DraftAnswers from .notebook_channels_type import ImageTypeColumn, ImageTypeRows @@ -55,6 +65,36 @@ ) +def followups(layouts: Sequence[UnitLayout], types: ImageTypeColumn) -> list[str]: + """Return a line per answered folder whose header does not fit its answer (the next step). + + The existing rules, said per folder: nothing here records or refuses anything. + """ + out = [] + for layout in layouts: + saved = types.saved(layout.key) + name = " / ".join(p for p in layout.key if p != "single") + unit = types.store.answers().units.get(layout.key) + if saved == "channels" and layout.rgb: + out.append( + f"{name}: its header says colour (RGB) but it is answered separate channels; " + "the run refuses it (R_IMAGE_TYPE_CONTRADICTS_HEADER): answer it colour under " + "Set per folder…, or correct its header" + ) + elif saved == "rgb" and not layout.rgb and layout.three_samples: + if unit is None or not unit.rgb_header_override: + out.append( + f"{name}: three interleaved samples under a header that does not say " + "colour: tick the RGB header override below (RH1)" + ) + elif saved == "rgb" and not layout.rgb: + out.append( + f"{name}: its header says separate channels but it is answered colour; the " + "run refuses it (R_IMAGE_TYPE_CONTRADICTS_HEADER)" + ) + return out + + def counted(values: Sequence[str]) -> str: """Return ``colour (RGB) in 2 folders, separate channels in 10`` for these types.""" found = Counter(values) @@ -93,6 +133,7 @@ def __init__(self, types: ImageTypeColumn, rows: ImageTypeRows) -> None: ) ui.set_visible(self.replace_box, False) self.message = widgets.HTML() + self.followups = widgets.HTML() self.override = RgbOverrideOffer(types) self.per_folder = ui.accordion("Set per folder…", [rows.widget]) # The rows of each folder are built, and their pictures read, only once opened. @@ -106,11 +147,14 @@ def __init__(self, types: ImageTypeColumn, rows: ImageTypeRows) -> None: self.blocker, self.replace_box, self.message, + self.followups, self.override.widget, self.per_folder, ], ) - self.apply.on_click(lambda _: self._use_for_all()) + self.apply.on_click(lambda _: self._clicked()) + types.default = lambda: self.choice.value + types.on_form = self._form_changed self.replace_yes.on_click(lambda _: self._replace()) self.replace_no.on_click(lambda _: self._cancel()) self.choice.observe(lambda _: self._choice_changed(), names="value") @@ -153,7 +197,7 @@ def refresh(self) -> None: self.override.refresh(shown) if not shown: self.line.value = ui.status("info", WAITING) if not self.opened else "" - self.blocker.value = self.message.value = "" + self.blocker.value = self.message.value = self.followups.value = "" self._shown_for = None return saved, suggestion = self.saved(), self.suggestion() @@ -164,8 +208,14 @@ def refresh(self) -> None: self._shown_for = key self.choice.value = one or (suggestion if not answered else None) self.line.value = self._line(saved, answered, one, suggestion) - if suggestion is None or len(set(answered)) > 1 or self.types.message: - self.per_folder.selected_index = 0 # they differ: each folder is shown + later = followups(usable, self.types) + self.followups.value = ( + ui.status("warn", f"Another step for {plural(len(later), 'folder')}:", later) + if later + else "" + ) + if len(set(answered)) > 1 or self.types.message: + self.per_folder.selected_index = 0 # the answers differ: each folder is shown self._choice_changed() def _line( @@ -190,7 +240,10 @@ def _line( return ui.status( "warn", f"The image headers differ: {counted(said)}.", - ["Nothing is proposed: choose the type of each folder below. " + MIXED], + [ + "Nothing is proposed: choose one type for all folders in the box and click " + "Use for all folders, or each folder's type under Set per folder…. " + MIXED + ], ) return ui.status( "info", @@ -198,8 +251,16 @@ def _line( ["Not saved until you click Use for all folders."], ) + @property + def deferred(self) -> bool: + """True with the form of the stepper: choices change the form, Validate saves.""" + return self.types.form is not None + def _choice_changed(self) -> None: """Offer the click for a type that is not already every folder's answer.""" + if self.deferred: + self._form_changed(cells=True) + return self._cancel() value, saved = self.choice.value, self.saved() everywhere = value is not None and all(s == value for s in saved) @@ -209,8 +270,131 @@ def _choice_changed(self) -> None: ["choose a type in the box, or set each folder below"] if value is None else [] ) + # The form (the stepper: owner, 25 November 2026) ----------------------------------- + + def final(self) -> dict: + """Return the type Validate would record for each usable folder (None: not chosen).""" + return {u.key: self.types.chosen(u) for u in self._usable()} + + def _form_changed(self, cells: bool = False) -> None: + """Update what the form shows in place after a choice: no save, no redraw. + + ``cells``: the box changed, so the folders without their own choice show it too. + """ + self._cancel() + types = self.types + if cells: + types._building = True + try: + for layout in self._usable(): + radio = types.radios.get(layout.key) + if radio is not None and layout.key not in types.form: + radio.value = types.chosen(layout) + finally: + types._building = False + for layout in self._usable(): + if layout.key in types.notes: + types.notes[layout.key].value = types.note(layout) + ui.set_visible(self.apply, True) + final = self.final() + missing = [k for k, v in final.items() if v is None] + # saved and unchanged since: said on the button, which waits for a change (review F5) + done = ( + bool(final) + and not missing + and self.override.pending is None + and all(self.types.saved(k) == v for k, v in final.items()) + ) + self.apply.description = " Validated ✓" if done else " Validate" + self.apply.disabled = bool(missing) or done + self.blocker.value = blocked_line( + [f"choose a type in the box, or set each folder below ({len(missing)} left)"] + if missing + else [] + ) + self.override.refresh(True) + + def _validate(self, replace_ok: bool = False) -> bool: + """Check the form and save every image-type answer in one draft write. + + Every folder needs a type; colour only for folders with three channels (all or none, + naming each); replacing answers already saved asks first. The folders whose header does + not fit their answer are listed afterwards (:func:`followups`), never a refusal here. + """ + final, usable = self.final(), self._usable() + missing = [u for u in usable if final[u.key] is None] + if missing: + self.message.value = ui.status( + "error", "Not saved: choose the type of every folder.", self._names(missing) + ) + return False + not3 = [u for u in usable if final[u.key] == "rgb" and u.channels != 3] + if not3: + self.message.value = ui.status( + "error", + "Nothing was changed: a colour image has 3 channels (RGB).", + [ + f"{n} ({u.channels} channels)" + for n, u in zip(self._names(not3), not3, strict=True) + ], + ) + return False + others = [u for u in usable if self.types.saved(u.key) not in (None, final[u.key])] + if others and not replace_ok: + self._pending = "form" + self.replace_text.value = ui.status( + "warn", + f"Change the type of {plural(len(others), 'folder')} already answered? " + "Nothing is written until you click Replace them.", + ["Their channel tags are cleared: a channel is tagged again after its type."], + ) + ui.set_visible(self.replace_box, True) + return False + return self._write_form(final) + + @staticmethod + def _names(layouts: Sequence[UnitLayout]) -> list[str]: + return [" / ".join(p for p in u.key if p != "single") for u in layouts] + + def _write_form(self, final: dict) -> bool: + """Save the form's types (and the override box) in one draft write.""" + store, layouts, usable = self.types.store, self.types.layouts, self._usable() + override = self.override.pending + offered = {u.key for u in self.override.offered()} + + def change(answers: DraftAnswers) -> DraftAnswers: + for layout in usable: + if self.types.saved(layout.key) != final[layout.key]: + answers = with_type(answers, layout, final[layout.key]) + if override is not None: + for layout in usable: + if layout.key in offered and final[layout.key] == "rgb": + answers = with_override(answers, layout, override) + return synced(answers, layouts) + + try: + ok = save_change(store, change) + except ValueError as exc: + self.message.value = ui.status("error", "Nothing was changed.", [str(exc)]) + return False + if not ok: + self.message.value = ui.status("error", "Not saved.", [store.refusal()]) + return False + self.types.form.clear() + self.override.pending = None + self.message.value = self.types.message = "" + self.types._on_change() # the channel step opens on the saved types + return True + # The click --------------------------------------------------------------------------- + def _clicked(self) -> None: + """Validate the form (the stepper), or record the box's type for every folder.""" + if self.deferred: + self._validate() + else: + self._use_for_all() + def _use_for_all(self) -> None: """Record the chosen type for every folder, asking first when it replaces answers.""" value = self.choice.value @@ -232,7 +416,9 @@ def _use_for_all(self) -> None: def _replace(self) -> None: pending = self._pending self._cancel() - if pending is not None: + if pending == "form": + self._validate(replace_ok=True) + elif pending is not None: self._write(pending) def _cancel(self) -> None: @@ -242,6 +428,19 @@ def _cancel(self) -> None: def _write(self, value: str) -> bool: """Save ``value`` as the type of every usable folder, all or none; say a refusal.""" store, usable, layouts = self.types.store, self._usable(), self.types.layouts + if value == "rgb": + other = [u for u in usable if u.channels != 3] + if other: # all or none: every folder that cannot be colour is named + names = [ + f"{' / '.join(p for p in u.key if p != 'single')} ({u.channels} channels)" + for u in other + ] + self.message.value = ui.status( + "error", + "Nothing was changed: a colour image has 3 channels (RGB).", + names, + ) + return False def change(answers: DraftAnswers) -> DraftAnswers: for layout in usable: diff --git a/src/morphobricks_preprocessing/notebook_rgb_override.py b/src/morphobricks_preprocessing/notebook_rgb_override.py index ffe34b43..c147b0b1 100644 --- a/src/morphobricks_preprocessing/notebook_rgb_override.py +++ b/src/morphobricks_preprocessing/notebook_rgb_override.py @@ -51,6 +51,8 @@ class RgbOverrideOffer: def __init__(self, types: ImageTypeColumn) -> None: self.types = types self._building = False + self.pending: bool | None = None + """With the image-type form (the stepper): the box's state not validated yet.""" self.text = widgets.HTML() self.box = widgets.Checkbox( value=False, description=LABEL, indent=False, layout=widgets.Layout(width="99%") @@ -67,13 +69,20 @@ def offered(self) -> list[UnitLayout]: return [u for u in self.types.layouts if u.usable and u.three_samples] def colour(self) -> list[UnitLayout]: - """Return the offered folders the user answered colour (RGB): the box applies to them.""" + """Return the offered folders the user answered colour (RGB): the box applies to them. + + With the image-type form (the stepper), the ones the form says colour. + """ + if self.types.form is not None: + return [u for u in self.offered() if self.types.chosen(u) == "rgb"] return [u for u in self.offered() if self.types.saved(u.key) == "rgb"] def recorded(self) -> list[UnitLayout]: """Return the folders the box applies to that have the override recorded.""" units = self.types.store.answers().units - return [u for u in self.colour() if units[u.key].rgb_header_override is True] + return [ + u for u in self.colour() if u.key in units and units[u.key].rgb_header_override is True + ] def ticked(self) -> bool: """Return True when every folder the box applies to has the override recorded.""" @@ -94,7 +103,7 @@ def refresh(self, shown: bool) -> None: raw=True, ) self._building = True - self.box.value = self.ticked() + self.box.value = self.ticked() if self.pending is None else self.pending self._building = False self.box.disabled = not colour self.blocker.value = blocked_line([] if colour else [CHOOSE_COLOUR]) @@ -120,6 +129,10 @@ def _clicked(self, value: bool) -> None: """Record or take back the override of the colour folders; say a refusal.""" if self._building: return + if self.types.form is not None: # the form: recorded by Validate, with the types + self.pending = value + self.types.on_form() + return store, colour, layouts = self.types.store, self.colour(), self.types.layouts def change(answers: DraftAnswers) -> DraftAnswers: diff --git a/src/morphobricks_preprocessing/notebook_steps.py b/src/morphobricks_preprocessing/notebook_steps.py index 681c84bc..625175bd 100644 --- a/src/morphobricks_preprocessing/notebook_steps.py +++ b/src/morphobricks_preprocessing/notebook_steps.py @@ -116,6 +116,9 @@ def steps(self) -> widgets.Widget: if getattr(self, "_stepper", None) is not None: return self._stepper.widget self.channel_grid.place_types = False # the image type has its own card on Channels + self.channel_grid.guided = self.channel_grid.GUIDED # a question, rows, Submit (25 Nov) + # the image type too: choices change a form, Validate saves them in one write (25 Nov) + self.channel_types.form = {} if self.channel_grid.guided else None if ui.is_visible(self.channel_grid.widget): self.channel_grid.refresh() for box in (self.folder_next, self.axis_next): diff --git a/src/morphobricks_preprocessing/repeat_tags.py b/src/morphobricks_preprocessing/repeat_tags.py index 8d9c7657..43513151 100644 --- a/src/morphobricks_preprocessing/repeat_tags.py +++ b/src/morphobricks_preprocessing/repeat_tags.py @@ -83,7 +83,7 @@ def recount(tags: Sequence[str | None], layout: UnitLayout) -> str | None: The old tags are never applied, cut or padded to the new count: every channel is chosen again (the override editor opens with blank dropdowns). """ - if counted(tags, layout): + if counted(tags, layout) or not tags: # no row's tags recorded (images disagreed): none return None return ( f"its channel count changed ({len(tags)} at the refusal, {layout.channels} now): " diff --git a/tests/conftest.py b/tests/conftest.py index e6487d81..c92d0869 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -118,3 +118,18 @@ def statement_off(monkeypatch): from morphobricks_preprocessing.notebook_channels_grid import TagGrid monkeypatch.setattr(TagGrid, "SAME_CHANNELS", False) + + +@pytest.fixture +def legacy_grid(monkeypatch): + """Show the per-unit tag grid in the stepper too, instead of the guided step (25 Nov 2026). + + The shipped notebook's stepper shows the guided channel step (a question, a few rows, one + Submit; ``tests/test_notebook_channel_step_acceptance.py``). The pages of the Python + interface keep the per-unit grid, and the tests that drive that grid through the stepper + (its blocks, matrix and repeat rows, and the #376 refusal machinery they share with the + guided Submit) pin it with this fixture. + """ + from morphobricks_preprocessing.notebook_channels_grid import TagGrid + + monkeypatch.setattr(TagGrid, "GUIDED", False) diff --git a/tests/test_channel_scope.py b/tests/test_channel_scope.py new file mode 100644 index 00000000..167117a7 --- /dev/null +++ b/tests/test_channel_scope.py @@ -0,0 +1,127 @@ +"""The rows the guided *Tag channels* step opens for each answer (pure, owner 25 Nov 2026).""" + +from __future__ import annotations + +from dataclasses import replace + +import pytest + +from morphobricks_preprocessing.channel_labels import UnitLayout +from morphobricks_preprocessing.channel_scope import ( + FROM_BROADER, + FROM_CHOICE, + FROM_HEADER, + FROM_NONE, + FROM_SAVED, + REPEAT, + UNIT, + WHOLE, + apart, + counts, + form_rows, + row_error, + scope_of_draft, + seed, + taggable, +) +from morphobricks_preprocessing.draft_answers import DraftAnswers, LayoutAnswer, UnitAnswer + +TAGS = ("DNA", "ACTIN", "PHASE") +KEYS = [(c, f"rep{r}", "single") for c in ("ctrl", "drug") for r in (1, 2, 10)] + + +def layout(key, count=3, names=None, uniform=True): + return UnitLayout(key, "a.tif", count, tuple(names or (None,) * count), uniform=uniform) + + +def answers(units=None): + return DraftAnswers("absent", "0" * 40, units=units or {}) + + +def typed(layouts, kind="channels"): + return {u.key: UnitAnswer((None,) * u.channels, kind) for u in layouts} + + +def test_same_count_whole_is_one_row_repeat_one_per_repeat_unit_one_per_unit(): + units = [layout(k) for k in KEYS] + saved = typed(units) + assert counts(units, saved) == [3] + assert [r.key for r in form_rows(units, saved, WHOLE)] == [(WHOLE, 3)] + assert [r.key for r in form_rows(units, saved, REPEAT)] == [ + (REPEAT, "rep1", 3), + (REPEAT, "rep2", 3), + (REPEAT, "rep10", 3), # natural order: rep2 before rep10 + ] + assert len(form_rows(units, saved, UNIT)) == len(KEYS) + whole = form_rows(units, saved, WHOLE)[0] + assert len(whole.units) == len(KEYS) + + +def test_mixed_counts_whole_is_one_row_per_count(): + units = [layout(k, 4 if k[1] == "rep2" else 3) for k in KEYS] + saved = typed(units) + assert counts(units, saved) == [3, 4] + rows = form_rows(units, saved, WHOLE) + assert [(r.key, len(r.units)) for r in rows] == [((WHOLE, 3), 4), ((WHOLE, 4), 2)] + assert [r.key for r in form_rows(units, saved, REPEAT)] == [ + (REPEAT, "rep1", 3), + (REPEAT, "rep2", 4), + (REPEAT, "rep10", 3), + ] + + +def test_colour_units_and_units_whose_images_disagree_are_in_no_row(): + units = [layout(k) for k in KEYS] + odd = replace(units[1], uniform=False) + units[1] = odd + saved = typed(units) + saved[units[0].key] = UnitAnswer(("R", "G", "B"), "rgb") + assert units[0] not in taggable(units, saved) + assert apart(taggable(units, saved)) == [odd] + rowed = {u.key for r in form_rows(units, saved, UNIT) for u in r.units} + assert rowed == {u.key for u in units[2:]} + + +def test_a_row_shows_the_choice_then_saved_then_a_broader_choice_then_header_names(): + units = [layout(k, names=TAGS) for k in KEYS] + saved = typed(units) + row = form_rows(units, saved, UNIT)[0] + key = row.units[0].key + labels = list(TAGS) + assert seed(row, {}, answers(saved), labels) == (list(TAGS), FROM_HEADER) + pending = {(WHOLE, 3): ["PHASE", "DNA", "ACTIN"]} + assert seed(row, pending, answers(saved), labels) == (["PHASE", "DNA", "ACTIN"], FROM_BROADER) + pending[(REPEAT, key[1], 3)] = ["DNA", "PHASE", "ACTIN"] + assert seed(row, pending, answers(saved), labels)[0] == ["DNA", "PHASE", "ACTIN"] + saved[key] = UnitAnswer(("ACTIN", "DNA", "PHASE"), "channels") + assert seed(row, {}, answers(saved), labels) == (["ACTIN", "DNA", "PHASE"], FROM_SAVED) + # the row's own saved tags rank above a broader choice (review of #546 at e40f1ad) + assert seed(row, pending, answers(saved), labels) == (["ACTIN", "DNA", "PHASE"], FROM_SAVED) + pending[row.key] = ["DNA", None, None] + assert seed(row, pending, answers(saved), labels) == (["DNA", None, None], FROM_CHOICE) + assert seed(row, pending, answers(saved), ["DNA"])[0] == ["DNA", None, None] # label gone + + +def test_header_names_propose_only_when_every_unit_of_the_row_names_the_same_labels(): + units = [layout(k, names=TAGS) for k in KEYS] + units[3] = layout(KEYS[3], names=("ACTIN", "DNA", "PHASE")) + saved = typed(units) + row = form_rows(units, saved, WHOLE)[0] + assert seed(row, {}, answers(saved), list(TAGS)) == ([None] * 3, FROM_NONE) + + +def test_a_row_is_refused_until_every_channel_is_tagged_with_each_label_once(): + assert row_error(["DNA", None, "PHASE"]) == "tag every channel" + assert row_error(["DNA", "DNA", "PHASE"]) == "each label once" + assert row_error(list(TAGS)) is None + + +def test_only_a_fast_mode_draft_answers_the_whole_dataset_question(): + assert scope_of_draft(answers()) is None + stated = replace(answers(), channel_layout=LayoutAnswer(TAGS, "channels", "2026-11-25")) + assert scope_of_draft(stated) == WHOLE + + +def test_an_unknown_scope_is_refused(): + with pytest.raises(ValueError, match="unknown scope"): + form_rows([], {}, "everything") diff --git a/tests/test_header_name_confirm.py b/tests/test_header_name_confirm.py index 4f5aa560..708ea62f 100644 --- a/tests/test_header_name_confirm.py +++ b/tests/test_header_name_confirm.py @@ -26,6 +26,9 @@ from test_notebook_axes_quick import stepper # noqa: E402 from test_notebook_prerelease import _tag, _text # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + GONE = "drug/rep2" diff --git a/tests/test_image_viewer.py b/tests/test_image_viewer.py index 020b6ae3..890de120 100644 --- a/tests/test_image_viewer.py +++ b/tests/test_image_viewer.py @@ -33,6 +33,9 @@ from test_notebook_axes_quick import stepper # noqa: E402 from test_notebook_check_save import answer_all, exp # noqa: E402, F401 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def _text(text): return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", text))).strip() diff --git a/tests/test_notebook_axes_quick.py b/tests/test_notebook_axes_quick.py index 46334054..f1459b63 100644 --- a/tests/test_notebook_axes_quick.py +++ b/tests/test_notebook_axes_quick.py @@ -18,6 +18,9 @@ from morphobricks_preprocessing import notebook_style as ui # noqa: E402 from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def stepper(root, masks, out): nb = PreprocessingNotebook(str(root), output_folder=str(out)) diff --git a/tests/test_notebook_channel_guide.py b/tests/test_notebook_channel_guide.py new file mode 100644 index 00000000..a55c4f77 --- /dev/null +++ b/tests/test_notebook_channel_guide.py @@ -0,0 +1,204 @@ +"""The guided channel step: Submit is the only save, and a choice never lags or resets (25 Nov). + +The owner's Colab test of the v0.9.0 candidate: every dropdown change saved and redrew the +page (lag), there was one row per unit even when every image had the same channels, and values +jumped after picking them. In the shipped notebook (the stepper) the step is now a question, a +few rows and one Submit (:mod:`.notebook_channels_guide`); these tests pin what fixes each +complaint and that Submit keeps the #376 guarantees (one draft write for tags and review, header +contradictions refused, R_DRAFT_CHANGED). +""" + +from __future__ import annotations + +import pytest + +from morphobricks_preprocessing.description_file import DRAFT_FILENAME +from morphobricks_preprocessing.draft_format import answers_from_bytes + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +import ipywidgets as widgets # noqa: E402 + +from test_notebook_channel_step_acceptance import ( # noqa: E402 + TAGS3, + UNITS, + choose, + experiment, + folder, + opened, + shown, +) + +OTHER_ORDER = ["ACTIN", "DNA", "PHASE"] + + +def dropdowns(widget): + """Yield every dropdown in a widget tree.""" + if isinstance(widget, widgets.Dropdown): + yield widget + for child in getattr(widget, "children", ()): + yield from dropdowns(child) + + +def counting(nb, monkeypatch): + """Count the draft writes and the redraws of the channel card from now on.""" + calls = {"saves": 0, "refresh": 0} + save, refresh = nb._save_answers, nb.channel_grid.refresh + + def counted_save(*args, **kwargs): + calls["saves"] += 1 + return save(*args, **kwargs) + + def counted_refresh(): + calls["refresh"] += 1 + return refresh() + + monkeypatch.setattr(nb, "_save_answers", counted_save) + monkeypatch.setattr(nb.channel_grid, "refresh", counted_refresh) + return calls + + +def test_a_dropdown_change_saves_nothing_and_redraws_nothing(tmp_path, monkeypatch): + exp = experiment(tmp_path) + nb = opened(*exp, TAGS3) + guide = nb.channel_grid.guide + guide.same.value = "yes" + calls, renders = counting(nb, monkeypatch), guide.renders + drops = guide.drops[("whole", 3)] + choose(nb, ("whole", 3), TAGS3) + assert calls == {"saves": 0, "refresh": 0} and guide.renders == renders + assert guide.drops[("whole", 3)] is drops # the very same widgets: nothing rebuilt + assert [d.value for d in drops] == TAGS3 + + +def test_submit_is_one_draft_write_holding_tags_review_and_statement(tmp_path, monkeypatch): + swapped = ("drug", "rep2", "single") + exp = experiment(tmp_path, names=lambda key, n: OTHER_ORDER if key == swapped else TAGS3) + nb = opened(*exp, TAGS3) + guide = nb.channel_grid.guide + guide.same.value = "yes" + choose(nb, ("whole", 3), TAGS3) + calls = counting(nb, monkeypatch) + assert guide.submit() + assert calls["saves"] == 1 # tags, aliases, tag review and channel_layout: one write + saved = answers_from_bytes((exp[2] / DRAFT_FILENAME).read_bytes()) + assert saved.channel_layout.channels == tuple(TAGS3) + assert set(saved.tag_review.refused) == {swapped} + filled = {k for k, u in saved.units.items() if u.channels == tuple(TAGS3)} + assert filled == set(UNITS) - {swapped} + assert all(saved.units[k].channels_from == "experiment" for k in filled) + assert saved.channels["DNA"].header_names == ("DNA",) # the confirmed header evidence + + +def test_choices_survive_any_redraw_of_the_card(tmp_path): + exp = experiment(tmp_path, count=lambda key: 4 if key[1] == "rep2" else 3) + nb = opened(*exp, [*TAGS3, "EXTRA"]) + guide = nb.channel_grid.guide + guide.same.value = "yes" + choose(nb, ("whole", 3), OTHER_ORDER) + guide.drops[("whole", 4)][0].value = "EXTRA" + nb.channel_grid.refresh() # what a type change, a label or a listed unit redraws + nb._refresh_channels() + assert shown(nb) == {("whole", 3): OTHER_ORDER, ("whole", 4): ["EXTRA", None, None, None]} + assert "tag every channel" in guide.notes[("whole", 4)].value + + +def test_an_incomplete_row_or_a_label_twice_saves_nothing(tmp_path, monkeypatch): + exp = experiment(tmp_path, count=lambda key: 4 if key[1] == "rep2" else 3) + nb = opened(*exp, [*TAGS3, "EXTRA"]) + guide = nb.channel_grid.guide + guide.same.value = "yes" + choose(nb, ("whole", 3), ["DNA", "DNA", "PHASE"]) + calls = counting(nb, monkeypatch) + assert not guide.submit() + assert calls["saves"] == 0 + assert "3 channels: each label once" in guide.message.value + assert "4 channels: tag every channel" in guide.message.value + guide.same.value = None + assert not guide.submit() and "Answer the question" in guide.message.value + + +def test_per_repeat_submit_refuses_a_contradicting_unit_and_fills_the_rest(tmp_path): + odd = ("ctrl", "rep1", "single") + exp = experiment(tmp_path, names=lambda key, n: OTHER_ORDER if key == odd else TAGS3) + nb = opened(*exp, TAGS3) + guide, rows = nb.channel_grid.guide, nb.channel_grid.by_repeat + guide.same.value = "no" + guide.narrow.value = "repeat" + assert len(guide.rows) == 3 # one row per repeat, not one per unit + for rep in ("rep1", "rep2", "rep3"): + choose(nb, ("repeat", rep, 3), TAGS3) + assert guide.submit() + assert set(rows.listed()) == {odd} + units = nb.draft_answers.units + assert all(units[k].channels == tuple(TAGS3) for k in UNITS if k != odd) + assert nb.draft_answers.channel_layout is None # per repeat: a strict file + # a deliberate tag of that unit alone, fitting its header, is an action on it + guide.narrow.value = "unit" + assert shown(nb)[("unit", odd)] == TAGS3 # from its repeat's choice, not saved + choose(nb, ("unit", odd), OTHER_ORDER) + assert guide.submit() + assert rows.listed() == {} + assert nb.draft_answers.units[odd].channels == tuple(OTHER_ORDER) + + +def test_a_header_that_still_contradicts_stays_listed_whatever_is_submitted(tmp_path): + odd = ("ctrl", "rep1", "single") + exp = experiment(tmp_path, names=lambda key, n: OTHER_ORDER if key == odd else TAGS3) + nb = opened(*exp, TAGS3) + guide, rows = nb.channel_grid.guide, nb.channel_grid.by_repeat + guide.same.value = "yes" + choose(nb, ("whole", 3), TAGS3) + assert guide.submit() and set(rows.listed()) == {odd} + assert guide.submit() and set(rows.listed()) == {odd} # again: never filled, never dropped + guide.same.value = "no" + guide.narrow.value = "unit" + choose(nb, ("unit", odd), TAGS3) # contradicts its own header names + assert guide.submit() and set(rows.listed()) == {odd} + assert not any(nb.draft_answers.units.get(odd, None).channels or ()) + + +def test_a_draft_changed_by_another_notebook_refuses_submit(tmp_path): + exp = experiment(tmp_path) + a = opened(*exp, TAGS3) + b = opened(*exp, TAGS3) + a.channel_grid.guide.same.value = "yes" + choose(a, ("whole", 3), TAGS3) + assert a.channel_grid.guide.submit() + saved = (exp[2] / DRAFT_FILENAME).read_bytes() + guide = b.channel_grid.guide + guide.same.value = "no" + guide.narrow.value = "repeat" + for rep in ("rep1", "rep2", "rep3"): + choose(b, ("repeat", rep, 3), OTHER_ORDER) + assert not guide.submit() + assert (exp[2] / DRAFT_FILENAME).read_bytes() == saved # A's answers, byte for byte + assert "changed since this notebook read or saved it" in guide.message.value + + +def test_a_reopened_fast_mode_draft_answers_yes_and_shows_its_saved_tags(tmp_path): + exp = experiment(tmp_path) + nb = opened(*exp, TAGS3) + nb.channel_grid.guide.same.value = "yes" + choose(nb, ("whole", 3), OTHER_ORDER) + assert nb.channel_grid.guide.submit() + again = opened(*exp, []) + guide = again.channel_grid.guide + assert guide.same.value == "yes" + assert shown(again) == {("whole", 3): OTHER_ORDER} + assert "Saved tags" in guide.saved_box.value + assert folder(UNITS[0]).split("/")[0] in guide.saved_box.value + + +def test_the_number_of_rows_follows_the_answer(tmp_path): + exp = experiment(tmp_path) + nb = opened(*exp, TAGS3) + guide = nb.channel_grid.guide + counts = [] + for same, narrow in (("yes", None), ("no", "repeat"), ("no", "unit")): + guide.same.value = same + guide.narrow.value = narrow + counts.append(len([d for d in guide.drops.values()])) + assert counts == [1, 3, len(UNITS)] + assert not list(dropdowns(nb.channel_grid.blocks)) # no per-unit grid in the stepper diff --git a/tests/test_notebook_channel_guide_flows.py b/tests/test_notebook_channel_guide_flows.py new file mode 100644 index 00000000..4934cbe7 --- /dev/null +++ b/tests/test_notebook_channel_guide_flows.py @@ -0,0 +1,237 @@ +"""Saved-experiment flows through the guided channel step (review of #546, F2). + +The modules that drive the per-unit grid through the stepper pin it (``legacy_grid``). These +tests take their flows through the guided step instead, as the shipped notebook does: the #281 +header-name loss and its click, the re-confirmation scope of a removal (#279), what a change of +answer between fast and strict mode does to the aliases (the guided step's counterpart of the +untick tests), and the pre-release header rename and channel swap (#257). +""" + +from __future__ import annotations + +import json +import re +import shutil +from datetime import date + +import pytest + +from channel_images import write_channels +from morphobricks_preprocessing.description_file import RECORDS_FILENAME +from test_notebook_check_save import FOLDERS, KINDS, exp # noqa: F401 + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +from morphobricks_preprocessing import notebook_check_save # noqa: E402 +from morphobricks_preprocessing import notebook_style as ui # noqa: E402 +from test_notebook_axes_quick import stepper # noqa: E402 +from test_notebook_channel_step_acceptance import choose, finish, published # noqa: E402 + +TAGS = ["DNA", "ACTIN", "PHASE"] +KEY = ("ctrl", "rep1", "single") +GONE = "drug/rep2" + + +def _text(value): + return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", value)) + + +def submit(nb, scope="yes", rows=None): + """Answer the image type and labels if needed, then the guide, and Submit.""" + if not nb.type_line.complete: + nb.type_line.apply.click() + card = nb.channel_labels + if not card.confirmed: + while len(card.rows) < len(TAGS): + card.add_button.click() + for row, text in zip(card.rows, TAGS, strict=False): + row.id_box.value = text + card.confirm.button.click() + guide = nb.channel_grid.guide + if scope == "yes": + guide.same.value = "yes" + else: + guide.same.value = "no" + guide.narrow.value = scope + for key, tags in (rows or ({("whole", 3): TAGS} if scope == "yes" else {})).items(): + choose(nb, key, tags) + return guide.submit() + + +def _open(exp): # noqa: F811 + nb = stepper(*exp) + nb.quick_confirm.click() + return nb + + +def _saved(exp, names=None): # noqa: F811 + """Save the experiment through the guided step; ``names`` rewrites headers first.""" + for name, given in (names or {}).items(): + write_channels(exp[0] / name / "a.tif", given, KINDS, seed=FOLDERS.index(name) + 1) + first = _open(exp) + if names: # headers that differ between units: tagged unit by unit (deliberate hand-tags) + keys = [(*name.split("/"), "single") for name in FOLDERS] + assert submit(first, "unit", {("unit", tuple(k)): TAGS for k in keys}) + else: + assert submit(first) + finish(first) + assert first.save_experiment(), _text(first.save_status.value) + return first + + +def _drop(exp, gone): # noqa: F811 + shutil.rmtree(exp[0] / gone) + shutil.rmtree(exp[1] / "Nuclei" / gone) + + +def _records(exp): # noqa: F811 + path = exp[2] / RECORDS_FILENAME + return [json.loads(x) for x in path.read_text().splitlines()] if path.exists() else [] + + +def _remove(nb): + finish(nb) + (row,) = nb.removals_box.children + row.children[1].click() # Yes, remove + nb._refresh_check_save() + + +# --- #281: a lost header name is confirmed by its own click ------------------------------------- + + +def test_281_the_dead_end_is_resolved_by_the_click_through_the_guided_step(exp): # noqa: F811 + _saved(exp, {"ctrl/rep1": ["Hoechst", "Actin", "Ch3"]}) + write_channels(exp[0] / "ctrl/rep1/a.tif", ["DAPI", "Actin", "Ch3"], KINDS, seed=1) + _drop(exp, GONE) + nb = _open(exp) + _remove(nb) + assert nb.save_experiment(), _text(nb.save_status.value) + assert nb._published().description.channels["DNA"].header_names == ("DAPI", "Hoechst") + before = _records(exp) + later = _open(exp) + guide = later.channel_grid.guide + assert (guide.same.value, guide.narrow.value) == ("no", "repeat") # from the saved tags + assert submit(later, "repeat") # every unit tagged again: "Hoechst" is in no cell now + finish(later) + assert later.draft_answers.channels["DNA"].header_names == ("DAPI",) + change = "DNA: header names “DAPI”, “Hoechst” → “DAPI”" + assert ui.is_visible(later.names_box) and not later.names_confirm.value # nothing ticked + assert change in _text(later.names_list.value) + assert later.save_button.disabled and not later.save_experiment() + assert _records(exp) == before + later.names_confirm.button.click() # Yes, this header name changed + assert later.save_experiment(), _text(later.save_status.value) + records = _records(exp)[len(before) :] + assert [(r["old_id"], r["new_id"], r["type"]) for r in records] == [ + ("DNA", None, "reconfirmation") + ] + assert later._published().description.channels["DNA"].header_names == ("DAPI",) + + +# --- #279: a removal re-confirms only the change it answers ------------------------------------- + + +def test_279_a_removal_never_accepts_a_name_lost_in_a_folder_still_there(exp): # noqa: F811 + _saved(exp, {"ctrl/rep1": ["Hoechst", "Actin", "Ch3"]}) + write_channels(exp[0] / "ctrl/rep1/a.tif", ["Nuc", "Actin", "Ch3"], KINDS, seed=1) + _drop(exp, GONE) + nb = _open(exp) + before = len(_records(exp)) + assert submit(nb, "repeat") # the guided re-tag: Hoechst is no longer a name of DNA + assert "Hoechst" not in (nb.draft_answers.channels["DNA"].header_names or ()) + _remove(nb) + change = "DNA: header names “DAPI”, “Hoechst” → “DAPI”, “Nuc”" + assert ui.is_visible(nb.names_box) and not nb.names_confirm.value + assert change in _text(nb.names_list.value) + assert nb.save_button.disabled and not nb.save_experiment() + assert "R_CONFIRMED_ID_CHANGED at channels.DNA" in _text(nb.checks.value) + assert len(_records(exp)) == before + nb.names_confirm.button.click() + assert nb.save_experiment(), _text(nb.save_status.value) + assert nb._published().description.channels["DNA"].header_names == ("DAPI", "Nuc") + + +# --- the aliases when the answer moves between fast and strict mode ----------------------------- + + +def test_moving_between_fast_and_strict_keeps_exactly_the_aliases_of_tagged_cells(exp): # noqa: F811 + nb = _open(exp) + assert submit(nb) # Yes: fast mode + aliases = {k: c.header_names for k, c in nb.draft_answers.channels.items()} + assert aliases == {"DNA": ("DAPI",), "ACTIN": ("Actin",), "PHASE": ("Ch3",)} + assert nb.draft_answers.channel_layout is not None + assert submit(nb, "repeat") # No, per repeat: each row starts from the Yes choice + answers = nb.draft_answers + assert answers.channel_layout is None and all( + u.channels_from is None for u in answers.units.values() + ) + assert {k: c.header_names for k, c in answers.channels.items()} == aliases + # a strict per-unit order that contradicts the saved aliases is refused, not saved + rows = {("unit", k): list(u.channels) for k, u in answers.units.items()} + rows[("unit", KEY)] = ["ACTIN", "DNA", "PHASE"] + assert submit(nb, "unit", rows) + assert set(nb.channel_grid.by_repeat.listed()) == {KEY} + assert nb.draft_answers.units[KEY].channels == tuple(TAGS) # never reordered + assert {k: c.header_names for k, c in nb.draft_answers.channels.items()} == aliases + nb.channel_grid.by_repeat.override.buttons[KEY].click() # its own tags, confirmed + for index, tag in enumerate(TAGS): + nb.channel_grid.by_repeat.override.cells[(KEY, index)].value = tag + assert nb.channel_grid.by_repeat.override.confirm() + assert submit(nb) # back to Yes: fast mode again, the same aliases + assert nb.draft_answers.channel_layout.channels == tuple(TAGS) + assert {k: c.header_names for k, c in nb.draft_answers.channels.items()} == aliases + finish(nb) + assert nb.save_experiment() + published(exp[2]) # the Spec's reference validator + + +# --- #257: a header rename and a channel swap on a saved experiment ----------------------------- + + +class _FirstOfJanuary(date): + @classmethod + def today(cls): + return date(2026, 1, 1) + + +SAVED_ON = "2026-01-01" + + +def _saved_long_ago(exp, monkeypatch, names): # noqa: F811 + monkeypatch.setattr(notebook_check_save, "date", _FirstOfJanuary) + _saved(exp) + monkeypatch.setattr(notebook_check_save, "date", date) + write_channels(exp[0] / "ctrl/rep1/a.tif", names, KINDS, seed=1) + return _open(exp) + + +def _dates(nb): + return {label: r.confirmed_on for label, r in nb.draft_answers.repeats.items()} + + +def test_257_a_rename_resolved_by_submit_keeps_the_dates_saves_and_runs(exp, monkeypatch): # noqa: F811 + nb = _saved_long_ago(exp, monkeypatch, ["Hoechst", "Actin", "Ch3"]) + assert submit(nb) + assert set(nb.draft_answers.channels["DNA"].header_names) == {"DAPI", "Hoechst"} + assert _dates(nb) == {"rep1": SAVED_ON, "rep2": SAVED_ON} # not reopened: kept + finish(nb) + assert nb.save_experiment(), _text(nb.save_status.value) + assert nb.run().written + + +def test_257_a_swap_is_refused_on_submit_and_released_by_its_own_row(exp, monkeypatch): # noqa: F811 + nb = _saved_long_ago(exp, monkeypatch, ["Actin", "DAPI", "Ch3"]) + assert submit(nb) # the saved aliases say ACTIN, DNA at C0, C1: contradicts the row + rows = nb.channel_grid.by_repeat + assert set(rows.listed()) == {KEY} + assert nb.draft_answers.units[KEY].channels == tuple(TAGS) # never reordered + finish(nb) + assert nb.save_button.disabled or not nb.save_experiment() + unit_rows = {("unit", k): list(u.channels) for k, u in nb.draft_answers.units.items()} + unit_rows[("unit", KEY)] = ["ACTIN", "DNA", "PHASE"] + assert submit(nb, "unit", unit_rows) # a row of its own that fits its header + assert rows.listed() == {} + assert nb.draft_answers.units[KEY].channels == ("ACTIN", "DNA", "PHASE") + assert None in _dates(nb).values() # its repeat's list changed: asked again + assert ui.is_visible(nb.moves_box) and not nb.moves_confirm.value # the move, unticked diff --git a/tests/test_notebook_channel_guide_marks.py b/tests/test_notebook_channel_guide_marks.py new file mode 100644 index 00000000..50956e6f --- /dev/null +++ b/tests/test_notebook_channel_guide_marks.py @@ -0,0 +1,125 @@ +"""What the guided channel step records and says (review of #546, F4 and F5). + +F4: a unit whose own images disagree is in no row, so no row's tags are recorded for it (on the +reviewed head it was refused with the tags of the first row of its channel count, another +repeat's for a per-repeat answer), and the narrowing choice names the *biological repeat +folder*. F5: a row filled from a broader choice says so, and the image type's button reads +*Validated ✓* once the answer is saved, until a choice changes. +""" + +from __future__ import annotations + +import pytest + +from channel_images import write_channels, write_masks +from morphobricks_preprocessing.description_file import DRAFT_FILENAME +from morphobricks_preprocessing.draft_format import answers_from_bytes + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +import ipywidgets as widgets # noqa: E402 + +from morphobricks_preprocessing.notebook_channels_guide import NARROW_OPTIONS # noqa: E402 +from test_notebook_channel_step_acceptance import ( # noqa: E402 + KINDS, + TAGS3, + choose, + experiment, + opened, +) + +NAMES = ["Hoechst", "Actin", "Ch3"] +MIXED = ("drug", "rep2", "single") +"""Its second image names the first two channels the other way round: its images disagree.""" +ORDERS = {"rep1": TAGS3, "rep2": ["ACTIN", "DNA", "PHASE"], "rep3": ["PHASE", "ACTIN", "DNA"]} + + +def _mixed(tmp_path): + root, masks, out = experiment(tmp_path, names=lambda key, n: NAMES) + write_channels(root / "drug/rep2/b.tif", ["Actin", "Hoechst", "Ch3"], KINDS[:3], seed=40) + write_masks(masks, {"drug/rep2/b.tif": 40}, {"Nuclei": "labels"}) + return root, masks, out + + +def _texts(widget): + """Return the text of every HTML widget in a widget tree.""" + own = widget.value if isinstance(widget, widgets.HTML) else "" + return own + "".join(_texts(child) for child in getattr(widget, "children", ())) + + +def _review(out): + return answers_from_bytes((out / DRAFT_FILENAME).read_bytes()).tag_review + + +# --- F4: no other row's tags for a unit whose images disagree ----------------------------------- + + +@pytest.mark.parametrize("scope", ["whole", "repeat"]) +def test_a_unit_whose_images_disagree_records_no_row_s_tags(tmp_path, scope): + exp = _mixed(tmp_path) + nb = opened(*exp, TAGS3) + guide = nb.channel_grid.guide + if scope == "whole": + guide.same.value = "yes" + choose(nb, ("whole", 3), TAGS3) + else: + guide.same.value = "no" + guide.narrow.value = "repeat" + for rep, tags in ORDERS.items(): + choose(nb, ("repeat", rep, 3), tags) + assert guide.submit() + rows = nb.channel_grid.by_repeat + assert MIXED in rows.listed() and rows.refused[MIXED].lead is None + # on the reviewed head: the first row of its count's tags (rep1's order, DNA ACTIN PHASE) + assert rows.refused[MIXED].tags == () + assert _review(exp[2]).refused[MIXED].tags == () + assert nb.draft_answers.units[MIXED].channels == (None, None, None) # never filled + assert MIXED not in rows.override.buttons # no reference while its images disagree + write_channels(exp[0] / "drug/rep2/b.tif", NAMES, KINDS[:3], seed=40) + nb.check_button.click() # its images agree again: still listed, no confirmation came + nb.preview_checked.set(True) + nb.show_preview() + nb.confirm_button.click() + assert MIXED in rows.listed() + rows.override.buttons[MIXED].click() # its editor: every channel chosen, none pre-set + assert rows.override.drafts[MIXED] == [None, None, None] + assert "no row's tags were recorded for it" in _texts(nb.channel_grid.widget) + + +def test_the_narrowing_choice_names_the_biological_repeat_folder(): + assert NARROW_OPTIONS[0][0] == "Same order within each biological repeat folder" + + +# --- F5: what a row and the image type's button say --------------------------------------------- + + +def test_a_row_filled_from_a_broader_choice_says_so(tmp_path): + exp = experiment(tmp_path) + nb = opened(*exp, TAGS3) + guide = nb.channel_grid.guide + guide.same.value = "yes" + choose(nb, ("whole", 3), TAGS3) # the form only: nothing saved + assert "check it before Submit" not in guide.notes[("whole", 3)].value # the user's own + guide.same.value = "no" + guide.narrow.value = "repeat" + for rep in ORDERS: + assert guide.values()[("repeat", rep, 3)] == TAGS3 # the broader choice, pre-filled + assert "check it before Submit" in guide.notes[("repeat", rep, 3)].value + choose(nb, ("repeat", "rep2", 3), ORDERS["rep2"]) + assert "check it before Submit" not in guide.notes[("repeat", "rep2", 3)].value + + +def test_the_image_type_button_reads_validated_after_a_save_until_a_choice_changes(tmp_path): + exp = experiment(tmp_path) + nb = opened(*exp, [], typed=False) + line = nb.type_line + assert line.apply.description.strip() == "Validate" and not line.apply.disabled + line.apply.click() + assert line.apply.description.strip() == "Validated ✓" and line.apply.disabled + line.per_folder.selected_index = 0 + one = ("drug", "rep1", "single") + nb.channel_types.radios[one].value = "rgb" # a change of the form: not saved yet + assert line.apply.description.strip() == "Validate" + nb.channel_types.radios[one].value = "channels" # back to what is saved + assert line.apply.description.strip() == "Validated ✓" diff --git a/tests/test_notebook_channel_guide_reopen.py b/tests/test_notebook_channel_guide_reopen.py new file mode 100644 index 00000000..6554f8b5 --- /dev/null +++ b/tests/test_notebook_channel_guide_reopen.py @@ -0,0 +1,297 @@ +"""The guided channel step on a reopened draft (review of #546, F1 and F3). + +The tick of fast mode is hidden in the guided step and only Submit sets it, so it is not in an +unpublished draft. On the review's head a strict draft (per repeat, per unit, or one list per +channel count) reopened ticked by default, and opening Channels wrote, with no click, +``channel_layout`` = the first unit's order with every unit ``experiment``: Check and save then +published every unit in rep1's order. A reopened draft now keeps its own mode, opening Channels +writes nothing, and the guide is answered as the draft already is. +""" + +from __future__ import annotations + +import pytest + +from morphobricks_preprocessing.description_file import DESCRIPTION_FILENAME +from morphobricks_preprocessing.draft_format import answers_from_bytes + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +from morphobricks_preprocessing import notebook_description # noqa: E402 +from morphobricks_preprocessing import notebook_style as ui # noqa: E402 +from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 +from test_notebook_channel_step_acceptance import ( # noqa: E402 + LABELS4, + TAGS3, + UNITS, + choose, + draft, + experiment, + finish, + folder, + opened, + published, + shown, + unit_channels, +) + +ORDERS = {"rep1": TAGS3, "rep2": ["ACTIN", "DNA", "PHASE"], "rep3": ["PHASE", "ACTIN", "DNA"]} + + +def _per_repeat(exp): + nb = opened(*exp, TAGS3) + guide = nb.channel_grid.guide + guide.same.value = "no" + guide.narrow.value = "repeat" + for rep, tags in ORDERS.items(): + choose(nb, ("repeat", rep, 3), tags) + assert guide.submit() + return nb + + +def _reopened(exp): + """Open the draft in a new notebook, up to Channels (nothing answered on the way).""" + before = draft(exp[2]) + nb = opened(*exp, [], typed=False) + assert draft(exp[2]) == before # opening Channels on a reopened draft writes 0 bytes + return nb + + +def _saved(exp): + return answers_from_bytes(draft(exp[2])) + + +def test_a_reopened_per_repeat_draft_stays_strict_and_publishes_each_repeat_s_order(tmp_path): + exp = experiment(tmp_path) + _per_repeat(exp) + nb = _reopened(exp) + assert _saved(exp).channel_layout is None # never converted with no click + assert not nb.channel_grid.same_channels.value + guide = nb.channel_grid.guide + assert (guide.same.value, guide.narrow.value) == ("no", "repeat") # as the draft is + assert "Pre-answered from your saved tags" in guide.draft_note.value + assert shown(nb) == {("repeat", rep, 3): tags for rep, tags in ORDERS.items()} + finish(nb) + assert nb.save_experiment() + doc = published(exp[2]) + assert "channel_layout" not in doc + assert unit_channels(doc) == {folder(k): (ORDERS[k[1]], None) for k in UNITS} + + +def test_a_reopened_per_unit_draft_stays_strict(tmp_path): + exp = experiment(tmp_path) + nb = opened(*exp, TAGS3) + guide = nb.channel_grid.guide + guide.same.value = "no" + guide.narrow.value = "unit" + shifts = {k: (i + (k[0] == "drug")) % 3 for i, k in enumerate(sorted(UNITS))} + orders = {k: TAGS3[n:] + TAGS3[:n] for k, n in shifts.items()} # no repeat has one order + for key, tags in orders.items(): + choose(nb, ("unit", key), tags) + assert guide.submit() + again = _reopened(exp) + assert _saved(exp).channel_layout is None + assert (again.channel_grid.guide.same.value, again.channel_grid.guide.narrow.value) == ( + "no", + "unit", + ) + finish(again) + assert again.save_experiment() + assert unit_channels(published(exp[2])) == {folder(k): (orders[k], None) for k in UNITS} + + +def test_a_reopened_mixed_count_yes_draft_stays_strict(tmp_path): + exp = experiment(tmp_path, count=lambda key: 4 if key[1] == "rep2" else 3) + nb = opened(*exp, LABELS4) + guide = nb.channel_grid.guide + guide.same.value = "yes" + choose(nb, ("whole", 3), TAGS3) + choose(nb, ("whole", 4), LABELS4) + assert guide.submit() + again = _reopened(exp) + assert _saved(exp).channel_layout is None + assert again.channel_grid.guide.same.value == "yes" # one list per count reproduces it + assert shown(again) == {("whole", 3): TAGS3, ("whole", 4): LABELS4} + finish(again) + assert again.save_experiment() + doc = published(exp[2]) + assert "channel_layout" not in doc + assert unit_channels(doc) == { + folder(k): (LABELS4 if k[1] == "rep2" else TAGS3, None) for k in UNITS + } + + +def test_a_reopened_fast_draft_stays_fast(tmp_path): + exp = experiment(tmp_path) + nb = opened(*exp, TAGS3) + nb.channel_grid.guide.same.value = "yes" + choose(nb, ("whole", 3), TAGS3) + assert nb.channel_grid.guide.submit() + again = _reopened(exp) + assert again.channel_grid.same_channels.value + assert _saved(exp).channel_layout.channels == tuple(TAGS3) + finish(again) + assert again.save_experiment() + assert unit_channels(published(exp[2])) == {folder(k): (TAGS3, "experiment") for k in UNITS} + + +def test_an_all_colour_reopen_still_publishes_r_g_b(tmp_path): + exp = experiment(tmp_path, rgb=lambda key: True) + opened(*exp, []) # the type for all folders: colour; nothing else + again = _reopened(exp) + finish(again) + assert again.save_experiment() + doc = published(exp[2]) + assert doc["channel_layout"]["channels"] == ["R", "G", "B"] + assert all(v == (["R", "G", "B"], "experiment") for v in unit_channels(doc).values()) + + +def test_a_reopened_draft_with_a_listed_unit_keeps_its_tags_and_says_so(tmp_path): + odd = ("drug", "rep2", "single") + names = ["ACTIN", "DNA", "PHASE"] + exp = experiment(tmp_path, names=lambda key, n: names if key == odd else TAGS3) + nb = opened(*exp, TAGS3) + guide = nb.channel_grid.guide + guide.same.value = "no" + guide.narrow.value = "repeat" + for rep in ("rep1", "rep2", "rep3"): + choose(nb, ("repeat", rep, 3), TAGS3) + assert guide.submit() and set(nb.channel_grid.by_repeat.listed()) == {odd} + again = _reopened(exp) + assert not again.channel_grid.same_channels.value # strict: saved tags of its own + assert set(again.channel_grid.by_repeat.listed()) == {odd} # still listed + assert again.channel_grid.guide.same.value is None # not every unit tagged: asked + assert "Saved per-unit tags are kept" in again.channel_grid.guide.draft_note.value + finish(again) + assert not again.save_experiment() + assert not (exp[2] / DESCRIPTION_FILENAME).exists() + assert _saved(exp).channel_layout is None + + +def _per_unit(exp): + nb = opened(*exp, TAGS3) + guide = nb.channel_grid.guide + guide.same.value = "no" + guide.narrow.value = "unit" + for i, key in enumerate(sorted(UNITS)): + choose(nb, ("unit", key), TAGS3[i % 3 :] + TAGS3[: i % 3]) + assert guide.submit() + + +def _mixed_yes(exp): + nb = opened(*exp, LABELS4) + nb.channel_grid.guide.same.value = "yes" + choose(nb, ("whole", 3), TAGS3) + choose(nb, ("whole", 4), LABELS4) + assert nb.channel_grid.guide.submit() + + +def _fast(exp): + nb = opened(*exp, TAGS3) + nb.channel_grid.guide.same.value = "yes" + choose(nb, ("whole", 3), TAGS3) + assert nb.channel_grid.guide.submit() + + +DRAFTS = { + "per_repeat": (_per_repeat, {}), + "per_unit": (_per_unit, {}), + "mixed_count_yes": (_mixed_yes, {"count": lambda key: 4 if key[1] == "rep2" else 3}), + "fast": (_fast, {}), + "all_colour": (lambda exp: opened(*exp, []), {"rgb": lambda key: True}), +} + + +@pytest.mark.parametrize("kind", sorted(DRAFTS)) +def test_opening_channels_on_a_reopened_draft_writes_no_byte(tmp_path, monkeypatch, kind): + answer, shape = DRAFTS[kind] + exp = experiment(tmp_path, **shape) + answer(exp) + before = draft(exp[2]) + writes = [] + real = notebook_description.save_draft + + def counted(*args, **kwargs): + writes.append(args) + return real(*args, **kwargs) + + monkeypatch.setattr(notebook_description, "save_draft", counted) + nb = opened(*exp, [], typed=False) # a new notebook on the draft, up to Channels + assert writes == [] # no draft write at all, not even of the same bytes + assert draft(exp[2]) == before + assert nb.channel_grid.guided and ui.is_visible(nb.channel_grid.widget) + + +def test_a_restored_per_repeat_draft_opens_strict_with_no_draft_write(tmp_path, monkeypatch): + """The restore of #547 (output folder set, nothing clicked) reopens the same way.""" + exp = experiment(tmp_path) + _per_repeat(exp) + before = draft(exp[2]) + writes = [] + real = notebook_description.save_draft + + def counted(*args, **kwargs): + writes.append(args) + return real(*args, **kwargs) + + monkeypatch.setattr(notebook_description, "save_draft", counted) + nb = PreprocessingNotebook() + nb.steps() + nb.results_step() + nb.folder.value = str(exp[0]) + nb.output.value = str(exp[2]) # the restore: the check, the saved answers + assert nb.preflight is not None and nb.confirmed_mapping is None + nb.masks_folder.value = str(exp[1]) + nb.preview_checked.set(True) + nb.show_preview() + nb.confirm_button.click() # the axes: the user's one click + nb._stepper.go(2) # Channels + assert writes == [] and draft(exp[2]) == before + assert not nb.channel_grid.same_channels.value + guide = nb.channel_grid.guide + assert (guide.same.value, guide.narrow.value) == ("no", "repeat") + assert shown(nb) == {("repeat", rep, 3): tags for rep, tags in ORDERS.items()} + monkeypatch.undo() + finish(nb) + assert nb.save_experiment() + doc = published(exp[2]) + assert "channel_layout" not in doc + assert unit_channels(doc) == {folder(k): (ORDERS[k[1]], None) for k in UNITS} + + +def test_an_abandoned_yes_never_replaces_the_saved_repeat_orders(tmp_path): + """Review of #546 at e40f1ad: Yes filled with rep1's order, then back to No, per repeat. + + The repeat rows showed rep1's order (a broader choice ranked above the saved tags) under + "Pre-answered from your saved tags", and one Submit published rep1's order everywhere. + """ + exp = experiment(tmp_path) + _per_repeat(exp) + nb = _reopened(exp) + guide = nb.channel_grid.guide + assert "Pre-answered from your saved tags" in guide.draft_note.value + guide.same.value = "yes" + assert guide.draft_note.value == "" # the answer changed: the note no longer holds + choose(nb, ("whole", 3), ORDERS["rep1"]) + guide.same.value = "no" + assert guide.narrow.value == "repeat" + assert shown(nb) == {("repeat", rep, 3): tags for rep, tags in ORDERS.items()} + assert all("as saved" in guide.notes[("repeat", rep, 3)].value for rep in ORDERS) + assert "Pre-answered from your saved tags" not in guide.draft_note.value + assert guide.submit() + finish(nb) + assert nb.save_experiment() + doc = published(exp[2]) + assert "channel_layout" not in doc + assert unit_channels(doc) == {folder(k): (ORDERS[k[1]], None) for k in UNITS} + + +def test_a_pick_in_a_pre_answered_row_takes_the_note_back(tmp_path): + exp = experiment(tmp_path) + _per_repeat(exp) + nb = _reopened(exp) + guide = nb.channel_grid.guide + assert "Pre-answered from your saved tags" in guide.draft_note.value + choose(nb, ("repeat", "rep2", 3), ORDERS["rep3"]) + assert guide.draft_note.value == "" diff --git a/tests/test_notebook_channel_moves.py b/tests/test_notebook_channel_moves.py index fc703f96..706e9dda 100644 --- a/tests/test_notebook_channel_moves.py +++ b/tests/test_notebook_channel_moves.py @@ -40,6 +40,9 @@ from morphobricks_preprocessing import notebook_style as ui # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def _retag_swapped(exp, monkeypatch, gone=None): # noqa: F811 """Save on 2026-01-01, swap ctrl/rep1's first two header channels, re-tag them to match. diff --git a/tests/test_notebook_channel_no_save_on_pick.py b/tests/test_notebook_channel_no_save_on_pick.py new file mode 100644 index 00000000..cceff767 --- /dev/null +++ b/tests/test_notebook_channel_no_save_on_pick.py @@ -0,0 +1,78 @@ +"""Regression (owner's Colab test of the v0.9.0 candidate, 25 November 2026): a pick never saves. + +On main at b683c7c every dropdown of the shipped notebook's channel step, and every image-type +radio button of a folder, wrote the draft at once (and redrew the page). These tests use only +what both versions have (the stepper, the widgets on screen), so they run, and fail, there too. +""" + +from __future__ import annotations + +import pytest + +from channel_images import write_channels, write_masks +from morphobricks_preprocessing.description_file import DRAFT_FILENAME + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +import ipywidgets as widgets # noqa: E402 + +from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 + +FOLDERS = ["ctrl/rep1", "ctrl/rep2", "drug/rep1", "drug/rep2"] + + +def _tree(tmp_path): + root, masks = tmp_path / "exp", tmp_path / "masks" + for i, name in enumerate(FOLDERS): + write_channels(root / name / "a.tif", None, ["blobs", "filaments", "cells"], seed=i + 1) + write_masks(masks, {f"{name}/a.tif": i + 1}, {"Nuclei": "labels"}) + nb = PreprocessingNotebook(str(root), output_folder=str(tmp_path / "out")) + nb.welcome() + nb.steps() + nb.masks_folder.value = str(masks) + nb.check_button.click() + nb.preview_checked.set(True) + nb.show_preview() + nb.confirm_button.click() + return nb, tmp_path / "out" / DRAFT_FILENAME + + +def _all(widget): + yield widget + for child in getattr(widget, "children", ()): + yield from _all(child) + + +def _shown(widget): + return getattr(widget.layout, "display", None) != "none" + + +def _bytes(path): + return path.read_bytes() if path.exists() else None + + +def test_choosing_a_folder_s_image_type_writes_nothing(tmp_path): + nb, draft = _tree(tmp_path) + nb.type_line.per_folder.selected_index = 0 # Set per folder… + before = _bytes(draft) + radio = next(iter(nb.channel_types.radios.values())) + radio.value = "channels" + assert _bytes(draft) == before + + +def test_picking_a_channel_writes_nothing(tmp_path): + nb, draft = _tree(tmp_path) + nb.type_line.apply.click() # the image type for all folders (a deliberate save) + card = nb.channel_labels + for row, text in zip(card.rows, ["DNA", "ACTIN", "PHASE"], strict=False): + row.id_box.value = text + card.confirm.button.click() + for toggle in _all(nb.channel_grid.widget): + if isinstance(toggle, widgets.ToggleButtons) and toggle.options[0][1] == "yes": + toggle.value = "yes" # the guided step's question, where there is one + before = _bytes(draft) + drops = [w for w in _all(nb.channel_grid.widget) if isinstance(w, widgets.Dropdown)] + drop = next(d for d in drops if _shown(d)) + drop.value = "DNA" + assert _bytes(draft) == before diff --git a/tests/test_notebook_channel_step_acceptance.py b/tests/test_notebook_channel_step_acceptance.py new file mode 100644 index 00000000..38d07615 --- /dev/null +++ b/tests/test_notebook_channel_step_acceptance.py @@ -0,0 +1,551 @@ +"""Acceptance: the guided channel step of the shipped notebook, button by button (25 Nov 2026). + +The owner's design, driven headlessly the way a user clicks through the stepper +(``PreprocessingNotebook().steps()``, the shipped notebooks' layout): Images (check), Axes +(confirm), Channels (image type, labels, then the guided step), the rest of the answers, Check +and save. Each scenario checks what the user SEES (the questions asked, the number of rows of +dropdowns, the choices kept, nothing saved before Submit) and what is PUBLISHED (the +description passes the Spec's reference validator and records exactly the intended channels of +every imaging unit, in fast mode only when the order is the same for the whole dataset with +one channel count). + +The same scenarios, as clicks for a person, are in ``docs/colab-release-check.md``. +""" + +from __future__ import annotations + +import tomllib + +import pytest + +from channel_images import write_channels, write_masks, write_rgb +from morphobricks_preprocessing.description_file import DESCRIPTION_FILENAME, DRAFT_FILENAME +from spec_oracle import refval + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +from morphobricks_preprocessing import notebook_style as ui # noqa: E402 +from morphobricks_preprocessing.notebook_channels_guide import ( # noqa: E402 + NARROW_QUESTION, + SAME_QUESTION, +) +from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 + +TAGS3 = ["DNA", "ACTIN", "PHASE"] +LABELS4 = [*TAGS3, "EXTRA"] +KINDS = ["blobs", "filaments", "cells", "blobs"] +UNITS = [(c, b, "single") for c in ("ctrl", "drug") for b in ("rep1", "rep2", "rep3")] + + +def folder(key): + return "/".join(part for part in key if part != "single") + + +def experiment(tmp_path, *, count=lambda key: 3, names=lambda key, n: None, rgb=lambda key: False): + """Write one image per unit; ``count``, ``names`` and ``rgb`` say what each unit holds.""" + root, masks = tmp_path / "exp", tmp_path / "masks" + for i, key in enumerate(UNITS): + path = root / folder(key) / "a.tif" + if rgb(key): + write_rgb(path, seed=i + 1) + else: + n = count(key) + write_channels(path, names(key, n), KINDS[:n], seed=i + 1) + write_masks(masks, {f"{folder(key)}/a.tif": i + 1}, {"Nuclei": "labels"}) + return root, masks, tmp_path / "out" + + +def opened(root, masks, out, labels, *, typed=True): + """Click through Images and Axes, confirm the image type and the labels (Channels).""" + nb = PreprocessingNotebook(str(root), output_folder=str(out)) + nb.welcome() + nb.steps() + nb.results_step() + nb.masks_folder.value = str(masks) + nb.check_button.click() + nb.preview_checked.set(True) + nb.show_preview() + nb.confirm_button.click() + nb._stepper.go(2) # Channels + if typed: + nb.type_line.apply.click() # "Use for all folders": the image type first + card = nb.channel_labels + if labels: + while len(card.rows) < len(labels): + card.add_button.click() + for row, text in zip(card.rows, labels, strict=False): + row.id_box.value = text + card.confirm.button.click() + return nb + + +def draft(out): + """Return the draft file's bytes (None before the first save).""" + path = out / DRAFT_FILENAME + return path.read_bytes() if path.exists() else None + + +def choose(nb, row, tags): + """Pick ``tags`` in the dropdowns of one row of the guided step.""" + for drop, tag in zip(nb.channel_grid.guide.drops[row], tags, strict=True): + drop.value = tag + + +def shown(nb): + """Return what every row of the form shows now.""" + return nb.channel_grid.guide.values() + + +def finish(nb): + """Answer the rest (mask type, comparisons, design, same way) as a user does.""" + question = nb.mask_card.questions.get("Nuclei") + if question is not None and question.choice.value is None: + question.choice.value = "instances" + if nb._chosen_reference("drug") is None: + nb.reference_boxes["drug"].value = "ctrl" + if nb._chosen_reference("ctrl") is None and nb.reference_boxes["ctrl"].value is None: + nb.reference_boxes["ctrl"].value = "" + if not nb._design_confirmed(): + nb.design_confirm.click() + for toggle in list(nb.same_way.values()): + if not toggle.value: + toggle.button.click() + + +def published(out): + """Return the published description, after the Spec's reference validator passed it.""" + data = (out / DESCRIPTION_FILENAME).read_bytes() + report, _ = refval().validate(data) + assert report.errors == [] + return tomllib.loads(data.decode("utf-8")) + + +def unit_channels(doc): + """Return each published unit's channels and marker, by its folder (condition/repeat).""" + found = {} + for repeat in doc["repeats"].values(): + for condition, member in repeat["members"].items(): + for unit in member["technical_repeats"].values(): + key = (condition, member["source_repeat"], unit["source_folder"]) + found[folder(key)] = (unit["channels"], unit.get("channels_from")) + return found + + +def visible(widget): + return ui.is_visible(widget) + + +# --- 1. the owner's layout: 3 channels everywhere, a 4th in some repeats ------------------------ + + +def test_1_owner_layout_yes_opens_one_row_per_channel_count_and_publishes(tmp_path): + exp = experiment(tmp_path, count=lambda key: 4 if key[1] == "rep2" else 3) + nb = opened(*exp, LABELS4) + guide = nb.channel_grid.guide + assert SAME_QUESTION in guide.same_text.value and "3 and 4 channels" in guide.same_text.value + assert not guide.rows and not visible(guide.submit_button) # nothing before the answer + before = draft(exp[2]) + guide.same.value = "yes" + assert [r.key for r in guide.rows] == [("whole", 3), ("whole", 4)] # one row per count + assert [len(guide.drops[r.key]) for r in guide.rows] == [3, 4] + assert not visible(guide.narrow_box) + choose(nb, ("whole", 3), TAGS3) + choose(nb, ("whole", 4), LABELS4) + assert draft(exp[2]) == before # nothing saved before Submit + assert guide.submit() + assert "Saved" in guide.message.value + finish(nb) + assert nb.save_experiment() + doc = published(exp[2]) + assert "channel_layout" not in doc # several counts: a strict per-unit file + expected = {folder(k): (LABELS4 if k[1] == "rep2" else TAGS3, None) for k in UNITS} + assert unit_channels(doc) == expected + + +# --- 2. one channel count, the same order everywhere --------------------------------------------- + + +def test_2_same_count_yes_is_one_row_and_publishes_fast_mode(tmp_path): + exp = experiment(tmp_path) + nb = opened(*exp, TAGS3) + guide = nb.channel_grid.guide + assert guide.same_text.value == f"{SAME_QUESTION}" # no count sentence + guide.same.value = "yes" + assert [r.key for r in guide.rows] == [("whole", 3)] + choose(nb, ("whole", 3), TAGS3) + assert guide.submit() + finish(nb) + assert nb.save_experiment() + doc = published(exp[2]) + assert doc["channel_layout"]["channels"] == TAGS3 # ADR 0006: the user's statement + assert unit_channels(doc) == {folder(k): (TAGS3, "experiment") for k in UNITS} + + +# --- 3. one count, the order is per biological repeat --------------------------------------------- + + +def test_3_same_count_no_per_repeat_one_row_per_repeat_with_different_orders(tmp_path): + exp = experiment(tmp_path) + nb = opened(*exp, TAGS3) + guide = nb.channel_grid.guide + guide.same.value = "no" + assert visible(guide.narrow_box) and NARROW_QUESTION in repr(guide.narrow_box.children[0]) + assert not guide.rows # the second question first + guide.narrow.value = "repeat" + assert [r.key for r in guide.rows] == [("repeat", f"rep{i}", 3) for i in (1, 2, 3)] + orders = { + "rep1": TAGS3, + "rep2": ["ACTIN", "DNA", "PHASE"], + "rep3": ["PHASE", "ACTIN", "DNA"], + } + for rep, tags in orders.items(): + choose(nb, ("repeat", rep, 3), tags) + assert guide.submit() + finish(nb) + assert nb.save_experiment() + doc = published(exp[2]) + assert "channel_layout" not in doc + assert unit_channels(doc) == {folder(k): (orders[k[1]], None) for k in UNITS} + + +# --- 4. one count, every imaging unit ------------------------------------------------------------- + + +def test_4_same_count_no_per_unit_one_row_per_unit(tmp_path): + exp = experiment(tmp_path) + nb = opened(*exp, TAGS3) + guide = nb.channel_grid.guide + guide.same.value = "no" + guide.narrow.value = "unit" + assert len(guide.rows) == len(UNITS) + orders = {k: TAGS3[i % 3 :] + TAGS3[: i % 3] for i, k in enumerate(sorted(UNITS))} + for key, tags in orders.items(): + choose(nb, ("unit", key), tags) + assert guide.submit() + finish(nb) + assert nb.save_experiment() + doc = published(exp[2]) + assert "channel_layout" not in doc + assert unit_channels(doc) == {folder(k): (orders[k], None) for k in UNITS} + + +# --- 5. mixed counts, per biological repeat ------------------------------------------------------- + + +def test_5_mixed_counts_no_per_repeat(tmp_path): + exp = experiment(tmp_path, count=lambda key: 4 if key[1] == "rep3" else 3) + nb = opened(*exp, LABELS4) + guide = nb.channel_grid.guide + assert "3 and 4 channels" in guide.same_text.value + guide.same.value = "no" + guide.narrow.value = "repeat" + assert [r.key for r in guide.rows] == [ + ("repeat", "rep1", 3), + ("repeat", "rep2", 3), + ("repeat", "rep3", 4), + ] + orders = {"rep1": TAGS3, "rep2": ["ACTIN", "DNA", "PHASE"], "rep3": ["EXTRA", *TAGS3]} + for rep, tags in orders.items(): + choose(nb, ("repeat", rep, len(tags)), tags) + assert guide.submit() + finish(nb) + assert nb.save_experiment() + doc = published(exp[2]) + assert "channel_layout" not in doc + assert unit_channels(doc) == {folder(k): (orders[k[1]], None) for k in UNITS} + + +# --- 6. a header contradicts the submitted tags -------------------------------------------------- + +SWAPPED = ("drug", "rep2", "single") + + +def _named(key, n): + return ["ACTIN", "DNA", "PHASE"] if key == SWAPPED else list(TAGS3) + + +def test_6_a_contradicting_unit_is_refused_on_submit_and_released_by_its_confirm(tmp_path): + exp = experiment(tmp_path, names=_named) + nb = opened(*exp, TAGS3) + guide, rows = nb.channel_grid.guide, nb.channel_grid.by_repeat + guide.same.value = "yes" + assert shown(nb) == {("whole", 3): [None, None, None]} # the headers differ: no proposal + choose(nb, ("whole", 3), TAGS3) + assert guide.submit() + assert "1 imaging unit(s) not tagged" in guide.message.value + assert set(rows.listed()) == {SWAPPED} + assert "C0: header ‘ACTIN’ is ACTIN, the row says DNA" in rows.listed()[SWAPPED] + units = nb.draft_answers.units + assert SWAPPED not in units or not any(units[SWAPPED].channels) # never reordered + review = nb.draft_answers.tag_review + assert set(review.refused) == {SWAPPED} # the refusal is in the same write as the tags + finish(nb) + assert not nb.save_experiment() # a listed unit is never published + rows.override.buttons[SWAPPED].click() # the existing refusal flow + for index, tag in enumerate(["ACTIN", "DNA", "PHASE"]): + rows.override.cells[(SWAPPED, index)].value = tag + assert rows.override.confirm() + assert rows.listed() == {} + finish(nb) + assert nb.save_experiment() + found = unit_channels(published(exp[2])) + assert found[folder(SWAPPED)] == (["ACTIN", "DNA", "PHASE"], "unit") # its own list + assert all(v == (TAGS3, "experiment") for k, v in found.items() if k != folder(SWAPPED)) + + +# --- 7. colour (RGB) ------------------------------------------------------------------------------ + + +def test_7_every_folder_colour_asks_nothing_and_publishes_r_g_b(tmp_path): + exp = experiment(tmp_path, rgb=lambda key: True) + nb = opened(*exp, []) + guide = nb.channel_grid.guide + assert nb.channel_labels.not_applicable # no stains to name + assert not visible(guide.questions) and not guide.rows + assert "Every folder is colour (RGB)" in guide.rows_box.children[0].value + finish(nb) + assert nb.save_experiment() + doc = published(exp[2]) + # "Use for all folders: colour" states it for the whole dataset (ADR 0006), as before + assert doc["channel_layout"]["channels"] == ["R", "G", "B"] + found = unit_channels(doc) + assert all(value == (["R", "G", "B"], "experiment") for value in found.values()) + assert len(found) == len(UNITS) + + +def test_7_the_image_type_is_asked_before_any_row(tmp_path): + exp = experiment(tmp_path) + nb = opened(*exp, TAGS3, typed=False) + guide = nb.channel_grid.guide + assert "Waiting for the image type" in guide.rows_box.children[0].value + assert not visible(guide.questions) + + +def test_7_colour_mixed_with_separate_channels_is_refused_as_today(tmp_path): + exp = experiment(tmp_path, rgb=lambda key: key[1] == "rep3") + nb = opened(*exp, [], typed=False) + # colour (YXS) and separate channels (CYX) have no one set of axis roles: refused at Axes, + # so Channels never opens and nothing can be tagged or published + assert nb.confirmed_mapping is None + assert "Waiting for the axis roles" in nb.channels_waiting.value + assert not visible(nb.channel_grid.widget) and not nb.channel_grid.guide.rows + finish(nb) + assert not nb.save_experiment() + assert not (exp[2] / DESCRIPTION_FILENAME).exists() + + +# --- 8. changing one's mind before Submit --------------------------------------------------------- + + +def test_8_choices_are_kept_across_changes_and_branch_switches_with_no_draft_write(tmp_path): + exp = experiment(tmp_path, count=lambda key: 4 if key[1] == "rep2" else 3) + nb = opened(*exp, LABELS4) + guide = nb.channel_grid.guide + before = draft(exp[2]) + guide.same.value = "yes" + choose(nb, ("whole", 3), TAGS3) + drop = guide.drops[("whole", 3)][1] + drop.value = "PHASE" # change your mind + drop.value = "ACTIN" # and back + assert shown(nb)[("whole", 3)] == TAGS3 + guide.same.value = "no" + guide.narrow.value = "repeat" + rows = shown(nb) + assert set(rows) == {("repeat", "rep1", 3), ("repeat", "rep2", 4), ("repeat", "rep3", 3)} + assert rows[("repeat", "rep1", 3)] == TAGS3 # starts from the whole dataset's choice + assert rows[("repeat", "rep2", 4)] == [None] * 4 # no choice for 4 channels yet + choose(nb, ("repeat", "rep3", 3), ["ACTIN", "DNA", "PHASE"]) + guide.narrow.value = "unit" + assert len(shown(nb)) == len(UNITS) + assert shown(nb)[("unit", ("ctrl", "rep3", "single"))] == ["ACTIN", "DNA", "PHASE"] + guide.same.value = "yes" + assert shown(nb) == {("whole", 3): TAGS3, ("whole", 4): [None] * 4} # no stale rows + guide.same.value = "no" + assert shown(nb)[("unit", ("ctrl", "rep3", "single"))] == ["ACTIN", "DNA", "PHASE"] + assert draft(exp[2]) == before # not one draft write before Submit + assert nb.draft_answers.units == {} or all( + not any(u.channels) for u in nb.draft_answers.units.values() + ) + + +# --- 9. one image-type answer for all folders (owner, 25 November 2026) --------------------- + + +def _type_for_all(nb, value): + """Choose the image type once and click "Use for all folders".""" + nb.type_line.choice.value = value + nb.type_line.apply.click() + + +def _types(nb): + return {k: u.image_type for k, u in nb.draft_answers.units.items()} + + +def test_9a_mixed_channel_counts_one_separate_channels_answer_goes_straight_to_tagging(tmp_path): + exp = experiment(tmp_path, count=lambda key: 4 if key[1] == "rep2" else 3) + nb = opened(*exp, LABELS4, typed=False) + assert visible(nb.type_line.apply) # offered whatever the channel counts + _type_for_all(nb, "channels") + assert _types(nb) == {k: "channels" for k in UNITS} # one click, every folder + assert nb.type_line.followups.value == "" + guide = nb.channel_grid.guide + assert visible(guide.questions) and "3 and 4 channels" in guide.same_text.value + + +def test_9b_different_image_counts_per_folder_one_answer_for_all(tmp_path): + exp = experiment(tmp_path) + root, masks, _ = exp + for extra, key in enumerate(UNITS[:2]): # two folders hold three images, the others one + for name in ("b.tif", "c.tif"): + write_channels(root / folder(key) / name, None, KINDS[:3], seed=40 + extra) + write_masks(masks, {f"{folder(key)}/{name}": 40 + extra}, {"Nuclei": "labels"}) + nb = opened(*exp, TAGS3, typed=False) + _type_for_all(nb, "channels") + assert _types(nb) == {k: "channels" for k in UNITS} + guide = nb.channel_grid.guide + guide.same.value = "yes" + assert [r.key for r in guide.rows] == [("whole", 3)] + choose(nb, ("whole", 3), TAGS3) + assert guide.submit() + finish(nb) + assert nb.save_experiment() + assert unit_channels(published(exp[2])) == {folder(k): (TAGS3, "experiment") for k in UNITS} + + +HEADER_RGB = ("drug", "rep3", "single") + + +def scanner_experiment(tmp_path): + """Colour images, three interleaved samples each: one folder's header says colour (RGB), + the others' do not (a scanner's MINISBLACK header, Spec RH1).""" + import numpy as np + import tifffile + + from channel_images import blobs + + root, masks = tmp_path / "exp", tmp_path / "masks" + for i, key in enumerate(UNITS): + path = root / folder(key) / "a.tif" + path.parent.mkdir(parents=True, exist_ok=True) + data = np.stack([blobs(i + s) // 256 for s in (1, 2, 3)], axis=-1).astype(np.uint8) + photometric = "rgb" if key == HEADER_RGB else "minisblack" + tifffile.imwrite(path, data, photometric=photometric, planarconfig="contig") + write_masks(masks, {f"{folder(key)}/a.tif": i + 1}, {"Nuclei": "labels"}) + return root, masks, tmp_path / "out" + + +def test_9c_one_header_says_colour_answered_separate_for_all_lists_only_that_folder(tmp_path): + exp = scanner_experiment(tmp_path) + nb = opened(*exp, [], typed=False) + line = nb.type_line + assert line.suggestion() is None and visible(line.apply) # headers differ: still one answer + assert "choose one type for all folders in the box" in line.line.value + assert line.per_folder.selected_index is None + _type_for_all(nb, "channels") + assert _types(nb) == {k: "channels" for k in UNITS} # recorded for every folder + later = line.followups.value + assert "Another step for 1 folder:" in later + assert folder(HEADER_RGB).replace("/", " / ") in later + assert "R_IMAGE_TYPE_CONTRADICTS_HEADER" in later + # the others go on: the channel step opens with its question + card = nb.channel_labels + for row, text in zip(card.rows, TAGS3, strict=False): + row.id_box.value = text + card.confirm.button.click() + assert visible(nb.channel_grid.guide.questions) + + +def test_9c_colour_for_all_offers_the_rgb_header_override_to_the_other_folders(tmp_path): + exp = scanner_experiment(tmp_path) + nb = opened(*exp, [], typed=False) + _type_for_all(nb, "rgb") + assert _types(nb) == {k: "rgb" for k in UNITS} + later = nb.type_line.followups.value + assert "Another step for 5 folders:" in later and "RGB header override" in later + assert folder(HEADER_RGB).replace("/", " / ") not in later # its header says colour + before = draft(exp[2]) + nb.type_line.override.box.value = True # the existing RH1 tick, for those folders + assert draft(exp[2]) == before # a form choice: nothing saved before Validate + nb.type_line.apply.click() # Validate + assert nb.type_line.followups.value == "" + assert all(u.rgb_header_override for k, u in nb.draft_answers.units.items() if k != HEADER_RGB) + finish(nb) + assert nb.save_experiment() + found = unit_channels(published(exp[2])) + assert all(value[0] == ["R", "G", "B"] for value in found.values()) + + +def test_9_colour_for_all_is_refused_naming_every_folder_without_three_channels(tmp_path): + exp = experiment(tmp_path, count=lambda key: 4 if key[1] == "rep2" else 3) + nb = opened(*exp, [], typed=False) + _type_for_all(nb, "rgb") + assert _types(nb) == {} # all or none + said = nb.type_line.message.value + assert "a colour image has 3 channels" in said + assert said.count("(4 channels)") == 2 + + +# --- 10. the image type is a form too: Validate is its one save (owner, 25 November 2026) ---- + + +def test_10_image_type_choices_write_nothing_and_redraw_nothing_until_validate( + tmp_path, monkeypatch +): + exp = experiment(tmp_path, count=lambda key: 4 if key[1] == "rep2" else 3) + nb = opened(*exp, [], typed=False) + line = nb.type_line + assert line.apply.description.strip() == "Validate" + line.per_folder.selected_index = 0 # Set per folder… (its rows are built once opened) + radios = nb.channel_types.radios + assert len(radios) == len(UNITS) + before = draft(exp[2]) + calls = {"rows": 0, "line": 0, "saves": 0} + rows_refresh, line_refresh, save = nb.type_rows.refresh, line.refresh, nb._save_answers + + def count(name, function): + def counted(*args, **kwargs): + calls[name] += 1 + return function(*args, **kwargs) + + return counted + + monkeypatch.setattr(nb.type_rows, "refresh", count("rows", rows_refresh)) + monkeypatch.setattr(line, "refresh", count("line", line_refresh)) + monkeypatch.setattr(nb, "_save_answers", count("saves", save)) + widgets_before = dict(radios) + line.choice.value = "channels" # the box: every folder without its own choice follows + assert all(r.value == "channels" for r in radios.values()) + one = ("drug", "rep1", "single") + radios[one].value = "rgb" # one folder on its own, then back: the values stay as chosen + radios[one].value = "channels" + radios[one].value = "rgb" + assert radios[one].value == "rgb" and "Not validated yet" in nb.channel_types.notes[one].value + assert calls == {"rows": 0, "line": 0, "saves": 0} # no save, no redraw + assert dict(nb.channel_types.radios) == widgets_before # the very same widgets + assert draft(exp[2]) == before + radios[one].value = "channels" + line.apply.click() # Validate: one draft write for every folder's type + assert calls["saves"] == 1 + assert _types(nb) == {k: "channels" for k in UNITS} + card = nb.channel_labels # the channel step goes on: the labels, then the question + while len(card.rows) < len(LABELS4): + card.add_button.click() + for row, text in zip(card.rows, LABELS4, strict=True): + row.id_box.value = text + card.confirm.button.click() + assert visible(nb.channel_grid.guide.questions) + + +def test_10_validate_refuses_a_form_with_a_folder_left_unanswered(tmp_path): + exp = experiment(tmp_path) + nb = opened(*exp, [], typed=False) + line = nb.type_line + line.per_folder.selected_index = 0 + line.choice.value = None # the box's proposal from the headers taken away + one = ("ctrl", "rep1", "single") + nb.channel_types.radios[one].value = "channels" # one folder only, no answer for all + assert line.apply.disabled and "5 left" in line.blocker.value + assert not line._validate() + assert "choose the type of every folder" in line.message.value + assert _types(nb) == {} diff --git a/tests/test_notebook_compact.py b/tests/test_notebook_compact.py index 2bb5edfe..6fccc2a6 100644 --- a/tests/test_notebook_compact.py +++ b/tests/test_notebook_compact.py @@ -27,6 +27,9 @@ from morphobricks_preprocessing.validation import error, warning # noqa: E402 from test_notebook_axes_quick import stepper # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def _text(html): return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html)).strip() diff --git a/tests/test_notebook_design_confirm_speed.py b/tests/test_notebook_design_confirm_speed.py index 723d789f..0e12fe1d 100644 --- a/tests/test_notebook_design_confirm_speed.py +++ b/tests/test_notebook_design_confirm_speed.py @@ -25,6 +25,9 @@ ) from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + CONDITIONS, REPEATS, TECHNICAL, FOVS = 4, 4, 2, 2 BUDGET = 2.0 """Seconds for the click on 64 images; it took about 1.5 s here before the fix, 0.15 s after. diff --git a/tests/test_notebook_fast_statement.py b/tests/test_notebook_fast_statement.py index 409712e7..7f844ed3 100644 --- a/tests/test_notebook_fast_statement.py +++ b/tests/test_notebook_fast_statement.py @@ -23,6 +23,9 @@ from test_notebook_row_fold import stepper # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def _published(out): return description_from_bytes((out / DESCRIPTION_FILENAME).read_bytes()) diff --git a/tests/test_notebook_owner_fixes.py b/tests/test_notebook_owner_fixes.py index 52f6d6f7..7dc8be86 100644 --- a/tests/test_notebook_owner_fixes.py +++ b/tests/test_notebook_owner_fixes.py @@ -22,6 +22,9 @@ from morphobricks_preprocessing.validation import error # noqa: E402 from test_notebook_axes_quick import stepper # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def _text(html): return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html)).strip() diff --git a/tests/test_notebook_preprocessing_cellpose.py b/tests/test_notebook_preprocessing_cellpose.py index f0ec9044..c0a40ada 100644 --- a/tests/test_notebook_preprocessing_cellpose.py +++ b/tests/test_notebook_preprocessing_cellpose.py @@ -43,6 +43,9 @@ from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 from morphobricks_preprocessing.run_inputs import RunInputs # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def ran_app(tmp_path, *, with_masks=False): """Return the app of cell 3 after a finished run of four 3-channel images.""" diff --git a/tests/test_notebook_prerelease.py b/tests/test_notebook_prerelease.py index 767a789d..4a56698e 100644 --- a/tests/test_notebook_prerelease.py +++ b/tests/test_notebook_prerelease.py @@ -35,6 +35,9 @@ from morphobricks_preprocessing import notebook_style as ui # noqa: E402 from test_notebook_axes_quick import stepper # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + UNIT = UnitFolders("ctrl", "rep1", "single") KEY = ("ctrl", "rep1", "single") diff --git a/tests/test_notebook_progress.py b/tests/test_notebook_progress.py index 1d6a6b77..077badb7 100644 --- a/tests/test_notebook_progress.py +++ b/tests/test_notebook_progress.py @@ -29,6 +29,9 @@ from morphobricks_preprocessing.run.phases import PHASES # noqa: E402 from test_notebook_axes_quick import stepper # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def _text(html): return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html)).strip() diff --git a/tests/test_notebook_projection.py b/tests/test_notebook_projection.py index c19a04cf..6ea83ce0 100644 --- a/tests/test_notebook_projection.py +++ b/tests/test_notebook_projection.py @@ -35,6 +35,9 @@ from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 from test_notebook_check_save import FOLDERS, answer_all # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + NAMES = ["DAPI", "Actin", "Ch3"] diff --git a/tests/test_notebook_rgb_override.py b/tests/test_notebook_rgb_override.py index 79e504a0..8fabbd0c 100644 --- a/tests/test_notebook_rgb_override.py +++ b/tests/test_notebook_rgb_override.py @@ -43,6 +43,9 @@ from morphobricks_preprocessing.notebook_rgb_override import CHOOSE_COLOUR, LABEL # noqa: E402 from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + FOLDERS = ["ctrl/rep1", "ctrl/rep2", "drug/rep1", "drug/rep2"] OVERRIDE = b'image_type = "rgb"\nrgb_header_override = true\n' CONTRADICTS = "R_IMAGE_TYPE_CONTRADICTS_HEADER" diff --git a/tests/test_notebook_row_fold.py b/tests/test_notebook_row_fold.py index ac993477..5c73324e 100644 --- a/tests/test_notebook_row_fold.py +++ b/tests/test_notebook_row_fold.py @@ -33,6 +33,9 @@ from morphobricks_preprocessing import notebook_style as ui # noqa: E402 from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def test_a_row_folds_only_when_every_folder_is_as_saved_and_it_is_answered(): rec = Reconciliation( diff --git a/tests/test_notebook_seven_steps.py b/tests/test_notebook_seven_steps.py index f5754e58..2d3d3833 100644 --- a/tests/test_notebook_seven_steps.py +++ b/tests/test_notebook_seven_steps.py @@ -41,6 +41,9 @@ from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 from test_notebook_axes_quick import stepper # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + FOLDERS = ["ctrl/rep1", "ctrl/rep2", "drug/rep1", "drug/rep2"] @@ -157,13 +160,15 @@ def _line(colour): return line -def test_headers_that_differ_propose_nothing_and_open_each_folder(): +def test_headers_that_differ_propose_nothing_and_still_offer_one_answer_for_all(): line = _line({("drug", "rep2")}) assert line.suggestion() is None and line.choice.value is None said = _text(line.line.value) assert "The image headers differ: separate channels in 3 folders, colour (RGB) in 1" in said assert "Nothing is proposed" in said and "R_HETEROGENEOUS_LAYOUT_NOT_ENABLED" in said - assert line.per_folder.selected_index == 0 # the menu is open + # owner, 25 November 2026: one answer for all folders, the folders on demand + assert "choose one type for all folders in the box" in said + assert line.per_folder.selected_index is None and ui.is_visible(line.apply) assert line.apply.disabled and "choose a type in the box" in _text(line.blocker.value) assert not line.types.store.saved.units # nothing was applied diff --git a/tests/test_notebook_small_cleanups.py b/tests/test_notebook_small_cleanups.py index 4090143b..27ede0a0 100644 --- a/tests/test_notebook_small_cleanups.py +++ b/tests/test_notebook_small_cleanups.py @@ -31,6 +31,9 @@ from morphobricks_preprocessing.notebook_check_view import checks_html # noqa: E402 from test_notebook_axes_quick import stepper # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def test_a_read_failure_names_the_image_relative_to_the_experiment_folder(tmp_path): write_rgb(tmp_path / "ctrl" / "rgb.tif") diff --git a/tests/test_notebook_stains_na.py b/tests/test_notebook_stains_na.py index b5066220..6e7ebe92 100644 --- a/tests/test_notebook_stains_na.py +++ b/tests/test_notebook_stains_na.py @@ -25,6 +25,9 @@ from morphobricks_preprocessing.draft_answers import UnitAnswer # noqa: E402 from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + FOLDERS = ["ctrl/rep1", "ctrl/rep2", "drug/rep1", "drug/rep2"] CHANNELS = 2 # step 3, 0-based: the stains and the tags STAINS = TAGS = CHANNELS diff --git a/tests/test_notebook_stepper.py b/tests/test_notebook_stepper.py index af997b66..49707334 100644 --- a/tests/test_notebook_stepper.py +++ b/tests/test_notebook_stepper.py @@ -24,6 +24,9 @@ ) from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + ORDER = ["Images", "Axes", "Channels", "Masks", "Design", "Check and save", "Run"] """What the files hold first (images, axes, channels, masks), what it means after (design).""" AXES, CHANNELS, MASKS, DESIGN, SAVE, RUN = range(1, 7) diff --git a/tests/test_notebook_tag_blocks.py b/tests/test_notebook_tag_blocks.py index 361da00f..bcde089e 100644 --- a/tests/test_notebook_tag_blocks.py +++ b/tests/test_notebook_tag_blocks.py @@ -13,7 +13,8 @@ from morphobricks_preprocessing.description_file import DRAFT_FILENAME from test_notebook_channels import ACTIN, DNA, PHASE, open_screen, set_labels, tree -pytestmark = pytest.mark.usefixtures("statement_off") # the blocks: the statement unticked +# the blocks: the statement unticked, the per-unit grid also in the stepper +pytestmark = pytest.mark.usefixtures("statement_off", "legacy_grid") pytest.importorskip("ipywidgets") pytest.importorskip("matplotlib") diff --git a/tests/test_notebook_tag_by_repeat_scope.py b/tests/test_notebook_tag_by_repeat_scope.py index 2cc82ce8..704e567d 100644 --- a/tests/test_notebook_tag_by_repeat_scope.py +++ b/tests/test_notebook_tag_by_repeat_scope.py @@ -32,6 +32,9 @@ from test_notebook_tag_by_repeat_oneclick import GONE, OTHER, _fast, _strict # noqa: E402 from test_notebook_tag_by_repeat_recheck import _recheck # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def _visible(widget): """Return the text on screen: a closed accordion's contents are not.""" diff --git a/tests/test_notebook_tag_like.py b/tests/test_notebook_tag_like.py index 1cf0e659..cea29eff 100644 --- a/tests/test_notebook_tag_like.py +++ b/tests/test_notebook_tag_like.py @@ -14,7 +14,8 @@ from morphobricks_preprocessing.description_file import DRAFT_FILENAME from test_notebook_check_save import KINDS, TAGS, add_folder, answer_all, decode -pytestmark = pytest.mark.usefixtures("statement_off") # the blocks: the statement unticked +# the blocks: the statement unticked, the per-unit grid also in the stepper +pytestmark = pytest.mark.usefixtures("statement_off", "legacy_grid") pytest.importorskip("ipywidgets") pytest.importorskip("matplotlib") diff --git a/tests/test_notebook_tag_matrix.py b/tests/test_notebook_tag_matrix.py index f33aa8ef..ab4b8c90 100644 --- a/tests/test_notebook_tag_matrix.py +++ b/tests/test_notebook_tag_matrix.py @@ -33,6 +33,9 @@ from test_notebook_row_fold import stepper # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + TAGS = ("DNA", "ACTIN", "PHASE") UNITS = [(c, b, t) for c in ("ctrl", "drug") for b in ("rep1", "rep2") for t in ("t1", "t2")] LEAD = UNITS[0] diff --git a/tests/test_notebook_tag_untick.py b/tests/test_notebook_tag_untick.py index b31d457a..b9549640 100644 --- a/tests/test_notebook_tag_untick.py +++ b/tests/test_notebook_tag_untick.py @@ -22,6 +22,9 @@ from test_notebook_row_fold import stepper # noqa: E402 from test_notebook_tag_matrix import SAVED, TAGS, _add # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def _stale_aliases(tmp_path): """Save DAPI, Actin, Ch3 as aliases, then drop the saved units' header names. diff --git a/tests/test_ome_zarr_copy.py b/tests/test_ome_zarr_copy.py index 74bd2a07..7f2cff9c 100644 --- a/tests/test_ome_zarr_copy.py +++ b/tests/test_ome_zarr_copy.py @@ -33,6 +33,9 @@ from test_notebook_check_save import FOLDERS, answer_all # noqa: E402 from test_notebook_projection import NAMES, digests, write_stacks # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + def _text(text): return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", text))).strip() diff --git a/tests/test_reconfirm_scope.py b/tests/test_reconfirm_scope.py index 6cad1898..b39bc5df 100644 --- a/tests/test_reconfirm_scope.py +++ b/tests/test_reconfirm_scope.py @@ -25,6 +25,9 @@ from test_notebook_axes_quick import stepper # noqa: E402 from test_notebook_prerelease import _tag, _text # noqa: E402 +# the per-unit grid driven through the stepper (the guided step is pinned by its own tests) +pytestmark = pytest.mark.usefixtures("legacy_grid") + GONE = "drug/rep2" NO_NAMES = object() """The rewritten header states no channel name at all (not one empty name)."""