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 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`.
Expand Down
21 changes: 12 additions & 9 deletions src/morphobricks_preprocessing/mask_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down
104 changes: 90 additions & 14 deletions src/morphobricks_preprocessing/notebook_progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,37 @@
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

MEASURABLE_SECONDS = 1.0
"""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 = (
"<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 "
"kernel (Colab: Runtime > Interrupt execution).</div>"
)
"""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:
Expand Down Expand Up @@ -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:
Expand All @@ -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."""
Expand All @@ -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.
Expand All @@ -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",
]
35 changes: 31 additions & 4 deletions src/morphobricks_preprocessing/notebook_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -396,20 +402,24 @@ 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

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()
Expand Down Expand Up @@ -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())
Expand Down
22 changes: 20 additions & 2 deletions src/morphobricks_preprocessing/run/modes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -89,13 +90,21 @@ 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
verify_content: bool | None = None
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:
Expand Down Expand Up @@ -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:
Expand Down
6 changes: 6 additions & 0 deletions src/morphobricks_preprocessing/run/phases.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down
Loading
Loading