Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,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`.
- **`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`.
Expand Down
5 changes: 4 additions & 1 deletion src/morphobricks_preprocessing/masks/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ def _header_issues(
(OME-Zarr ``labels`` groups). With ``bind``, each mask is fingerprinted before and
after its header is read (:attr:`.model.MaskFile.bound`, issue #160); a mask whose two
fingerprints differ is ``mask_changed_during_check``. ``progress(done, total, path)`` is
called before each mask's header is read.
called before each mask's header is read, and once more as
``progress(total, total, "")`` when the last one is read.
"""
found: list[tuple[str, str, str]] = [("unreadable_mask", path, "") for path in unreadable]
for index, mask in enumerate(files):
Expand All @@ -66,6 +67,8 @@ def _header_issues(
found.extend(problems)
if checked is not None:
files[index] = checked
if progress is not None and files:
progress(len(files), len(files), "") # the last mask is done: "N of N"
by_image: dict[str, list[MaskFile]] = {}
for mask in files:
if mask.axes:
Expand Down
3 changes: 2 additions & 1 deletion src/morphobricks_preprocessing/masks/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ def find_masks(
mask step refuses a mask that is no longer the one its header described; a mask
that changed while its header was read is the error ``mask_changed_during_check``.
progress
Called as ``progress(done, total, mask_path)`` before each mask's header is read. It
Called as ``progress(done, total, mask_path)`` before each mask's header is read, and
as ``progress(total, total, "")`` after the last. It
changes nothing about the result.

Returns
Expand Down
4 changes: 2 additions & 2 deletions src/morphobricks_preprocessing/notebook_progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@
"acquisitions": "Preparing: comparing the images and checking the description",
"contents": "Preparing: reading each image whole for its content SHA-256",
}
COUNTED_PHASES = ("headers", "masks", "contents")
"""The phases of the run's checks shown as done of total, each with its file."""
"""What the run's wait says in each phase of its own checks before the first read
(:data:`.run.phases.PHASES`, then :data:`.run.phases.CONTENTS`)."""
COUNTED_PHASES = ("headers", "masks", "contents")
"""The phases of the run's checks shown as done of total, each with its file."""
BUSY_NOTE = (
"<div class='mb-help'>The run is going: the notebook is busy until it finishes or stops. "
"A cell run meanwhile (this one too) waits for it; to stop the run, interrupt the "
Expand Down
6 changes: 4 additions & 2 deletions src/morphobricks_preprocessing/run/preflight.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,8 @@ def preflight(
:data:`.phases.PHASES` (``folders``, ``headers``, ``masks``, ``acquisitions``): a phase
is announced as ``(phase, 0, total, "")`` and ends with ``(phase, total, total, "")``;
the headers phase also reports ``(phase, done, total, path)`` before each image, the
masks phase ``("masks", done, total, mask_path)`` before each mask's header, and the
masks phase ``("masks", done, total, mask_path)`` before each mask's header and
``("masks", total, total, "")`` after the last, and the
folders phase ``("folders", 0, 1, folder)`` before each folder is listed.
:func:`.phases.progress_text` words it. It changes nothing about the result.
recorded
Expand Down Expand Up @@ -352,7 +353,8 @@ def remasked(
output_folder
The output folder (it may not be inside the masks folder).
progress
Called as ``progress(done, total, mask_path)`` before each mask's header is read.
Called as ``progress(done, total, mask_path)`` before each mask's header is read, and
as ``progress(total, total, "")`` after the last.

Returns
-------
Expand Down
4 changes: 3 additions & 1 deletion tests/test_notebook_progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,9 @@ def test_pairing_the_masks_again_reports_each_mask(exp): # noqa: F811
calls = []
again = remasked(pre, masks, None, out, lambda *call: calls.append(call))
assert again.masks == pre.masks
assert [call[0] for call in calls] == list(range(len(pre.masks.files)))
count = len(pre.masks.files)
assert [call[0] for call in calls] == [*range(count), count] # each, then the last one done
assert calls[-1] == (count, count, "")


def test_check_progress_words_each_phase():
Expand Down
43 changes: 43 additions & 0 deletions tests/test_run_checking_progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,3 +309,46 @@ def test_the_run_wait_counts_real_totals_and_ends_at_n_of_n():
assert lines[-1].startswith(
"Preparing: reading each image whole for its content SHA-256 · 3 of 3"
)


def test_the_masks_counter_reaches_n_of_n(tmp_path, experiment):
"""The masks phase reads "n of N" up to N (it stopped at N-1: reported before each mask)."""
pytest.importorskip("ipywidgets")
from types import SimpleNamespace

import ipywidgets as widgets

from morphobricks_preprocessing.notebook_progress import Wait
from morphobricks_preprocessing.notebook_run import _RunStep

masks = tmp_path / "masks"
for rel in IMAGES[:3]:
write_tiff(masks / rel.replace(".tif", "_mask.tif"))
calls = []
result = run_described(
experiment,
prefill_mapping("YX"),
output_folder=tmp_path / "out",
masks_folder=masks,
mode=RunMode(checking=lambda *call: calls.append(call)),
)
assert result.written
real = [c for c in calls if c[0] == "masks" and c[3]]
assert real, calls # the masks were found and read
total = real[0][2]
assert total == 3 and calls.count(("masks", total, total, "")) == 1
target = widgets.HTML()
seen = []
target.observe(
lambda change: seen.append(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", change["new"]))),
names="value",
)
now = [0.0]
step = SimpleNamespace(_run_wait=Wait(target, bar=False, clock=lambda: now[0]))
step._run_wait.start("Preparing")
for call in calls:
if call[0] in ("folders", "headers", "masks"):
now[0] += 1
_RunStep._checking(step, *call)
lines = [line.strip() for line in seen if "mask headers" in line]
assert lines[-1].startswith("Preparing: reading the mask headers again · 3 of 3"), lines
Loading