From 0597be51a33cda93e84bb8e28265101b87d0afe0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 11:49:57 +0000 Subject: [PATCH 1/2] Cell 5: ask what each mask is; show Register's steps as they go (#574 items 6-7) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Item 6: the tick box "Declare as separate objects" under a TOML preview is replaced by a question per mask type with no answer chosen: "Each object has its own number (label image: every cell/nucleus is a separate object)" or "Foreground / background only (binary mask)", with one sentence on why we ask. The TOML is shown only folded (
). The recorded value (representation = "instances") and the refusal while a mask type is unanswered are unchanged; a binary answer is refused beside the button (Cellpose gives each object its own number), nothing records it. Item 7: Register showed nothing in cell 5 while it read, per image of a verify_content run, 4 whole files (SHA-256: cell 5's checks, the app's run, its pre-publish check, the tissue-mask step's opening) and per mask 5 (run, pre-publish check, mask step fingerprints before/after, pixels). Each read is a check or the data itself, so none is removed; reads per file and the normalized run-folder digests are identical to main. RegisterWait (notebook_progress.Wait and its ticking thread, #567) shows "Step k of 5 · " with the elapsed time and the step's own line: the run's checks counted through open_run(checking=) (open_checks and run_inputs.open_checked, identical to #575's hunks), and the app's own wait lines copied while each step runs. Notebook cells are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- AGENTS.md | 7 +- CHANGELOG.md | 1 + docs/user_guide.md | 17 +- pyproject.toml | 2 + .../notebook_mask_register.py | 220 +++++++++---- .../notebook_register_progress.py | 132 ++++++++ src/morphobricks_preprocessing/open_checks.py | 68 ++++ src/morphobricks_preprocessing/run_inputs.py | 46 ++- .../segmentation_cellpose_run.py | 16 +- tests/test_mask_register_progress.py | 310 ++++++++++++++++++ tests/test_notebook_preprocessing_cellpose.py | 22 +- 11 files changed, 738 insertions(+), 103 deletions(-) create mode 100644 src/morphobricks_preprocessing/notebook_register_progress.py create mode 100644 src/morphobricks_preprocessing/open_checks.py create mode 100644 tests/test_mask_register_progress.py diff --git a/AGENTS.md b/AGENTS.md index 39b56123..a4861871 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -209,6 +209,8 @@ src/morphobricks_preprocessing/ preprocessing's discovery and pairing; RunInputs.open raises UnrecordedFilesError for them (PP-8b, contract §9.1) run_inputs_text.py the texts RunInputs refuses a run with (moved from run_inputs.py in PP-12) + open_checks.py OPEN_PHASES, counted: the phases of opening a run told to a progress callback + (run_inputs.open_checked: RunInputs.open with checking=; #574) (pure) run_inputs_stopped.py stopped_run_refusal: the one reader of discovery_report.json for the bricks; RunInputs.open raises RunStoppedError (RUN_FOLDER_STOPPED, the stopped run's error issues as the report records them) or @@ -312,8 +314,9 @@ src/morphobricks_preprocessing/ on the Preprocessing app's finished run; cellpose_install.py installs Cellpose 4.2.1.1 only on the user's tick (restart when numpy/opencv changed); notebook_mask_register.py register_step(app, segmentation): cell 5, a - declaration to tick per mask type, then the app's own check, Masks answer, - save, run and Describe the masks + question per mask type (objects or binary, none chosen; objects registered), + then the app's own check, Masks answer, save, run and Describe the masks, + each step shown by notebook_register_progress.py RegisterWait (#574) notebook_cellpose_preview.py MaskResult, preview_figures: the example result as ZeroCostDL4Mic draws it (cellpose.plot.show_segmentation), one result per mask notebook_cellpose_channels.py ChannelPicker, MaskTarget: the output's masks (Both: diff --git a/CHANGELOG.md b/CHANGELOG.md index 841cf7f1..9e4d8883 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased - **The run's masks counter ends at N of N (follow-up of #567).** The mask header check reported "done of N" before each mask and nothing after the last, so the run's wait stopped at "N-1 of N" (preflight's closing `("masks", 1, 1, "")` is a placeholder the wait ignores unless the total is 1). The check now also reports `(total, total, "")` after the last mask; what is read and recorded is unchanged. A stray docstring in `notebook_progress` (the one of `PREPARING` sat after `COUNTED_PHASES`) is back under `PREPARING`. Tests: `tests/test_run_checking_progress.py`, `tests/test_notebook_progress.py`. +- **Cellpose cell 5, Register the masks: a clear question, and every step shown as it goes (#574, items 6 and 7; owner's Colab test of 26 November 2026).** Item 6: the tick box "Declare Cells as separate objects" under a TOML preview was awkward. Each mask type is now asked what it is, with no answer chosen: "Each object has its own number (label image: every cell/nucleus is a separate object)" or "Foreground / background only (binary mask)", with one sentence on why: "We ask because the two are measured differently, and we never guess which one a file is." The TOML is shown only folded (`
`) under the question. What is recorded is unchanged (`representation = "instances"` through the app's *Masks* question), and so is the refusal while a mask type is unanswered (the button stays disabled, saying "choose what Cells is", and pressing does nothing). Cellpose gives each object its own number, so the binary answer is refused beside the button, saying so; nothing records it (`BINARY_REFUSED`). Item 7: after **Register the masks** something ran for a long time with nothing in cell 5. Measured with a patched opener (`builtins.open`, bytes read per file) on main: per image of a `verify_content` run (the notebook's default), the press reads every image whole 4 times, each for its content SHA-256 (cell 5's own checks of the segmented run, the app's run, its check before it publishes, and the app's tissue-mask step that opens the run after it), and every mask whole 5 times (the run and its check before publishing, the mask step's fingerprints before and after reading, and its pixels for the piece counts, 1 per mask); a press that stops for the axes reads every image whole once, and showing cell 5 once more. The app drew its own waits in cell 3. Every one of these reads is a check or the data itself, so none was removed: what is read, and the run folder, are unchanged (normalized digests of every file of the run folder, and the reads per file, equal before and after). Cell 5 now shows the press with the waits of #567 (`notebook_progress.Wait` and its ticking thread, `notebook_register_progress.RegisterWait`): "Step k of 5 · " with the elapsed time, and under it the step's own line: the run's checks counted ("Reading each image whole for its content SHA-256 · 2 of 200 · ctrl/rep1/a.tif"), through `segmentation_cellpose_run.open_run(checking=)` (`run_inputs.open_checked` and `open_checks`, the same code as #575, unchanged checks), and the app's own wait lines of its folder check, run and mask step, copied as the app draws them; then "Took m:ss." (or "Stopped after m:ss."). The button is disabled while it goes. Cell 5's text is unchanged. `tests/test_mask_register_progress.py`. - **`piece_counts` counts the pieces of masks of objects by runs (#69).** It sorted every pixel (`np.unique(..., return_inverse=True)`, most of its time) and labelled each label again in its bounding box, so labels spread over the plane read it once each. Each row is now cut into runs of one label and runs of one label in neighbouring rows that touch (8-connected, from `masks.binary.STRUCTURE`) are joined with `scipy.sparse.csgraph.connected_components` (new pure module `mask_pieces`; `mask_scan.piece_counts` is the same function, imported). On pixel-scale masks (noise, checkerboards) runs are almost pixels and that graph needs several times the memory of the sort, so above `RUNS_PER_PIXEL_LIMIT` = 0.25 runs per pixel the former route is taken, unchanged. The results are byte-identical either way (labels in the mask's pixel type, counts `int64`): a property test compares both routes, forced and as chosen, with the former function, kept in the test as the reference, on random masks of every label pixel type (touching labels, holes, single pixels, edges, corners, no background, empty) and on the benchmark masks; every digest of `tools/benchmark_kernels.py --group masks` is unchanged, including its new pixel-scale cases (`benchmark_inputs.pixel_mask`). On the benchmark machine `piece_counts` of the 4096 px cells mask went from 2.1 to 2.3 s to 0.07 to 0.10 s and one position's scan from 4.9 to 5.1 s to 0.9 to 1.0 s; the pixel-scale masks take the time and memory they took before (`docs/benchmarks.md`). Outside the former results: a mask with a side of length 0 now has no labels, where the former function failed inside SciPy; a mask that is not 2D is refused with a `ValueError` saying so (it was a SciPy `RuntimeError`, or no labels when it was all background). **The mask scan refuses a mask plane of no pixels** (`mask_without_pixels`, naming the mask): before, SciPy's failure in `piece_counts` was its only guard, and with no labels such a plane would have counted as an image and as a plane of at most one label in its mask type's kind. `pair_counts` and the repeated pair work of #69 are not changed. `tests/test_mask_pieces.py`, `tests/test_mask_scan.py`. - **The run shows its own folder and header check, and that check is no longer quadratic (owner Colab test of v0.9.0, 25 November 2026).** On a large mixed-layout experiment, *Run* showed "Preparing: checking the folders and the image headers again · 0:00 elapsed" for 10-15 minutes before the first image: the run checks every header again (bound to its fingerprint) with no progress reported, and the elapsed time was redrawn only on a progress report. The run now reports that check through `RunMode(checking=...)` (preflight's `(phase, done, total, path)`, operational only like `workers`; `run_experiment`'s parameters are unchanged), and the notebook shows each phase and each header of how many ("Preparing: reading the image headers again · 120 of 24,000"), with the elapsed time redrawn every second by `Wait.ticking()` while the run works. While it goes, the notebook says that a cell run meanwhile waits for it, and how to interrupt it. Two steps of the check were O(n²): each image's staging key took `MetadataReport.dtype` (a pass over every header) and the mask-name screen compared each image's name with every other one (`mask_names._mask_owner` now looks up the prefixes of the name). The outputs are byte for byte the same (`plane_histograms.csv`, `experiment_design.csv`, `image_qc.csv` of a 4,800-image three- and two-channel tree); the check before the first image took 30.0 s → 10.3 s for 12,000 images and 72-75 s → 24-27 s for 24,000 on local disk (`tests/test_run_checking_progress.py`). In a `verify_content` run (the notebook's default, and any run on a fresh output folder) the run then reads every image whole for its content SHA-256 before the first pixel is read: on Google Drive that pass, not the header check, is what took minutes (owner: about 200 images, 10-15 minutes). It is now reported too, as the phase `contents` (`run.phases.CONTENTS`, "Preparing: reading each image whole for its content SHA-256 · 12 of 200"); what is read and verified is unchanged. - **Earlier work that does not record its experiment folder no longer leaves the stepper at a dead end (owner's Colab test of v0.9.0 at ca3b3c6).** An output folder holding only saved answers (here an older version's `morphobricks.draft.json`) showed *"The experiment folder it is of is not recorded … Enter the experiment folder and click Check folder"*: the stepper has no *Check folder* button (its check, *Looks right: read all image headers*, stays disabled until **Scan the folders**), and entering the folder showed the same message again, with no scan and no picture. Now the experiment folder entered is scanned at once on the stepper (folder walk and one picture; nothing is written), the message names the stepper's own buttons, and the check, on the user's click, reads the saved answers as always. Saved answers written by another version of the software (`DraftFileError` `unknown_version`, `unknown_key` or `spec_commit_mismatch`; the owner's file is format 3, `unknown_version`) are not earlier work (`EarlierWork.old_answers`): one line says they are not used and the file is left as it is, and the experiment folder entered is scanned and shown as above (an early **Scan the folders** click, before the typed folder reached the kernel, is made good when it arrives). The same scan follows a record and a run that name different folders. Each message names the buttons of the layout shown (the stacked pages say **Check folder**). Tests: `tests/test_notebook_restore.py`. diff --git a/docs/user_guide.md b/docs/user_guide.md index 9aa3b28c..ae1a5339 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -365,11 +365,18 @@ run the experiment in the app of cell 3. Then: reuses it) and **Segment** (it reuses the loaded model, and says in one line exactly which model and settings it will use, in amber with what differs when the last Preview used others). One line after the batch points to cell 5. -- **5. Register the masks** shows, for each mask type cell 4 wrote, the declaration it would - add (`[masks.Cells]` with `source_type = "Cells"` and `representation = "instances"`). Tick - each one and press **Register the masks**: the app of cell 3 then checks the folders again - with the masks folder, answers the mask on **Masks**, saves the description, runs again - (the histograms of unchanged images are reused) and describes the masks. Masks written into +- **5. Register the masks** asks, for each mask type cell 4 wrote, what the mask is, with no + answer chosen: *Each object has its own number (label image: every cell/nucleus is a + separate object)* or *Foreground / background only (binary mask)*. They are measured + differently, and the notebook never guesses which one a file is. Cellpose gives each object + its own number, so only the first is registered (the second is refused, saying why); the + declaration it adds (`[masks.Cells]` with `source_type = "Cells"` and `representation = + "instances"`) is shown folded under the question. Answer each one and press **Register the + masks**: the app of cell 3 then checks the folders again with the masks folder, answers the + mask on **Masks**, saves the description, runs again (the histograms of unchanged images are + reused) and describes the masks. Each step is shown under the button as it goes ("Step 4 of + 5 · Running again…", its elapsed time, and the step's own line: the image read now, "n of + N"), then how long it took. Masks written into the masks folder the run already used are fine. If its folder check asks you to confirm the axes again, do it in cell 3 (step **Axes**) and press the button again (or run cell 5 again). It refuses, changing nothing, a mask type that collides with a mask already declared, diff --git a/pyproject.toml b/pyproject.toml index 00e113d2..f6b94bc1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -156,6 +156,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.name_issues" = "pure" "morphobricks_preprocessing.run.phases" = "pure" "morphobricks_preprocessing.ome_header" = "io" +"morphobricks_preprocessing.open_checks" = "pure" "morphobricks_preprocessing.tiff_colour" = "io" "morphobricks_preprocessing.tiff_axes" = "io" "morphobricks_preprocessing.rgb_override" = "pure" @@ -195,6 +196,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.notebook_cellpose_summary" = "ui" "morphobricks_preprocessing.notebook_cellpose_view" = "ui" "morphobricks_preprocessing.notebook_mask_register" = "ui" +"morphobricks_preprocessing.notebook_register_progress" = "ui" "morphobricks_preprocessing.notebook_preprocessing_cellpose" = "ui" "morphobricks_preprocessing.notebook_stop" = "ui" "morphobricks_preprocessing.notebook_channels" = "ui" diff --git a/src/morphobricks_preprocessing/notebook_mask_register.py b/src/morphobricks_preprocessing/notebook_mask_register.py index ccf0a8e2..756da90f 100644 --- a/src/morphobricks_preprocessing/notebook_mask_register.py +++ b/src/morphobricks_preprocessing/notebook_mask_register.py @@ -1,10 +1,14 @@ """Cell 5 of the combined notebook: declare the masks cell 4 wrote, rescan, describe them. -One declaration is offered per mask type cell 4 wrote, prefilled from the segmentation: -``[masks.]`` with ``source_type = ""`` and ``representation = "instances"`` -(Cellpose writes one label per object). Nothing is declared until the user ticks each one and -presses **Register the masks**. Then the Preprocessing app's own code does the rest, the same -code as its buttons (no second implementation): +For each mask type cell 4 wrote, the user says what the mask is, with no answer chosen for +them (owner, 26 Nov 2026, #574 item 6): *each object has its own number* (a label image) or +*foreground / background only* (a binary mask). The two are measured differently and a file is +never guessed to be one or the other. Cellpose writes one number per object, so only the first +is registered: ``[masks.]`` with ``source_type = ""`` and ``representation = +"instances"`` (shown folded, under the question); the second is refused, saying why. Nothing is +declared until every mask type is answered and **Register the masks** is pressed. Then the +Preprocessing app's own code does the rest, the same code as its buttons (no second +implementation), each step shown in cell 5 as it goes (:mod:`.notebook_register_progress`): 1. the app's folder check with the masks folder (``check_folder``, *Scan the folders*); 2. each mask answered on the app's *Masks* question (its ID box and its choice, which save the @@ -42,9 +46,11 @@ from .description_identity import nfc from .folder_rules import masks_folder_issues from .manifest import MANIFEST_FILENAME, ManifestFormatError, read_manifest -from .mask_answers import INSTANCES +from .mask_answers import BINARY, INSTANCES from .notebook_cellpose_app import app_folders +from .notebook_register_progress import RegisterWait from .notebook_render import blocked_line +from .open_checks import Checking, quiet from .report import mapping_summary from .run_inputs import RunInputsError, UnrecordedFilesError from .segmentation_cellpose_run import manifest_sha256, open_run @@ -91,6 +97,22 @@ "step Axes, confirm the recorded axes, then press Register the masks again. Nothing was " "declared." ) +CHOICES = [ + ( + "Each object has its own number (label image: every cell/nucleus is a separate object)", + INSTANCES, + ), + ("Foreground / background only (binary mask)", BINARY), +] +"""The answers to "what is this mask?", in this order; none is chosen for the user.""" +WHY_WE_ASK = ( + "We ask because the two are measured differently, and we never guess which one a file is." +) +BINARY_REFUSED = ( + "{mask_type} cannot be registered as foreground / background only: cell 4 wrote it with " + "Cellpose, which gives each object its own number" +) +"""Why a binary answer is not registered (a phrase beside the disabled button).""" NOT_SAVED = ( "Check and save did not save the description: open cell 3, step Check and save, answer " "what it lists, then press Register the masks again here." @@ -154,11 +176,15 @@ def _app_run(app: object, rechecked: bool) -> tuple[str, str]: return run, masks -def refusal(app: object, segmentation: object, *, rechecked: bool = False) -> str: +def refusal( + app: object, segmentation: object, *, rechecked: bool = False, checking: Checking = quiet +) -> str: """Return why the masks of cell 4 cannot be registered in the app's run, or "". ``rechecked``: cell 5 made the app's folder check for this run (also read from the segmentation's ``rechecked_run``, so cell 5 run again after the axes stop continues). + ``checking`` is told each phase of opening the run (:func:`.segmentation_cellpose_run. + open_run`); it changes nothing checked or decided. """ types = written_types(segmentation) if not types: @@ -179,7 +205,7 @@ def refusal(app: object, segmentation: object, *, rechecked: bool = False) -> st if app_masks and Path(app_masks).resolve() != masks: return OTHER_MASKS.format(segmented=masks, app_masks=app_masks) try: - open_run(os.fspath(segmented)) + open_run(os.fspath(segmented), checking=checking) except UnrecordedFilesError as exc: if not _only_written(exc, masks, types): return CHANGED.format(reason=exc) @@ -252,50 +278,71 @@ def _other_experiment(app: object, inputs: object) -> str: class MaskRegistration(widgets.VBox): - """Cell 5's widget: one declaration to tick per mask type, and **Register the masks**.""" + """Cell 5's widget: what each mask type is, and **Register the masks**.""" def __init__(self, app: object, segmentation: object) -> None: - """Offer the declarations, or show why the masks cannot be registered.""" + """Ask what each mask is, or show why the masks cannot be registered.""" super().__init__(layout=widgets.Layout(width="99%")) self.app, self.segmentation = app, segmentation self.status = widgets.HTML() - self.ticks: dict[str, widgets.Checkbox] = {} + self.choices: dict[str, widgets.RadioButtons] = {} self.registered = False why = refusal(app, segmentation) if why: self.status.value = ui.status("error", "The masks cannot be registered", [why]) self.children = [widgets.HTML(ui.STYLE_CSS), self.status] return - rows = [] - for mask_type in written_types(segmentation): - tick = widgets.Checkbox( - value=False, - description=f"Declare {mask_type} as separate objects", - indent=False, - layout=widgets.Layout(width="auto"), - ) - tick.observe(lambda _: self._update(), names="value") - self.ticks[mask_type] = tick - section = html.escape(toml_section(mask_type)) - rows += [widgets.HTML(f"
{section}
"), tick] + rows = [self._question(mask_type) for mask_type in written_types(segmentation)] self.button = ui.button("Register the masks", icon="check", main=True) self.button.on_click(lambda _: self.register()) self.blocker = widgets.HTML() + self.progress, self.progress_detail = widgets.HTML(), widgets.HTML() self._update() text = ( - "Each mask type cell 4 wrote, as it would be declared in the experiment description. " - "Tick each one you confirm, then press Register the masks: the app of cell 3 " - "checks the folders again with the masks folder, saves the description, runs again " - "(the histograms are reused) and describes the masks." + "For each mask type cell 4 wrote, say what the mask is. " + f"{html.escape(WHY_WE_ASK)} Then press Register the masks: the app of " + "cell 3 checks the folders again with the masks folder, saves the description, " + "runs again (the histograms are reused) and describes the masks; each step is " + "shown here as it goes." ) - body = [ui.help_text(text), *rows, widgets.HBox([self.button, self.blocker]), self.status] + body = [ + ui.help_text(text), + *rows, + widgets.HBox([self.button, self.blocker]), + self.progress, + self.progress_detail, + self.status, + ] self.children = [widgets.HTML(ui.STYLE_CSS), ui.card("Register the masks", body)] + def _question(self, mask_type: str) -> widgets.VBox: + """Return the question about ``mask_type``, with no answer chosen, and its declaration. + + The declaration it adds to the description is shown folded (``
``). + """ + choice = widgets.RadioButtons( + options=CHOICES, value=None, layout=widgets.Layout(width="auto") + ) + choice.observe(lambda _: self._update(), names="value") + self.choices[mask_type] = choice + section = html.escape(toml_section(mask_type)) + declared = ( + "
What registering it as separate objects adds " + f"to the experiment description
{section}
" + ) + title = f"{html.escape(mask_type)}: what is this mask?" + return widgets.VBox([widgets.HTML(title), choice, widgets.HTML(declared)]) + def _update(self) -> None: - """Enable the button once every declaration is ticked, saying which are not.""" - left = [t for t, tick in self.ticks.items() if not tick.value] - self.button.disabled = bool(left) - reasons = [f"tick the declaration of {', '.join(left)}"] if left else [] + """Enable the button once every mask type is answered as objects, saying what is left.""" + left = [t for t, choice in self.choices.items() if choice.value is None] + reasons = [f"choose what {', '.join(left)} is"] if left else [] + reasons += [ + BINARY_REFUSED.format(mask_type=t) + for t, choice in self.choices.items() + if choice.value == BINARY + ] + self.button.disabled = bool(reasons) self.blocker.value = blocked_line(reasons) def _stop(self, text: str) -> bool: @@ -304,54 +351,91 @@ def _stop(self, text: str) -> bool: return False def register(self) -> bool: - """Declare the ticked masks through the app, save, run and describe; True when done.""" + """Declare the masks through the app, save, run and describe; True when done. + + Each step is shown under the button while it goes (:class:`.RegisterWait`), and the + button is disabled meanwhile. + """ if self.button.disabled: return False - why = refusal(self.app, self.segmentation) + self.button.disabled = True + self.status.value = "" + try: + with RegisterWait(self.progress, self.progress_detail).running() as wait: + return self._register(wait) + finally: + self._update() + + def _register(self, wait: RegisterWait) -> bool: + """Do the steps of :meth:`register`, each named by ``wait``; True when done.""" + with wait.step("run"): + why = refusal(self.app, self.segmentation, checking=wait.checking) if why: return self._stop(why) + self._check_folders(wait) + app = self.app + if app.confirmed_mapping is None: + return self._stop(AXES_AGAIN) + why = _other_experiment(app, self.segmentation.workflow.inputs) + if why: # the axes stop lets the user change the app: check it is still the run's + return self._stop(why) + with wait.step("save"): + why = self._answer_masks() + if why: + return self._stop(why) + if not app.save_experiment(): + return self._stop(NOT_SAVED) + with wait.step("rerun", getattr(app, "run_status", None)): + result = app.run() + if result is None or not result.written: + return self._stop("The run of cell 3 stopped: its step Run says why.") + # Kept on cell 4's step: this publication is the registration's (cell 5 run again). + self.segmentation.registered_manifest = manifest_sha256(Path(result.output_folder)) + with wait.step("describe", getattr(app, "mask_step_status", None)): + app.mask_step_button.click() # the app's Describe the masks + self.registered = True + self.status.value = self._registered_html(result) + return True + + def _check_folders(self, wait: RegisterWait) -> None: + """Make the app's folder check with the masks folder, unless its last one has them.""" app, masks = self.app, Path(self.segmentation.workflow.masks_root).resolve() found = getattr(app.preflight, "masks", None) checked = getattr(found, "folder", None) if ( - checked is None - or Path(checked).resolve() != masks - or any(t not in found.types for t in self.ticks) # checked before cell 4 wrote + checked is not None + and Path(checked).resolve() == masks + and all(t in found.types for t in self.choices) # else checked before cell 4 wrote ): + return + with wait.step("folders", getattr(app, "folder_status", None)): app.masks_folder.value = os.fspath(masks) app.check_folder() # the app's Scan the folders, now with the masks folder - # Kept on cell 4's step, not this widget: cell 5 run again continues from here. - self.segmentation.rechecked_run = Path( - self.segmentation.workflow.inputs.output_folder - ).resolve() - if app.confirmed_mapping is None: - return self._stop(AXES_AGAIN) - why = _other_experiment(app, self.segmentation.workflow.inputs) - if why: # the axes stop lets the user change the app: check it is still the run's - return self._stop(why) - for mask_type in self.ticks: - question = app.mask_card.questions.get(mask_type) + # Kept on cell 4's step, not this widget: cell 5 run again continues from here. + self.segmentation.rechecked_run = Path( + self.segmentation.workflow.inputs.output_folder + ).resolve() + + def _answer_masks(self) -> str: + """Answer each mask on the app's *Masks* question as objects; return a refusal or "".""" + for mask_type in self.choices: + question = self.app.mask_card.questions.get(mask_type) if question is None: - return self._stop(f"The folder check of cell 3 found no {mask_type} masks.") + return f"The folder check of cell 3 found no {mask_type} masks." question.id_box.value = mask_type question.choice.value = INSTANCES if question.saved is None or question.saved[:2] != (mask_type, INSTANCES): - return self._stop(f"{mask_type}: {_plain(question.message.value)}") - if not app.save_experiment(): - return self._stop(NOT_SAVED) - result = app.run() - if result is None or not result.written: - return self._stop("The run of cell 3 stopped: its step Run says why.") - # Kept on cell 4's step: this publication is the registration's (cell 5 run again). - self.segmentation.registered_manifest = manifest_sha256(Path(result.output_folder)) - app.mask_step_button.click() # the app's Describe the masks - self.registered = True - self.status.value = ( + return f"{mask_type}: {_plain(question.message.value)}" + return "" + + def _registered_html(self, result: object) -> str: + """Return the card saying the masks are registered, with the app's mask step's.""" + return ( ui.status( "ok", "The masks are registered", [ - f"Declared: {', '.join(self.ticks)}; the run in {result.output_folder} now " + f"Declared: {', '.join(self.choices)}; the run in {result.output_folder} now " "records them and is ready for MorphoFeature.", f"Histograms reused for {len(result.unchanged)} images; images read again: " f"{len(result.read)}" @@ -359,9 +443,8 @@ def register(self) -> bool: + ".", ], ) - + app.mask_step_status.value + + self.app.mask_step_status.value ) - return True def _plain(text: str) -> str: @@ -374,4 +457,13 @@ def register_step(app: object, segmentation: object) -> MaskRegistration: return MaskRegistration(app, segmentation) -__all__ = ["MaskRegistration", "refusal", "register_step", "toml_section", "written_types"] +__all__ = [ + "BINARY_REFUSED", + "CHOICES", + "WHY_WE_ASK", + "MaskRegistration", + "refusal", + "register_step", + "toml_section", + "written_types", +] diff --git a/src/morphobricks_preprocessing/notebook_register_progress.py b/src/morphobricks_preprocessing/notebook_register_progress.py new file mode 100644 index 00000000..b037f3b8 --- /dev/null +++ b/src/morphobricks_preprocessing/notebook_register_progress.py @@ -0,0 +1,132 @@ +"""The wait shown while cell 5 registers the masks (owner Colab test, 26 Nov 2026, #574 item 7). + +**Register the masks** runs, one after another, the checks of the run cell 4 segmented and the +app's own steps: its folder check with the masks folder, its *Check and save*, its run and its +*Describe the masks*. In a ``verify_content`` run (the notebook's default) the run's checks read +every image whole for its SHA-256, the app's run reads every image and mask whole again for +theirs, and *Describe the masks* reads every mask; the app draws each wait in its own step, in +cell 3, far above cell 5, which showed nothing. :class:`RegisterWait` shows them in cell 5 with +the waits of #567 (:class:`.notebook_progress.Wait` and its ticking thread): one line +"Step k of N · " whose elapsed time goes on, and under it the step's own line: the run's +checks, counted here ("n of N" with the image read now), and the app's own wait line of the +folder check, the run and the mask step, copied as the app draws it. Nothing here reads a file +or decides anything. +""" + +from __future__ import annotations + +import html +import time +from collections.abc import Callable, Iterator +from contextlib import contextmanager + +import ipywidgets as widgets + +from .notebook_progress import Wait + +STEPS = { + "run": "Checking the run cell 4 segmented and its images", + "folders": "Checking the folders again with the masks folder", + "save": "Answering each mask and saving the description", + "rerun": "Running again (the histograms of unchanged images are reused)", + "describe": "Describing the masks", +} +"""The steps of **Register the masks**, in order; the folder check is made only when needed.""" +CHECKS = { + "run": "Reading the run's manifest, table and description", + "images": "Checking that each image is the one the run read (size and date)", + "contents": "Reading each image whole for its content SHA-256", + "masks": "Checking that each mask is the one the run read (size and date)", + "unrecorded": "Listing the folders for files added since the run", +} +"""What the step line says in each phase of the run's checks (:data:`.open_checks.OPEN_PHASES`).""" +COUNTED = ("images", "contents", "masks") +"""The phases of the run's checks shown as done of total, each with its file.""" +TOOK = "Took {took}." +"""The line left once **Register the masks** ends, registered or refused (``{took}``: ``m:ss``).""" +STOPPED_AFTER = "Stopped after {took}." +"""The line left when an error or an interrupt went through it.""" + + +def step_label(key: str) -> str: + """Return the line of step ``key`` of :data:`STEPS`: ``"Step 2 of 5 · "``.""" + number = list(STEPS).index(key) + 1 + return f"Step {number} of {len(STEPS)} · {STEPS[key]}" + + +class RegisterWait: + """The wait of **Register the masks**: the step line, and the step's own line under it. + + Parameters + ---------- + line + The HTML widget of the step line (elapsed time of the whole press, ticking). + detail + The HTML widget of the step's own line (the run's checks, or the app's wait). + clock + Returns the time in seconds (monotonic); replaced in tests. + """ + + def __init__( + self, + line: widgets.HTML, + detail: widgets.HTML, + *, + clock: Callable[[], float] = time.monotonic, + ) -> None: + self.line, self.detail = line, detail + self.wait = Wait(line, bar=False, clock=clock) + self.checks = Wait(detail, clock=clock) + + @contextmanager + def running(self) -> Iterator[RegisterWait]: + """Show the wait while the block runs; then leave how long it took (or that it stopped).""" + self.wait.start(step_label("run")) + text = STOPPED_AFTER + try: + with self.wait.ticking(): + yield self + text = TOOK + finally: + self.detail.value = "" + took = html.escape(text.format(took=self.wait.took())) + self.line.value = f"
{took}
" + + @contextmanager + def step(self, key: str, shown: widgets.HTML | None = None) -> Iterator[None]: + """Name step ``key`` while the block runs; copy ``shown`` (the app's wait) under it. + + ``shown`` is the app's own status line of that step: each value the app draws there + while the block runs is drawn under the step line too, then the copy stops and the + line under it is emptied. + """ + if self.wait.label != step_label(key): + self.wait.phase(step_label(key)) + self.detail.value = "" + + def copy(change: dict) -> None: + self.detail.value = change["new"] + + if shown is not None: + shown.observe(copy, names="value") + try: + yield + finally: + if shown is not None: + shown.unobserve(copy, names="value") + self.detail.value = "" + + def checking(self, phase: str, done: int, total: int, path: str) -> None: + """Show the run's checks (``checking`` of :func:`.segmentation_cellpose_run.open_run`).""" + label = CHECKS[phase] + counted = phase in COUNTED + if self.checks.label != label: + if phase == "run" or not self.checks.label: # the first phase starts the clock + self.checks.start(label, total if counted else 0) + else: + self.checks.phase(label, total if counted else 0) + if counted: + self.checks.step(done, total, path) + + +__all__ = ["CHECKS", "COUNTED", "STEPS", "STOPPED_AFTER", "TOOK", "RegisterWait", "step_label"] diff --git a/src/morphobricks_preprocessing/open_checks.py b/src/morphobricks_preprocessing/open_checks.py new file mode 100644 index 00000000..f9cbcbdb --- /dev/null +++ b/src/morphobricks_preprocessing/open_checks.py @@ -0,0 +1,68 @@ +"""The phases of opening a run, told to a progress callback (owner Colab test, 26 Nov 2026). + +Opening a run (:func:`.run_inputs.open_checked`, :meth:`.run_inputs.RunInputs.open`) checks +every image and mask against the manifest before anything is used: on Google Drive, with a +``verify_content`` run of 200 images of 10-50 MB each, that took minutes with nothing on +screen (the Cellpose step **Folders**, issue #574). A caller that shows it passes +``checking(phase, done, total, path)``, the signature of the run's own checks +(:class:`.run.modes.RunMode` ``checking``, #567), told each phase of :data:`OPEN_PHASES`. +It changes nothing: the same files are checked, in the same order, with the same result. +Nothing here reads a file. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable, Iterator +from operator import attrgetter +from typing import TypeVar + +Checking = Callable[[str, int, int, str], None] +"""``checking(phase, done, total, path)``: a phase of :data:`OPEN_PHASES`, ``done`` of +``total`` items (0 of 0 for a phase that is not counted) and the item now checked.""" + +OPEN_PHASES = ("run", "images", "contents", "masks", "unrecorded") +"""In order: the manifest, table and description; each image's fingerprint (size and +modification time); each image's content SHA-256 (``verify_content`` runs only: every image +read whole); each mask's fingerprint; the folders listed for files added since the run.""" + +RELATIVE = attrgetter("relative_path") +"""The relative path of an image's manifest entry, as a progress line shows it.""" + +T = TypeVar("T") + + +def quiet(phase: str, done: int, total: int, path: str) -> None: + """Tell nothing: the ``checking`` of a caller that shows no progress.""" + + +def counted( + checking: Checking, phase: str, items: Iterable[T], path: Callable[[T], str] +) -> Iterator[T]: + """Yield ``items`` in order, telling ``checking`` before each one and once at the end. + + Parameters + ---------- + checking + The progress callback. + phase + The phase of :data:`OPEN_PHASES` these items are checked in. + items + What is checked, one after another. + path + The item's relative path, as shown. + + Yields + ------ + T + Each item, after ``checking(phase, done, total, path(item))``; then + ``checking(phase, total, total, "")``. + """ + items = list(items) + total = len(items) + for done, item in enumerate(items): + checking(phase, done, total, path(item)) + yield item + checking(phase, total, total, "") + + +__all__ = ["OPEN_PHASES", "RELATIVE", "Checking", "counted", "quiet"] diff --git a/src/morphobricks_preprocessing/run_inputs.py b/src/morphobricks_preprocessing/run_inputs.py index 4d2a42e7..53dc76ae 100644 --- a/src/morphobricks_preprocessing/run_inputs.py +++ b/src/morphobricks_preprocessing/run_inputs.py @@ -67,6 +67,7 @@ from .mask_conversion import ConversionInputs from .mask_record import shared_mask_text from .masks import FOLDER +from .open_checks import RELATIVE, Checking, counted, quiet from .plane_channels import read_xyc_plane from .planes import DEFAULT_MEMORY_LIMIT from .recorded_sizes import RecordedSize @@ -262,17 +263,7 @@ def open( ``RUN_FOLDER_REPORT_UNREADABLE``: the folder holds no manifest and its report cannot be read, or is of another report version; it names the file. """ - output = Path(output_folder).resolve() - # One generation of the outputs (contract §9): read again if a run published - # meanwhile. - inputs = read_stable(output, lambda: cls._read(output, experiment_root, masks_root)) - if inputs is None: - raise RunInputsError( - f"Another run kept publishing new results in {output} while they were being " - "opened. Open the run again once it has finished." - ) - inputs._check_files() - return inputs + return open_checked(output_folder, experiment_root, masks_root) @classmethod def _read( @@ -388,15 +379,18 @@ def histograms(self) -> tuple[PlaneRecord, ...]: """Return the table's rows, as read when the run was opened.""" return self.records - def _check_files(self) -> None: + def _check_files(self, checking: Checking = quiet) -> None: """Refuse changed or gone files, masks without axes or shared, unrecorded files.""" - changed = [e.relative_path for e in self.manifest.files if not self._unchanged(e)] + images = counted(checking, "images", self.manifest.files, RELATIVE) + changed = [e.relative_path for e in images if not self._unchanged(e)] if not changed and self.manifest.settings.verify_content: - changed = content_changed(self.manifest.files, self.experiment_root) + entries = counted(checking, "contents", self.manifest.files, RELATIVE) + changed = content_changed(entries, self.experiment_root) if changed: raise RunInputsError(_changed_text(changed)) recorded = (self.manifest.masks or {}).get("files", ()) - changed = [m["path"] for m in recorded if not self._mask_unchanged(m)] + masks = counted(checking, "masks", recorded, lambda m: m["path"]) + changed = [m["path"] for m in masks if not self._mask_unchanged(m)] if changed: raise RunInputsError(_changed_text(changed, "mask")) without_axes = [m["path"] for m in recorded if not m.get("axes") or not m.get("roles")] @@ -405,6 +399,7 @@ def _check_files(self) -> None: shared = shared_mask_text(recorded) if shared: raise RunInputsError(shared) + checking("unrecorded", 0, 0, "") try: unrecorded = unrecorded_files( self.manifest, self.experiment_root, self.masks_root, self.output_folder @@ -460,6 +455,27 @@ def _mask_unchanged(self, recorded: Mapping) -> bool: return False +def open_checked( + output_folder: str | os.PathLike, + experiment_root: str | os.PathLike | None = None, + masks_root: str | os.PathLike | None = None, + *, + checking: Checking = quiet, +) -> RunInputs: + """Open a run as :meth:`RunInputs.open` does, telling ``checking`` (:mod:`.open_checks`).""" + output = Path(output_folder).resolve() + checking("run", 0, 0, "") + # One generation of the outputs (contract §9): read again if a run published meanwhile. + inputs = read_stable(output, lambda: RunInputs._read(output, experiment_root, masks_root)) + if inputs is None: + raise RunInputsError( + f"Another run kept publishing new results in {output} while they were being " + "opened. Open the run again once it has finished." + ) + inputs._check_files(checking) + return inputs + + def _manifest(output: Path) -> tuple[RunManifest, str]: """Read an output folder's manifest and the SHA-256 of the bytes it was parsed from. diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_run.py b/src/morphobricks_preprocessing/segmentation_cellpose_run.py index ec136649..19d38de3 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose_run.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose_run.py @@ -11,7 +11,8 @@ from ._io import file_sha256 from .manifest import MANIFEST_FILENAME -from .run_inputs import RunInputs +from .open_checks import Checking, quiet +from .run_inputs import RunInputs, open_checked from .segmentation_cellpose_model import CELLPOSE_VERSION from .segmentation_record import SegmentationError, check_mask_type @@ -38,9 +39,12 @@ """The refusal of a preview, a batch or a record whose run manifest is no longer the opened one.""" -def open_run(run_folder: str) -> RunInputs: +def open_run(run_folder: str, *, checking: Checking = quiet) -> RunInputs: """Open the run in ``run_folder`` (preprocessing's own checks; refusals are unchanged). + ``checking`` is told each phase of the checks (:func:`.run_inputs.open_checked`); it + changes nothing they check or decide. + Raises ------ SegmentationError @@ -50,11 +54,11 @@ def open_run(run_folder: str) -> RunInputs: """ if not run_folder.strip(): raise SegmentationError("Give the run's output folder (the one holding run_manifest.json).") - return RunInputs.open(Path(run_folder.strip())) + return open_checked(Path(run_folder.strip()), checking=checking) -def open_pinned(run_folder: str) -> tuple[RunInputs, str | None]: - """Open the run (:func:`open_run`) and return it with the SHA-256 of its manifest. +def open_pinned(run_folder: str, *, checking: Checking = quiet) -> tuple[RunInputs, str | None]: + """Open the run (:func:`open_run`, with ``checking``) and return it with its manifest SHA-256. The SHA-256 is the snapshot's (:attr:`.run_inputs.RunInputs.manifest_sha256`: of the bytes the manifest was parsed from, review ar B2); a run published again before this returns is @@ -69,7 +73,7 @@ def open_pinned(run_folder: str) -> tuple[RunInputs, str | None]: RunInputsError For a run that cannot be opened. """ - inputs = open_run(run_folder) + inputs = open_run(run_folder, checking=checking) check_manifest(inputs, inputs.manifest_sha256) return inputs, inputs.manifest_sha256 diff --git a/tests/test_mask_register_progress.py b/tests/test_mask_register_progress.py new file mode 100644 index 00000000..9bbdcded --- /dev/null +++ b/tests/test_mask_register_progress.py @@ -0,0 +1,310 @@ +"""Cell 5's question and its wait (owner Colab test of 26 November 2026, issue #574 items 6-7). + +Item 6: "Declare Cells as separate objects" with a TOML preview was awkward. Each mask type is +now asked what it is, with no answer chosen: each object with its own number (a label image) or +foreground / background only (a binary mask); the TOML is folded under it. What is recorded, +and the refusal when nothing is chosen, are unchanged. + +Item 7: after **Register the masks** something ran for a long time with nothing in cell 5. It +reads, per image of a ``verify_content`` run, 4 whole files (the run's checks, then the app's +run, its check before it publishes and its tissue-mask step's opening, each for the content +SHA-256) and per mask 5 (the run, its check before publishing, the mask step's fingerprints +before and after, and the pixels); the app drew its waits in cell 3. Cell 5 now shows each step +with the waits of #567. What is read is unchanged: no check could read less without becoming +weaker (the reads per file are pinned here). +""" + +import os +from collections import Counter +from pathlib import Path + +import pytest + +from cellpose_stub import install +from channel_images import write_channels +from test_notebook_check_save import KINDS +from test_notebook_preprocessing_cellpose import ran_app, segment + +widgets = pytest.importorskip("ipywidgets") + +import builtins # noqa: E402 +import io # noqa: E402 + +import test_notebook_preprocessing_cellpose as cell_tests # noqa: E402 +from morphobricks_preprocessing import notebook_progress # noqa: E402 +from morphobricks_preprocessing.description_file import DESCRIPTION_FILENAME # noqa: E402 +from morphobricks_preprocessing.notebook_mask_register import ( # noqa: E402 + BINARY_REFUSED, + CHOICES, + WHY_WE_ASK, + refusal, + register_step, + toml_section, +) +from morphobricks_preprocessing.notebook_preprocessing_cellpose import ( # noqa: E402 + segmentation_step, +) +from morphobricks_preprocessing.notebook_register_progress import ( # noqa: E402 + CHECKS, + STOPPED_AFTER, + RegisterWait, + step_label, +) +from morphobricks_preprocessing.run_inputs import RunInputs # noqa: E402 + +pytestmark = pytest.mark.usefixtures("legacy_grid") + +SIDE = 256 +"""Images and masks large enough that reading a header is not reading the whole file.""" + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +@pytest.fixture +def larger(monkeypatch): + """Write the experiment of ``ran_app`` at :data:`SIDE` pixels.""" + + def add_folder(root, masks, folder, seed): + Path(masks).mkdir(parents=True, exist_ok=True) + write_channels(root / folder / "a.tif", ["DAPI", "Actin", "Ch3"], KINDS, seed, SIDE) + + monkeypatch.setattr(cell_tests, "add_folder", add_folder) + + +class Reads: + """Per file of the experiment and the masks folder: opens, and whole reads. + + A whole read is one opening of the file through which at least its size was read. + """ + + def __init__(self, base): + self.base = Path(base).resolve() + self.opens, self.whole = Counter(), Counter() + + def key(self, path): + where = Path(os.fspath(path)).resolve() + for folder in ("exp", "masks"): + if where.is_relative_to(self.base / folder): + return where.relative_to(self.base).as_posix() + return None + + +@pytest.fixture +def reads(monkeypatch, tmp_path): + """Count the reads with a patched opener (``builtins.open``, as tifffile and hashing use).""" + counted, real = Reads(tmp_path), builtins.open + + class Counting(io.BufferedReader): + def __init__(self, path, key): + super().__init__(io.FileIO(path, "rb")) + self.key, self.size, self.got = key, os.path.getsize(path), 0 + + def read(self, *args): + data = super().read(*args) + self.got += len(data) + return data + + def readinto(self, buffer): + n = super().readinto(buffer) + self.got += n or 0 + return n + + def close(self): + if not self.closed and self.got >= self.size > 0: + counted.whole[self.key] += 1 + super().close() + + def opener(file, mode="r", *args, **kwargs): + key = counted.key(file) if isinstance(file, (str, os.PathLike)) else None + if key is None: + return real(file, mode, *args, **kwargs) + counted.opens[key] += 1 + if mode in ("rb", "br") and not args and all(v is None for v in kwargs.values()): + return Counting(os.fspath(file), key) + return real(file, mode, *args, **kwargs) + + monkeypatch.setattr(builtins, "open", opener) + return counted + + +def segmented_app(tmp_path): + """Return the app and cell 4 after it segmented the app's run into ``tmp_path/masks``.""" + nb = ran_app(tmp_path) + step = segmentation_step(nb) + segment(step, tmp_path / "masks") + return nb, step + + +def answered(nb, step): + """Return cell 5 answered for Cells, after the axes stop of its first press.""" + registration = register_step(nb, step) + registration.choices["Cells"].value = "instances" + assert not registration.register() # the folder check asks for the axes again + nb.quick_confirm.click() + return registration + + +# item 6: the question -------------------------------------------------------------------------- + + +def test_each_mask_type_is_asked_what_it_is_with_no_answer_chosen(tmp_path, stub): + nb, step = segmented_app(tmp_path) + registration = register_step(nb, step) + choice = registration.choices["Cells"] + assert choice.value is None + assert [label for label, _ in CHOICES] == [ + "Each object has its own number (label image: every cell/nucleus is a separate object)", + "Foreground / background only (binary mask)", + ] + assert list(choice.options) == CHOICES + text = repr(registration.children) + assert WHY_WE_ASK in text.replace("\\'", "'") + assert "Declare Cells as separate objects" not in text + # The declaration is shown folded only. + section = toml_section("Cells").replace('"', """) + with_section = [w.value for w in _all_html(registration) if "[masks.Cells]" in w.value] + assert len(with_section) == 1 and with_section[0].startswith("
") + assert section in with_section[0] + + +def _all_html(widget): + """Yield every HTML widget inside ``widget``.""" + if isinstance(widget, widgets.HTML): + yield widget + for child in getattr(widget, "children", ()): + yield from _all_html(child) + + +def test_nothing_chosen_is_refused_as_before_and_nothing_is_declared(tmp_path, stub): + nb, step = segmented_app(tmp_path) + out = nb.result.output_folder + registration = register_step(nb, step) + assert registration.button.disabled and not registration.register() + assert "choose what Cells is" in registration.blocker.value + assert "[masks" not in (out / DESCRIPTION_FILENAME).read_text(encoding="utf-8") + assert registration.progress.value == "" # nothing ran + + +def test_a_binary_answer_is_refused_saying_why_and_nothing_is_declared(tmp_path, stub): + nb, step = segmented_app(tmp_path) + out = nb.result.output_folder + registration = register_step(nb, step) + registration.choices["Cells"].value = "binary" + assert registration.button.disabled and not registration.register() + text = BINARY_REFUSED.format(mask_type="Cells") + assert text.split(":")[0] in registration.blocker.value + assert "[masks" not in (out / DESCRIPTION_FILENAME).read_text(encoding="utf-8") + registration.choices["Cells"].value = "instances" + assert not registration.button.disabled and registration.blocker.value == "" + + +def test_the_recorded_declaration_is_unchanged(tmp_path, stub): + nb, step = segmented_app(tmp_path) + registration = answered(nb, step) + assert registration.register(), registration.status.value + text = (nb.result.output_folder / DESCRIPTION_FILENAME).read_text(encoding="utf-8") + assert '[masks.Cells]\nsource_type = "Cells"\nrepresentation = "instances"' in text + assert RunInputs.open(nb.result.output_folder).mask_types() == ("Cells",) + + +# item 7: what Register reads, and its wait ---------------------------------------------------- + + +def test_register_reads_each_file_as_many_times_as_before(tmp_path, stub, larger, reads): + # Measured on main before #574 with this opener; pinned so that showing the wait reads + # nothing more. Per image: the run's checks (cell 5), the app's run, its check before it + # publishes and the tissue-mask step's opening after it, each a content SHA-256. The two + # viewers Check and save redraws twice also read the first image, about 4 times its size in + # all, through openings that each read a part of it (not whole reads here). Per mask: + # the run and its check before publishing (SHA-256), the mask step's fingerprints before + # and after reading, and its pixels (the piece counts). + nb, step = segmented_app(tmp_path) + registration = answered(nb, step) + images = sorted(f"exp/{f.relative_path}" for f in step.workflow.inputs.fovs()) + masks = sorted(f"masks/Cells/{f.relative_path}" for f in step.workflow.inputs.fovs()) + assert len(images) == len(masks) == 4 + reads.opens.clear(), reads.whole.clear() + assert registration.register(), registration.status.value + first, *others = images + assert reads.whole == Counter({**dict.fromkeys(images, 4), **dict.fromkeys(masks, 5)}) + assert reads.opens == Counter( + {first: 21, **dict.fromkeys(others, 9), **dict.fromkeys(masks, 7)} + ) + + +def test_showing_cell_5_reads_each_image_whole_once(tmp_path, stub, larger, reads): + nb, step = segmented_app(tmp_path) + reads.opens.clear(), reads.whole.clear() + register_step(nb, step) + images = [f"exp/{f.relative_path}" for f in step.workflow.inputs.fovs()] + assert reads.whole == Counter(dict.fromkeys(images, 1)) == reads.opens + + +def test_register_names_each_step_counts_the_images_and_ticks(tmp_path, stub, monkeypatch): + nb, step = segmented_app(tmp_path) + registration = answered(nb, step) + monkeypatch.setattr(notebook_progress, "MIN_INTERVAL", 0.0) # every step drawn + ticking, original = [], notebook_progress.Wait.ticking + + def spy(self, *args, **kwargs): + ticking.append(self.target) + return original(self, *args, **kwargs) + + monkeypatch.setattr(notebook_progress.Wait, "ticking", spy) + lines, details = [], [] + registration.progress.observe(lambda c: lines.append(c["new"]), names="value") + registration.progress_detail.observe(lambda c: details.append(c["new"]), names="value") + names = [f.relative_path for f in step.workflow.inputs.fovs()] + assert registration.register(), registration.status.value + for label in (step_label(k) for k in ("run", "save", "rerun", "describe")): + assert any(label in line for line in lines), label + assert not any(step_label("folders") in line for line in lines) # made at the first press + hashed = [d for d in details if CHECKS["contents"] in d] + for done, name in enumerate(names): + assert any(f"{done} of 4" in d and name in d for d in hashed), name + assert any("Preparing:" in d for d in details) # the app's run's own wait, copied + assert any("Pairing the masks" in d for d in details) # the app's mask step's + assert ticking[0] is registration.progress # the timer thread of #567 redraws the line + assert "Took " in registration.progress.value and registration.progress_detail.value == "" + assert "The masks are registered" in registration.status.value + assert not registration.button.disabled # back once it ended + + +def test_the_first_press_shows_the_folder_check_of_the_app(tmp_path, stub): + nb, step = segmented_app(tmp_path) + registration = register_step(nb, step) + registration.choices["Cells"].value = "instances" + lines, details = [], [] + registration.progress.observe(lambda c: lines.append(c["new"]), names="value") + registration.progress_detail.observe(lambda c: details.append(c["new"]), names="value") + assert not registration.register() # the axes to confirm again + assert any(step_label("folders") in line for line in lines) + assert details and any(d for d in details) # the app's folder check, copied + assert "Took " in registration.progress.value + + +def test_the_run_checks_refuse_the_same_with_or_without_the_wait(tmp_path, stub): + nb, step = segmented_app(tmp_path) + image = tmp_path / "exp" / "ctrl" / "rep1" / "a.tif" + image.write_bytes(image.read_bytes()[:-1] + b"\x07") + told = [] + quiet = refusal(nb, step) + shown = refusal(nb, step, checking=lambda *args: told.append(args)) + assert quiet == shown and "The images changed since the run" in shown + assert told and told[0][0] == "run" + + +def test_the_wait_says_stopped_after_an_error_and_stops_copying(): + line, detail, source = widgets.HTML(), widgets.HTML(), widgets.HTML() + wait = RegisterWait(line, detail) + with pytest.raises(KeyboardInterrupt), wait.running(): + with wait.step("rerun", source): + source.value = "the app's line" + assert detail.value == "the app's line" + raise KeyboardInterrupt + assert STOPPED_AFTER.split("{")[0] in line.value and detail.value == "" + source.value = "later" + assert detail.value == "" # copied only while its step ran diff --git a/tests/test_notebook_preprocessing_cellpose.py b/tests/test_notebook_preprocessing_cellpose.py index c0a40ada..2bd26dcf 100644 --- a/tests/test_notebook_preprocessing_cellpose.py +++ b/tests/test_notebook_preprocessing_cellpose.py @@ -4,7 +4,7 @@ experiment; cell 4 (:func:`.notebook_preprocessing_cellpose.segmentation_step`) segments that run with the stand-in Cellpose of ``cellpose_stub.py`` (no GPU, no download) and cell 5 (:func:`.notebook_mask_register.register_step`) offers the declarations and registers them -through the app's own steps once the user ticked them. +through the app's own steps once the user answered what each mask is. """ import json @@ -218,19 +218,19 @@ def test_preprocessing_alone_never_imports_cellpose_or_torch(): # cell 5 --------------------------------------------------------------------------------------- -def test_cell_5_offers_the_declaration_and_registers_only_after_the_tick(tmp_path, stub): +def test_cell_5_asks_what_each_mask_is_and_registers_only_once_answered(tmp_path, stub): nb = ran_app(tmp_path) out = nb.result.output_folder step = segmentation_step(nb) segment(step, tmp_path / "masks") registration = register_step(nb, step) - assert list(registration.ticks) == ["Cells"] + assert list(registration.choices) == ["Cells"] section = toml_section("Cells") assert section == '[masks.Cells]\nsource_type = "Cells"\nrepresentation = "instances"' assert "[masks.Cells]" in repr(registration.children) assert registration.button.disabled and not registration.register() # nothing silent assert "[masks" not in (out / DESCRIPTION_FILENAME).read_text(encoding="utf-8") - registration.ticks["Cells"].value = True + registration.choices["Cells"].value = "instances" # The app's folder check with the masks folder asks for the axes again: the user's click. assert not registration.register() assert AXES_AGAIN.split(":")[0] in registration.status.value @@ -256,8 +256,8 @@ def test_cell_5_registers_masks_written_into_the_runs_own_masks_folder(tmp_path, assert step.masks_folder == str((tmp_path / "masks").resolve()) segment(step) # into the prefilled masks folder registration = register_step(nb, step) - assert list(registration.ticks) == ["Cells"], registration.status.value - registration.ticks["Cells"].value = True + assert list(registration.choices) == ["Cells"], registration.status.value + registration.choices["Cells"].value = "instances" assert not registration.register() # the folder check is made again: axes to confirm assert AXES_AGAIN.split(":")[0] in registration.status.value nb.quick_confirm.click() @@ -273,7 +273,7 @@ def stopped_for_the_axes(tmp_path, stub): step = segmentation_step(nb) segment(step, tmp_path / "masks") registration = register_step(nb, step) - registration.ticks["Cells"].value = True + registration.choices["Cells"].value = "instances" assert not registration.register() assert AXES_AGAIN.split(":")[0] in registration.status.value return nb, registration, nb._output_path(tmp_path / "exp") @@ -288,8 +288,8 @@ def test_cell_5_run_again_after_the_axes_stop_continues(tmp_path, stub): nb, registration, out = stopped_for_the_axes(tmp_path, stub) nb.quick_confirm.click() again = register_step(nb, registration.segmentation) # cell 5 run again - assert list(again.ticks) == ["Cells"], again.status.value - again.ticks["Cells"].value = True + assert list(again.choices) == ["Cells"], again.status.value + again.choices["Cells"].value = "instances" assert again.register(), again.status.value assert RunInputs.open(out).mask_types() == ("Cells",) @@ -339,7 +339,7 @@ def segmented(tmp_path, nb, masks, mask_type="Cells"): def refused(registration): - assert registration.ticks == {} + assert registration.choices == {} return registration.status.value.replace("'", "'") @@ -428,4 +428,4 @@ def test_cell_5_run_again_after_it_registered_the_masks_is_not_refused(tmp_path, nb.quick_confirm.click() assert registration.register(), registration.status.value again = register_step(nb, registration.segmentation) - assert list(again.ticks) == ["Cells"], again.status.value + assert list(again.choices) == ["Cells"], again.status.value From acfc4d5da1d1020aab0aa32dbec45946d997372c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 15:23:46 +0000 Subject: [PATCH 2/2] Republished-run test: patch open_checked, as #575 does (identical hunk) open_run now opens through run_inputs.open_checked (the hunks shared with #575), so the test that publishes the run while it is opened patches that function instead of RunInputs.open. Same change, byte for byte, as #575's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- tests/test_notebook_cellpose_republished.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/test_notebook_cellpose_republished.py b/tests/test_notebook_cellpose_republished.py index 00852c14..ed2f1b95 100644 --- a/tests/test_notebook_cellpose_republished.py +++ b/tests/test_notebook_cellpose_republished.py @@ -20,7 +20,7 @@ from morphobricks_preprocessing import segmentation_cellpose as cp from morphobricks_preprocessing import segmentation_cellpose_run as run_module from morphobricks_preprocessing.manifest import MANIFEST_FILENAME -from morphobricks_preprocessing.run_inputs import RunInputs +from morphobricks_preprocessing.run_inputs import RunInputs, open_checked from morphobricks_preprocessing.segmentation_record import read_record, record_path from test_notebook_cellpose import BATCH, CHANNELS, MODEL, OPEN, PREVIEW, run_cell, source @@ -143,14 +143,15 @@ def progress(done, total, image): def test_a_run_published_while_it_is_opened_is_refused(monkeypatch, tmp_path): install(monkeypatch, tmp_path) run, ns = two_channel_run(tmp_path / "run"), {} - real = RunInputs.open + real = open_checked def open_then_publish(*args, **kwargs): inputs = real(*args, **kwargs) republish(run.out, check=False) # after the snapshot was read return inputs - monkeypatch.setattr(RunInputs, "open", open_then_publish) + # The notebook opens the run through open_checked (RunInputs.open with its wait, #574). + monkeypatch.setattr(run_module, "open_checked", open_then_publish) exec(compile(source(OPEN), "", "exec"), ns) opener = ns["workflow"].forms["open"] opener.fields["run_folder"].value = str(run.out)