diff --git a/CHANGELOG.md b/CHANGELOG.md
index dba95119..072997e2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ v0.5.1: no run before v0.5.1 is read.)
## Unreleased
+- **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`.
- **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`.
diff --git a/src/morphobricks_preprocessing/mask_names.py b/src/morphobricks_preprocessing/mask_names.py
index 563790f5..bddb392b 100644
--- a/src/morphobricks_preprocessing/mask_names.py
+++ b/src/morphobricks_preprocessing/mask_names.py
@@ -204,17 +204,20 @@ def _mask_owner(
Any suffix when ``suffixes`` is None. ``stem`` and the keys of ``stems`` are lower case.
The longest such position wins, an image of ``folder`` first; None when there is none.
+ Only the prefixes of ``stem`` that end before one of its ``_`` can be such a position, so
+ those are looked up, longest first (not every key of ``stems``: that was quadratic).
"""
- keys = [
- key
- for key in stems
- if key != stem
- and stem.startswith(key + "_")
- and (suffixes is None or stem[len(key) :] in suffixes)
- ]
- if not keys:
+ key = None
+ cut = stem.rfind("_")
+ while cut >= 0:
+ candidate = stem[:cut]
+ if candidate in stems and (suffixes is None or stem[cut:] in suffixes):
+ key = candidate
+ break
+ cut = stem.rfind("_", 0, cut)
+ if key is None:
return None
- owners = stems[max(keys, key=len)]
+ owners = stems[key]
near = [owner for owner in owners if str(PurePosixPath(owner).parent) == folder]
return (near or owners)[0]
diff --git a/src/morphobricks_preprocessing/notebook_progress.py b/src/morphobricks_preprocessing/notebook_progress.py
index f711de57..3c872cc0 100644
--- a/src/morphobricks_preprocessing/notebook_progress.py
+++ b/src/morphobricks_preprocessing/notebook_progress.py
@@ -12,8 +12,10 @@
from __future__ import annotations
import html
+import threading
import time
-from collections.abc import Callable
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
import ipywidgets as widgets
@@ -21,6 +23,26 @@
"""No estimate of the time left before this much time was spent on at least one item."""
MIN_INTERVAL = 0.1
"""Seconds between two redraws of a wait (the first and the last are always drawn)."""
+TICK = 1.0
+"""Seconds between two redraws of a ticking wait (:meth:`Wait.ticking`) that reports nothing."""
+
+PREPARING = {
+ "folders": "Preparing: listing the folders again",
+ "headers": "Preparing: reading the image headers again",
+ "masks": "Preparing: reading the mask headers again",
+ "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`)."""
+BUSY_NOTE = (
+ "
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 "
+ "kernel (Colab: Runtime > Interrupt execution).
"
+)
+"""Said under the wait while the run goes (owner test of v0.9.0: a cell run again just waited)."""
def clock_text(seconds: float) -> str:
@@ -129,6 +151,7 @@ def __init__(
self.drawn = 0
self._started = self._phase_started = self._last = 0.0
self._state: tuple[int, int, str] = (0, 0, "")
+ self._drawing = threading.Lock()
@property
def elapsed(self) -> float:
@@ -137,19 +160,14 @@ def elapsed(self) -> float:
def start(self, label: str, total: int = 0) -> None:
"""Start the wait: the clock is set and the line drawn with nothing done."""
- self.label = label
- self._started = self._phase_started = self.clock()
- self.drawn = 0
- self._draw(0, total, "")
+ self._draw(0, total, "", label=label, restart=True)
def phase(self, label: str, total: int = 0, done: int = 0) -> None:
"""Name the next part of the same wait; the elapsed time goes on.
``done`` of ``total`` says which part this is when the parts themselves are counted.
"""
- self.label = label
- self._phase_started = self.clock()
- self._draw(done, total, "")
+ self._draw(done, total, "", label=label)
def step(self, done: int, total: int = 0, item: str = "") -> None:
"""Report progress; redrawn at most every :data:`MIN_INTERVAL` seconds, and at the end."""
@@ -158,11 +176,58 @@ def step(self, done: int, total: int = 0, item: str = "") -> None:
if last or self.clock() - self._last >= MIN_INTERVAL:
self._draw(done, total, item)
- def _draw(self, done: int, total: int, item: str) -> None:
- self._state = (done, total, item)
- self._last = self.clock()
- self.drawn += 1
- self.target.value = self.html(done, total, item)
+ @property
+ def total(self) -> int:
+ """The total last reported (0 for work that is not counted)."""
+ return self._state[1]
+
+ def _draw(
+ self, done: int, total: int, item: str, *, label: str | None = None, restart: bool = False
+ ) -> None:
+ """Draw the line; with ``label``, a new part starts (``restart``: a new wait).
+
+ The label, the clocks and the line change together under the lock the ticking
+ thread draws with, so it never draws a new label with an old part's numbers.
+ """
+ with self._drawing: # the ticking thread draws too
+ if label is not None:
+ now = self.clock()
+ self.label, self._phase_started = label, now
+ if restart:
+ self._started, self.drawn = now, 0
+ self._state = (done, total, item)
+ self._last = self.clock()
+ self.drawn += 1
+ self.target.value = self.html(done, total, item)
+
+ @contextmanager
+ def ticking(self, interval: float = TICK) -> Iterator[None]:
+ """Redraw the line every ``interval`` seconds in a thread while the block runs.
+
+ For work that reports no progress for a long time (the run's checks before its first
+ image, on a large experiment): the elapsed time goes on in the line instead of
+ staying at ``0:00``. The thread only redraws what was last reported; it is stopped,
+ and has drawn its last, before the block returns, so whatever replaces the line
+ afterwards stays.
+ """
+ stop = threading.Event()
+
+ def tick() -> None:
+ while not stop.wait(interval):
+ with self._drawing:
+ if stop.is_set():
+ return
+ done, total, item = self._state
+ self.drawn += 1
+ self.target.value = self.html(done, total, item)
+
+ thread = threading.Thread(target=tick, name="morphobricks-wait-tick", daemon=True)
+ thread.start()
+ try:
+ yield
+ finally:
+ stop.set()
+ thread.join()
def html(self, done: int, total: int, item: str) -> str:
"""Return the line as it would be drawn now.
@@ -186,4 +251,15 @@ def took(self) -> str:
return clock_text(self.elapsed)
-__all__ = ["MEASURABLE_SECONDS", "MIN_INTERVAL", "Wait", "clock_text", "progress_html", "time_left"]
+__all__ = [
+ "BUSY_NOTE",
+ "COUNTED_PHASES",
+ "MEASURABLE_SECONDS",
+ "MIN_INTERVAL",
+ "PREPARING",
+ "TICK",
+ "Wait",
+ "clock_text",
+ "progress_html",
+ "time_left",
+]
diff --git a/src/morphobricks_preprocessing/notebook_run.py b/src/morphobricks_preprocessing/notebook_run.py
index 57817365..1d86534c 100644
--- a/src/morphobricks_preprocessing/notebook_run.py
+++ b/src/morphobricks_preprocessing/notebook_run.py
@@ -33,7 +33,7 @@
serial_note,
)
from .notebook_plots import IntensityPanel
-from .notebook_progress import Wait
+from .notebook_progress import BUSY_NOTE, COUNTED_PHASES, PREPARING, Wait
from .notebook_render import _bins_help, _label, blocked_line, change_lines, issues_html
from .planes import DEFAULT_MEMORY_LIMIT
from .report import issue_counts, rebuild_line
@@ -244,7 +244,13 @@ def _run_mode(self, verify_content: bool | None) -> RunMode:
"""Return the run's mode with the workers chosen; the memory cap only with Auto."""
workers = self.workers.value
cap = round(self.max_ram_gib.value * 2**30) if workers == AUTO else 0
- return RunMode(self.mode.value, verify_content, workers=workers, max_ram=cap or None)
+ return RunMode(
+ self.mode.value,
+ verify_content,
+ workers=workers,
+ max_ram=cap or None,
+ checking=self._checking,
+ )
def _build_histogram_range(self) -> list[widgets.Widget]:
"""Build the histogram range choice and its robust quantiles; return the widgets."""
@@ -396,12 +402,16 @@ def run(self) -> RunResult | None:
return None
self._start_run()
try:
- with self.log.attached():
+ # The run checks every header again before its first image, with no image read to
+ # report: the line says which header, and its elapsed time goes on (owner, v0.9.0).
+ with self.log.attached(), self._run_wait.ticking():
self.result = self._call_run(histogram_settings)
except Exception as exc: # unexpected failures still get a readable message
self._run_failed(exc)
return None
finally:
+ if self.run_next.value == BUSY_NOTE:
+ self.run_next.value = ""
self._idle(self.run_button, " Compute histograms", "play")
self._finish_run(self.result)
return self.result
@@ -409,7 +419,7 @@ def run(self) -> RunResult | None:
def _start_run(self) -> None:
"""Clear the results of an earlier run and show that this one is starting."""
self._busy(self.run_button, "Computing…")
- self.run_next.value = ""
+ self.run_next.value = BUSY_NOTE
self.run_checks.clear()
self.run_lock.hide()
self.run_report.clear()
@@ -440,6 +450,23 @@ def _call_run(self, histogram_settings: HistogramSettings) -> RunResult:
histogram_settings=histogram_settings,
)
+ def _checking(self, phase: str, done: int, total: int, path: str) -> None:
+ """Show the run's own checks: each phase, and each header or image of how many.
+
+ A phase's start and end calls without a path are placeholders (``("masks", 0, 1, "")``
+ with no masks): only the headers' start, or a call with a path, gives the real total;
+ an end is drawn as "N of N" only when the phase counted that total.
+ """
+ wait = self._run_wait
+ label = PREPARING[phase]
+ if wait.label != label:
+ counted = phase == "headers" or bool(path) # a call with a path has the real total
+ wait.phase(label, total if counted and phase in COUNTED_PHASES else 0)
+ if phase not in COUNTED_PHASES:
+ return
+ if path or (total > 0 and done >= total and wait.total == total):
+ wait.step(done, total, path)
+
def _run_failed(self, exc: Exception) -> None:
"""Show an unexpected failure in plain words, with the traceback in the details."""
self.log.lines.append(traceback.format_exc())
diff --git a/src/morphobricks_preprocessing/run/modes.py b/src/morphobricks_preprocessing/run/modes.py
index 51664f3c..d71ffb32 100644
--- a/src/morphobricks_preprocessing/run/modes.py
+++ b/src/morphobricks_preprocessing/run/modes.py
@@ -23,7 +23,8 @@
from __future__ import annotations
-from dataclasses import dataclass
+from collections.abc import Callable
+from dataclasses import dataclass, field
from typing import Literal
from ..lab_links import LabLinks
@@ -89,6 +90,13 @@ class RunMode:
for byte the same with any value; it is not recorded.
max_ram
With ``workers="auto"``, the bytes of memory the run may use; None: no RAM cap.
+ checking
+ Called while the run checks the folder and every image header again, before any
+ image is read, as :func:`.preflight.preflight`'s ``progress``:
+ ``(phase, done, total, path)``, a phase of :data:`.phases.PHASES`, once per header,
+ then in a ``verify_content`` run :data:`.phases.CONTENTS`, once per image hashed.
+ On a large experiment this check takes minutes (owner test of v0.9.0). Operational
+ only, like ``workers``: not recorded, not compared, and the outputs are the same.
"""
name: str = RESTART
@@ -96,6 +104,7 @@ class RunMode:
lab_links: LabLinks | None = None
workers: int | Literal["auto"] = 1
max_ram: int | None = None
+ checking: Callable[[str, int, int, str], None] | None = field(default=None, compare=False)
def run_mode(mode: object) -> RunMode:
@@ -127,7 +136,16 @@ def run_mode(mode: object) -> RunMode:
if links is not None and not isinstance(links, LabLinks):
raise ValueError(f"lab_links must be LabLinks or None; found {type(links).__name__}")
check_workers(mode.workers, mode.max_ram)
- return RunMode(check_mode(mode.name), mode.verify_content, links, mode.workers, mode.max_ram)
+ if mode.checking is not None and not callable(mode.checking):
+ raise ValueError(f"checking must be callable or None; found {mode.checking!r}")
+ return RunMode(
+ check_mode(mode.name),
+ mode.verify_content,
+ links,
+ mode.workers,
+ mode.max_ram,
+ mode.checking,
+ )
def check_workers(workers: object, max_ram: object) -> None:
diff --git a/src/morphobricks_preprocessing/run/phases.py b/src/morphobricks_preprocessing/run/phases.py
index 4a19158f..517f24cf 100644
--- a/src/morphobricks_preprocessing/run/phases.py
+++ b/src/morphobricks_preprocessing/run/phases.py
@@ -11,6 +11,12 @@
"""The phases of the check, in order: the folder walk, one header per image, the masks found
and paired, and the acquisitions (calibration, dataset consistency, axis suggestion)."""
+CONTENTS = "contents"
+"""The run's phase after the check, in a ``verify_content`` run: each image's content SHA-256,
+one whole read of every image before the first pixel is read (reported as
+``("contents", done, total, path)`` to :attr:`.modes.RunMode.checking`; not a phase of the
+folder check, so not in :data:`PHASES`)."""
+
COUNTED = "headers"
"""The phase that counts its work (one header per image); the others are one step each."""
diff --git a/src/morphobricks_preprocessing/run/pipeline.py b/src/morphobricks_preprocessing/run/pipeline.py
index b92630fa..8522b68d 100644
--- a/src/morphobricks_preprocessing/run/pipeline.py
+++ b/src/morphobricks_preprocessing/run/pipeline.py
@@ -72,7 +72,15 @@
from .rows import _pixel_issues, _range_issues, _row_order
from .staging import clear_staging
from .state import RunOptions, RunState
-from .steps import Rows, compute_rows, counts, header_checks, outcome_of, unreadable_issue
+from .steps import (
+ Reporting,
+ Rows,
+ compute_rows,
+ counts,
+ header_checks,
+ outcome_of,
+ unreadable_issue,
+)
from .workers import Workers
logger = logging.getLogger(__name__)
@@ -141,6 +149,8 @@ def run_experiment( # noqa: PLR0913
turning it on or off recomputes every row). Its ``lab_links``: manifest only (PP-2).
Its ``workers`` and ``max_ram``: how many images are read at once, each whole in a
worker thread (issue #107, :mod:`.workers`); the outputs are the same with any value.
+ Its ``checking``: the progress of the run's own folder and header check, before any
+ image is read (:attr:`.modes.RunMode.checking`).
With more than one worker, ``progress`` is called in this thread as each image is done.
progress
Called as ``progress(done, total, relative_path)`` before each file is
@@ -208,7 +218,9 @@ def run_experiment( # noqa: PLR0913
try:
with output_lock(output):
reading = Workers(chosen.workers, chosen.max_ram)
- options = RunOptions(mode, memory_limit, progress, chosen.lab_links, reading)
+ options = RunOptions(
+ mode, memory_limit, progress, chosen.lab_links, reading, chosen.checking
+ )
return _locked_run(given, output, options)
except OutputLockedError as exc:
return RunResult(output, False, (lock_issue(exc),), mode=mode)
@@ -228,6 +240,7 @@ def _locked_run(given: GivenInputs, output: Path, options: RunOptions) -> RunRes
masks_folder=inputs.masks_folder,
mask_axes=inputs.mask_axes or None,
bind_headers=True,
+ progress=options.checking, # minutes on a large experiment: it is reported (v0.9.0)
)
loaded = load_description(output)
links = options.lab_links # provenance only (experiment-v1 9.3): checked, never a key
@@ -263,8 +276,9 @@ def _locked_run(given: GivenInputs, output: Path, options: RunOptions) -> RunRes
histogram=inputs.histogram_settings,
verify_content=inputs.verify_content,
)
+ reporting = Reporting(options.progress, options.checking)
rows = compute_rows(
- pre, checked, settings, output, previous, options.mode, options.progress, options.workers
+ pre, checked, settings, output, previous, options.mode, reporting, options.workers
)
checked.issues.extend(_read_issues(rows, settings))
if rows.refused or rows.changed or rows.failed:
diff --git a/src/morphobricks_preprocessing/run/resume.py b/src/morphobricks_preprocessing/run/resume.py
index d1ab2222..52ee6191 100644
--- a/src/morphobricks_preprocessing/run/resume.py
+++ b/src/morphobricks_preprocessing/run/resume.py
@@ -177,7 +177,9 @@ def new_rows(
)
discard_staged(job.output, rel)
workers = workers or Workers()
- keys = {rel: _staging_key(job, rel) for rel in to_read}
+ # The pixel type once: MetadataReport.dtype looks at every header (O(n) per call).
+ dtype = job.pre.metadata.dtype.name
+ keys = {rel: _staging_key(job, rel, dtype) for rel in to_read}
if workers.count == 1:
for done, rel in enumerate(to_read):
if progress is not None:
@@ -191,10 +193,10 @@ def new_rows(
return found
-def _staging_key(job: FileJob, rel: str) -> dict:
- """Return the staging key of one file's rows in this run."""
+def _staging_key(job: FileJob, rel: str, dtype: str) -> dict:
+ """Return the staging key of one file's rows in this run (``dtype``: the pixel type's name)."""
root = job.pre.discovery.root.as_posix()
- return staging_key(RowKey.of(job.entries[rel], job.settings, root), job.pre.metadata.dtype.name)
+ return staging_key(RowKey.of(job.entries[rel], job.settings, root), dtype)
def _resumed(job: FileJob, rel: str, key: dict, earlier: StagedFile | None, found: NewRows) -> bool:
diff --git a/src/morphobricks_preprocessing/run/state.py b/src/morphobricks_preprocessing/run/state.py
index ce6fdbab..3081eb80 100644
--- a/src/morphobricks_preprocessing/run/state.py
+++ b/src/morphobricks_preprocessing/run/state.py
@@ -28,6 +28,8 @@ class RunOptions:
progress: Callable[[int, int, str], None] | None
lab_links: LabLinks | None = None
workers: Workers = field(default_factory=Workers)
+ checking: Callable[[str, int, int, str], None] | None = None
+ """The progress of the run's own folder and header check (:func:`.preflight.preflight`)."""
@dataclass(frozen=True)
diff --git a/src/morphobricks_preprocessing/run/steps.py b/src/morphobricks_preprocessing/run/steps.py
index 04a53aaf..86a16bd1 100644
--- a/src/morphobricks_preprocessing/run/steps.py
+++ b/src/morphobricks_preprocessing/run/steps.py
@@ -29,6 +29,7 @@
from ..validation import ValidationIssue, error, has_errors, plural
from .entries import Comparison, compare_with_previous, file_entries
from .modes import FULL
+from .phases import CONTENTS
from .preflight import Preflight
from .recorded import ResolvedInputs
from .resume import FileJob, changed_during_check, new_rows
@@ -169,6 +170,28 @@ def _no_roles_issue() -> ValidationIssue:
)
+@dataclass(frozen=True)
+class Reporting:
+ """Who is told what :func:`compute_rows` does: before the first read, and each read.
+
+ Attributes
+ ----------
+ reading
+ As :func:`.pipeline.run_experiment`'s ``progress``: each image read.
+ checking
+ As :attr:`.modes.RunMode.checking`: here the phase :data:`.phases.CONTENTS`, each
+ image's content SHA-256 in a ``verify_content`` run.
+ """
+
+ reading: Callable[[int, int, str], None] | None = None
+ checking: Callable[[str, int, int, str], None] | None = None
+
+ def contents(self, done: int, total: int, path: str) -> None:
+ """Report the content SHA-256 of image ``done`` of ``total`` (phase ``contents``)."""
+ if self.checking is not None:
+ self.checking(CONTENTS, done, total, path)
+
+
@dataclass(frozen=True)
class Rows:
"""The rows of a run, and which files were read and why.
@@ -227,7 +250,7 @@ def compute_rows(
output: Path,
previous: tuple[RunManifest | None, str | None],
mode: str,
- progress: Callable[[int, int, str], None] | None,
+ reporting: Reporting,
workers: Workers | None = None,
) -> Rows:
"""Reuse the earlier rows that can be reused, resume staged rows, and read the rest.
@@ -246,8 +269,8 @@ def compute_rows(
:func:`.reuse.read_previous`'s answer.
mode
``"restart"`` or ``"full"``.
- progress
- As :func:`.pipeline.run_experiment`.
+ reporting
+ Who is told of each content SHA-256 and each read (:class:`Reporting`).
workers
How many files may be read at once (:class:`.workers.Workers`); None: one.
@@ -266,7 +289,12 @@ def compute_rows(
earlier_qc, reason = _load_previous_qc(output, previous[0], earlier)
entries = file_entries(pre, review, root, in_blocks, checked.channels)
# Strict reuse: each image's content SHA-256 joins its row key; an unreadable one fails.
- entries, unhashed = with_content(entries, root) if settings.verify_content else (entries, [])
+ # Each image read whole (minutes on Google Drive): reported, before the first read.
+ entries, unhashed = (
+ with_content(entries, root, reporting.contents)
+ if settings.verify_content
+ else (entries, [])
+ )
found = compare_with_previous(entries, previous[0], earlier, reason is not None, settings, root)
records: list[PlaneRecord] = []
narrow: list[NarrowRange] = []
@@ -284,7 +312,7 @@ def compute_rows(
if rel not in changed and rel not in unhashed
]
kept = set(found.unchanged) if not reason else set()
- new = new_rows(job, to_read, kept, progress, workers)
+ new = new_rows(job, to_read, kept, reporting.reading, workers)
return Rows(
[*records, *new.records],
[*narrow, *new.narrow],
diff --git a/src/morphobricks_preprocessing/source_content.py b/src/morphobricks_preprocessing/source_content.py
index a8c76e7e..31ba8d41 100644
--- a/src/morphobricks_preprocessing/source_content.py
+++ b/src/morphobricks_preprocessing/source_content.py
@@ -20,7 +20,7 @@
import hashlib
import logging
import os
-from collections.abc import Iterable, Mapping
+from collections.abc import Callable, Iterable, Mapping
from dataclasses import replace
from pathlib import Path
@@ -68,7 +68,9 @@ def current_content(path: Path) -> str | None:
def with_content(
- entries: Mapping[str, FileEntry], root: Path
+ entries: Mapping[str, FileEntry],
+ root: Path,
+ progress: Callable[[int, int, str], None] | None = None,
) -> tuple[dict[str, FileEntry], list[str]]:
"""Record each image's content SHA-256 in its entry.
@@ -78,6 +80,10 @@ def with_content(
The run's entries, ``{relative path: FileEntry}``.
root
The experiment folder.
+ progress
+ Called as ``progress(done, total, relative_path)`` before each image is hashed, and
+ as ``progress(total, total, "")`` at the end: each image is read whole, which takes
+ seconds for a large image on slow storage. It changes nothing about the result.
Returns
-------
@@ -86,11 +92,16 @@ def with_content(
cannot be read keeps None, and is never reused.
"""
found, unreadable = {}, []
- for rel, entry in entries.items():
+ total = len(entries)
+ for done, (rel, entry) in enumerate(entries.items()):
+ if progress is not None:
+ progress(done, total, rel)
sha = current_content(root / rel)
if sha is None:
unreadable.append(rel)
found[rel] = replace(entry, content_sha256=sha)
+ if progress is not None:
+ progress(total, total, "")
return found, unreadable
diff --git a/tests/test_brick_api_surface.py b/tests/test_brick_api_surface.py
index 2f6be43a..fdfab4a9 100644
--- a/tests/test_brick_api_surface.py
+++ b/tests/test_brick_api_surface.py
@@ -359,6 +359,7 @@ def test_the_run_workers_are_a_run_mode_option():
("lab_links", "LabLinks | None", None),
("workers", "int | Literal['auto']", 1),
("max_ram", "int | None", None),
+ ("checking", "Callable[[str, int, int, str], None] | None", None),
]
assert package.RunMode is RunMode
parameters = inspect.signature(run_experiment).parameters
diff --git a/tests/test_run_checking_progress.py b/tests/test_run_checking_progress.py
new file mode 100644
index 00000000..0208691a
--- /dev/null
+++ b/tests/test_run_checking_progress.py
@@ -0,0 +1,311 @@
+"""The run's own folder and header check shows its progress, and costs O(n) (v0.9.0 owner test).
+
+Before its first image, a run checks the folder and every image header again
+(:func:`.run.preflight.preflight` with ``bind_headers``). On a large experiment in Colab the
+notebook showed "Preparing: checking the folders and the image headers again · 0:00 elapsed"
+for 10-15 minutes: nothing reported that check's progress, and the elapsed time was only
+redrawn on a progress report. Two steps of it were also quadratic in the number of images:
+the pixel type of :class:`.metadata.MetadataReport` (a pass over every header) taken once per
+image for its staging key, and the mask-name screen comparing each image with every other.
+"""
+
+import random
+import re
+import threading
+import time
+from pathlib import PurePosixPath
+
+import pytest
+
+from described_tree import run_described
+from morphobricks_preprocessing import prefill_mapping
+from morphobricks_preprocessing.mask_names import _mask_owner, _stems, mask_name_issues
+from morphobricks_preprocessing.metadata import MetadataReport
+from morphobricks_preprocessing.run import RunMode
+from morphobricks_preprocessing.run.phases import CONTENTS, PHASES
+from test_notebook_check_save import answer_all, exp # noqa: F401
+from tiff_tree import write_tiff
+
+IMAGES = (
+ "ctrl/rep1/a.tif",
+ "ctrl/rep1/b.tif",
+ "ctrl/rep2/a.tif",
+ "drug/rep1/a.tif",
+ "drug/rep1/b.tif",
+ "drug/rep2/c.tif",
+)
+
+
+@pytest.fixture
+def experiment(tmp_path):
+ root = tmp_path / "exp"
+ for rel in IMAGES:
+ write_tiff(root / rel)
+ return root
+
+
+# --- the run reports its own check --------------------------------------------------------------
+
+
+def test_the_run_reports_each_header_it_checks_again(tmp_path, experiment):
+ calls = []
+ result = run_described(
+ experiment,
+ prefill_mapping("YX"),
+ output_folder=tmp_path / "out",
+ mode=RunMode(checking=lambda *call: calls.append(call)),
+ )
+ assert result.written
+ order = [phase for phase, *_ in calls]
+ assert [p for p in PHASES if p in order] == list(PHASES)
+ reading = [(done, total, path) for phase, done, total, path in calls if phase == "headers"]
+ assert [entry for entry in reading if entry[2]] == [
+ (index, len(IMAGES), rel) for index, rel in enumerate(sorted(IMAGES))
+ ]
+ assert reading[-1] == (len(IMAGES), len(IMAGES), "")
+
+
+def test_the_check_is_reported_before_any_image_is_read(tmp_path, experiment):
+ events = []
+ run_described(
+ experiment,
+ prefill_mapping("YX"),
+ output_folder=tmp_path / "out",
+ mode=RunMode(checking=lambda phase, *_: events.append(phase)),
+ progress=lambda *_: events.append("read"),
+ )
+ first_read = events.index("read")
+ # A fresh output folder verifies content by default: each image is hashed, and said so.
+ assert set(events[:first_read]) == {*PHASES, CONTENTS}
+ assert set(events[first_read:]) == {"read"}
+
+
+@pytest.mark.parametrize("verify", [True, False])
+def test_each_content_sha256_is_reported_before_the_first_read(tmp_path, experiment, verify):
+ calls = []
+ run_described(
+ experiment,
+ prefill_mapping("YX"),
+ output_folder=tmp_path / "out",
+ mode=RunMode(verify_content=verify, checking=lambda *call: calls.append(call)),
+ )
+ hashed = [(done, total, path) for phase, done, total, path in calls if phase == CONTENTS]
+ if not verify: # nothing is read whole before the pixels
+ assert hashed == []
+ return
+ assert [entry for entry in hashed if entry[2]] == [
+ (index, len(IMAGES), rel) for index, rel in enumerate(sorted(IMAGES))
+ ]
+ assert hashed[-1] == (len(IMAGES), len(IMAGES), "")
+
+
+def test_the_outputs_are_the_same_with_and_without_the_check_reported(tmp_path, experiment):
+ run_described(experiment, prefill_mapping("YX"), output_folder=tmp_path / "plain")
+ run_described(
+ experiment,
+ prefill_mapping("YX"),
+ output_folder=tmp_path / "told",
+ mode=RunMode(checking=lambda *_: None),
+ )
+ for name in ("plane_histograms.csv", "experiment_design.csv"):
+ assert (tmp_path / "plain" / name).read_bytes() == (tmp_path / "told" / name).read_bytes()
+
+
+# --- no step of the check is quadratic --------------------------------------------------------
+
+
+def test_the_pixel_type_is_taken_once_per_run_not_once_per_image(tmp_path, experiment, monkeypatch):
+ calls = []
+ real = MetadataReport.dtype.fget
+
+ def counted(self):
+ calls.append(1)
+ return real(self)
+
+ monkeypatch.setattr(MetadataReport, "dtype", property(counted))
+ assert run_described(experiment, prefill_mapping("YX"), output_folder=tmp_path / "out").written
+ # A handful of steps take it once each; one per image (the staging keys) made it O(n²).
+ assert len(calls) < len(IMAGES)
+
+
+class _NoScan(dict):
+ """A stems mapping that refuses to be scanned: only looked up."""
+
+ def __iter__(self):
+ raise AssertionError("every position was compared with this image (quadratic)")
+
+ def keys(self):
+ raise AssertionError("every position was compared with this image (quadratic)")
+
+
+def test_a_mask_owner_is_looked_up_not_scanned_for():
+ stems = _NoScan({"f1": ["a/f1.tif"], "f1_x": ["a/f1_x.tif"], "g": ["b/g.tif"]})
+ assert _mask_owner("f1_x_mask", stems, "a", {"_mask"}) == "a/f1_x.tif"
+ assert _mask_owner("f1_x_mask", stems, "a", None) == "a/f1_x.tif"
+ assert _mask_owner("f1_mask", stems, "a", {"_mask"}) == "a/f1.tif"
+ assert _mask_owner("f1_dna", stems, "a", {"_mask"}) is None
+ assert _mask_owner("g", stems, "b", None) is None
+
+
+def _brute_owner(stem, stems, folder, suffixes):
+ """The owner as the screen found it before v0.9.0's fix: every position compared."""
+ keys = [
+ key
+ for key in stems
+ if key != stem
+ and stem.startswith(key + "_")
+ and (suffixes is None or stem[len(key) :] in suffixes)
+ ]
+ if not keys:
+ return None
+ owners = stems[max(keys, key=len)]
+ near = [owner for owner in owners if str(PurePosixPath(owner).parent) == folder]
+ return (near or owners)[0]
+
+
+def test_the_looked_up_owner_is_the_one_every_comparison_found():
+ rng = random.Random(7)
+ names = ["a", "b", "f1", "A"]
+ parts = ["a", "b", "f1", "x", "mask", "cells", "", "A"]
+ images = sorted(
+ {
+ rng.choice(["", "c1/", "c2/r1/", "c2/masks/"]) # top-level images too
+ + "_".join([rng.choice(names), *(rng.choice(parts) for _ in range(rng.randint(0, 3)))])
+ + ".tif"
+ for _ in range(400)
+ }
+ )
+ stems = _stems(images)
+ for suffixes in (None, {"_mask", "_cells"}):
+ for rel in images:
+ path = PurePosixPath(rel)
+ stem, folder = path.stem.lower(), str(path.parent)
+ assert _mask_owner(stem, stems, folder, suffixes) == _brute_owner(
+ stem, stems, folder, suffixes
+ ), (rel, suffixes)
+
+
+def test_the_mask_name_screen_finds_the_same_masks(tmp_path):
+ from morphobricks_preprocessing.discovery import discover_experiment
+
+ root = tmp_path / "exp"
+ for rel in ("c/r/f1.tif", "c/r/f1_mask.tif", "c/r/f1_2.tif", "c/masks/f1.tif", "d/r/g.tif"):
+ write_tiff(root / rel)
+ issues = {i.code: list(i.paths) for i in mask_name_issues(discover_experiment(root).leaves)}
+ assert issues["image_named_as_mask"] == ["c/r/f1_mask.tif"]
+ assert "mask_folder_in_experiment" in issues
+
+
+# --- a wait whose elapsed time goes on --------------------------------------------------------
+
+
+def test_a_ticking_wait_redraws_its_elapsed_time_and_stops_with_its_block():
+ pytest.importorskip("ipywidgets")
+ import ipywidgets as widgets
+
+ from morphobricks_preprocessing.notebook_progress import Wait
+
+ target = widgets.HTML()
+ seen = []
+ target.observe(lambda change: seen.append(change["new"]), names="value")
+ now = [100.0]
+ wait = Wait(target, bar=False, clock=lambda: now[0])
+ wait.start("Preparing")
+ with wait.ticking(interval=0.01):
+ deadline = time.monotonic() + 5
+ while len(seen) < 4 and time.monotonic() < deadline:
+ now[0] += 61
+ time.sleep(0.01)
+ drawn = len(seen)
+ target.value = "the result"
+ time.sleep(0.05)
+ assert drawn >= 4, "the elapsed time was never redrawn"
+ assert any("1:01 elapsed" in line or re.search(r"[1-9]:\d\d elapsed", line) for line in seen)
+ assert target.value == "the result" and len(seen) == drawn + 1
+ assert not [t for t in threading.enumerate() if t.name == "morphobricks-wait-tick"]
+
+
+# --- the notebook's Run ---------------------------------------------------------------------------
+
+
+@pytest.mark.usefixtures("legacy_grid") # the per-unit grid (the guided step has its own)
+def test_the_notebook_run_shows_each_header_it_checks_again(exp): # noqa: F811
+ pytest.importorskip("ipywidgets")
+ pytest.importorskip("matplotlib")
+ from test_notebook_axes_quick import stepper
+
+ nb = stepper(*exp)
+ nb.quick_confirm.click()
+ answer_all(nb)
+ assert nb.save_experiment()
+ notes = []
+ nb.run_next.observe(lambda change: notes.append(change["new"]), names="value")
+ seen = []
+ nb.run_status.observe(
+ lambda change: seen.append(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", change["new"]))),
+ names="value",
+ )
+ assert nb.run().written
+ lines = [line.strip() for line in seen]
+ assert lines[0].startswith("Preparing: checking the folders and the image headers again")
+ headers = [line for line in lines if line.startswith("Preparing: reading the image headers")]
+ assert any(
+ re.match(r"Preparing: reading the image headers again · 0 of \d+ .*elapsed", line)
+ for line in headers
+ ), lines[:5]
+ first_read = next(i for i, line in enumerate(lines) if line.startswith("Reading images"))
+ assert any(line.startswith("Preparing: comparing the images") for line in lines[:first_read])
+ assert any(
+ re.match(r"Preparing: reading each image whole for its content SHA-256 · 0 of \d+", line)
+ for line in lines[:first_read]
+ ), lines
+ assert "elapsed" not in lines[-1] # the result replaced the wait, and stayed
+ # While it goes, the run says that a cell run meanwhile waits for it; then that goes.
+ assert "A cell run meanwhile (this one too) waits for it" in notes[0]
+ assert "waits for it" not in nb.run_next.value
+
+
+def test_the_run_wait_counts_real_totals_and_ends_at_n_of_n():
+ 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
+
+ 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")
+ # What preflight reports for 3 images and no masks (its placeholders included).
+ calls = [
+ ("folders", 0, 1, ""),
+ ("folders", 1, 1, ""),
+ ("headers", 0, 3, ""),
+ *(("headers", i, 3, f"c/{i}.tif") for i in range(3)),
+ ("headers", 3, 3, ""),
+ ("masks", 0, 1, ""),
+ ("masks", 1, 1, ""),
+ ("acquisitions", 0, 1, ""),
+ ("acquisitions", 1, 1, ""),
+ ("contents", 0, 3, "c/0.tif"),
+ ("contents", 3, 3, ""),
+ ]
+ for call in calls:
+ now[0] += 1 # past the redraw interval
+ _RunStep._checking(step, *call)
+ lines = [line.strip() for line in seen]
+ assert any(
+ line.startswith("Preparing: reading the image headers again · 3 of 3") for line in lines
+ )
+ masks = [line for line in lines if "mask headers" in line]
+ assert masks and not any(" of " in line for line in masks), masks # no masks: no "0 of 1"
+ assert lines[-1].startswith(
+ "Preparing: reading each image whole for its content SHA-256 · 3 of 3"
+ )