From a377c78eb385d3f3cb83635fbd65b8a508c40393 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:11:19 +0000 Subject: [PATCH 01/25] Entry identity: reusable outputs in conda; warn on an uncertain first write Conda installs setuptools as an .egg-info without RECORD, and brick_identity's closure (every extra included) reached it, so every entry record written in a conda environment was uncertain and every rerun refused with ENTRY_IDENTITY_UNCERTAIN (setuptools: RECORD missing). - entry_identity: the installers pip, setuptools and wheel are neither listed nor followed in the requirement closure (INSTALL_TOOLS); every other library without RECORD stays uncertain (ADR 0007 (b)); a caller's explicit name is still identified. uncertain_library names the library behind an uncertain brick part. - entry_record: write_entry_record warns (EntryIdentityWarning, text from identity_warning) that an output written under an uncertain identity will never be reused. - entry_errors: uncertain_code_fix; the ENTRY_IDENTITY_UNCERTAIN fix names an uncertain library and why instead of telling the user to reinstall a brick that is already a released install. - Tests with egg-info distributions in a temporary site folder; docs (contract 21.2/21.4, plan 12 question 93), CHANGELOG Unreleased (v0.10.1). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp98tSnytZ9QCrHt6297 --- AGENTS.md | 3 +- CHANGELOG.md | 26 ++++++ docs/contract.md | 15 +++- docs/plan.md | 15 ++++ src/morphobricks_preprocessing/__init__.py | 4 + .../entry_errors.py | 53 ++++++++++-- .../entry_identity.py | 40 +++++++-- .../entry_record.py | 38 ++++++++- tests/code_identity_tree.py | 22 ++++- tests/test_entry_identity.py | 84 +++++++++++++++++++ tests/test_entry_record.py | 40 ++++++++- 11 files changed, 321 insertions(+), 19 deletions(-) create mode 100644 tests/test_entry_identity.py diff --git a/AGENTS.md b/AGENTS.md index b513a96f..91b99efb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -232,7 +232,8 @@ src/morphobricks_preprocessing/ 0011 settings file, Q10), folder_values (no pixel), settings_template entry_record.py morphobricks_entry.json: build_record, write_entry_record, check_entry_record, EntryResult, reuse_or_refuse (RE10); entry_identity.py brick_identity (every - file of the brick hashed against RECORD, libraries by RECORD digest); + file of the brick hashed against RECORD, libraries by RECORD digest; + pip, setuptools and wheel left out: INSTALL_TOOLS, v0.10.1); entry_publish.py default_output, check_output_place, staging_folder, publish (renameat2 RENAME_NOREPLACE, or an exclusive mkdir) notebook_entry_card.py the card "Run on a validated folder" of every brick (ADR 0007 Q6) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cca45e7..4dbbef02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,32 @@ The design is [`docs/design-v0.4.md`](docs/design-v0.4.md), imported unchanged f are in [docs/plan.md](docs/plan.md) §12. (The v0.3 to v0.4 migration guide was removed in v0.5.1: no run before v0.5.1 is read.) +## Unreleased (v0.10.1) + +### Fixed + +- **An entry output is reusable in a conda environment** (Spec ADR 0007 RE10). Conda installs + `setuptools` as an `.egg-info` with no `RECORD`, and `brick_identity` followed every + requirement of the brick, every extra included, down to it: every record written there was + `uncertain`, so every rerun and `check` of the output was refused with + `ENTRY_IDENTITY_UNCERTAIN: ... (setuptools: RECORD missing)`. The installers `pip`, + `setuptools` and `wheel` are now neither listed nor followed in the identity's closure + (`entry_identity.INSTALL_TOOLS`): no brick computes a value with them. Any other library + without a `RECORD`, or editable, still makes the identity uncertain (ADR 0007 (b)); a name a + brick passes in `libraries` is identified whatever it is. An output whose v0.10.0 record lists + one of them is another identity for v0.10.1 (`ENTRY_OUTPUT_EXISTS` naming it); upgrading + preprocessing changes every brick's identity anyway, preprocessing being one of its libraries + (plan §12 question 93). +- **A first run under an uncertain identity says so.** `write_entry_record` writes the record and + warns with `EntryIdentityWarning` (text from the new `identity_warning`, both re-exported) that + the output will never be reused, naming the reason and the fix, instead of only the next run + failing. +- **The refusal's fix names the actual cause.** When the brick is a released install and a + library is what is uncertain, the fix of `ENTRY_IDENTITY_UNCERTAIN` names that library (no + `RECORD`: reinstall it with `pip install --force-reinstall --no-deps "=="`; or + an editable install) and says the brick needs no change, instead of "Install a released + ``" (`entry_errors.uncertain_code_fix`, `entry_identity.uncertain_library`). + ## v0.10.0 (3 December 2026) Minor release with a **breaking change of file format**: the histogram table is diff --git a/docs/contract.md b/docs/contract.md index 0a46176c..d26ff526 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1751,7 +1751,12 @@ no image of the run. **21.2 Entry refusals** (`entry_errors`). `EntryError` (`code`, `message`, `fix`, `subjects`; `as_json()` for the command line's stderr): `ENTRY_SETTING_MISSING`, `ENTRY_SETTING_INVALID`, `ENTRY_OUTPUT_PLACE`, `ENTRY_OUTPUT_EXISTS`, `ENTRY_OUTPUT_INCOMPLETE`, `ENTRY_IDENTITY_UNCERTAIN`, -one constructor each, with the ADR's texts under its revision R2 (choices are settings). +one constructor each, with the ADR's texts under its revision R2 (choices are settings). Ahead of +the ADR (v0.10.1, plan §12 question 93): when the brick is a released install and a library of +its identity is what is uncertain, the fix of `ENTRY_IDENTITY_UNCERTAIN` cases (a)-(c) names that +library and why (`uncertain_code_fix`: no `RECORD`, with the `pip install --force-reinstall +--no-deps "=="` that writes one, or an editable install) instead of telling the +user to reinstall the brick. **21.3 Settings** (`entry_settings`, `entry_declaration`). A brick declares its settings in its ADR 0011 `defaults.toml` plus a static `entry_settings.json` keyed `
.` (`type`, @@ -1768,7 +1773,13 @@ canonical JSON (sorted keys, UTF-8, LF), written last: `entry_version` (1), `bri `source`, `resolver`, `settings`, `execution`, `locations`, `outputs`, `identity` (the SHA-256 of the canonical JSON of `entry_version`, `brick`, `run_folder` without its path and the table's file SHA-256, `resolver`, and the settings with `affects_values`) and `written_at`. Reuse or refuse -(`reuse_or_refuse`) follows ADR 0007 RE10; publication is exclusive (`publish`). +(`reuse_or_refuse`) follows ADR 0007 RE10; publication is exclusive (`publish`). The libraries +of `brick` are the brick's requirements, directly or through another, every extra included, +**except the installers `pip`, `setuptools` and `wheel`** (`entry_identity.INSTALL_TOOLS`, v0.10.1, +plan §12 question 93), which are neither listed nor followed; a name the brick passes in +`libraries` is identified whatever it is. `write_entry_record` of a record whose `brick` is +`uncertain` writes it and warns (`EntryIdentityWarning`, text `identity_warning`) that the output +will never be reused, naming the reason and the fix. **21.5 Test helpers.** `testing_spy.decoder_spy` counts every pixel-decoding route; `testing_folder_states.derive_state` and `report_state` make the folder states of ADR 0007 row E2. diff --git a/docs/plan.md b/docs/plan.md index a391f787..2a6935c0 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -1819,3 +1819,18 @@ Raised during review; to be decided before the milestones that need them: hashes is `RUN_FOLDER_CONTENT_NOT_RECORDED` (ahead of the ADR, Spec issue 84); masks stay `fingerprint` for now (the run records no mask hash; a separate issue). +93. Why was an entry output never reused in a conda environment, and what is left out of the + code identity? *Decided (3 December 2026, in the session fixing the v0.10.0 wave's + entry-identity gap; for the owner's review):* conda installs `setuptools` as an `.egg-info` + with no `RECORD`, and the identity's closure, every extra included, reached it, so every + record was `uncertain` (ADR 0007 (b)) and every rerun refused. The installers `pip`, + `setuptools` and `wheel` leave the closure (`entry_identity.INSTALL_TOOLS`): they install and + build distributions and no brick computes a value with them, so they are not libraries "the + brick may compute with". The smallest change the ADR allows: dropping extras would make the + identity weaker than MorphoFeature's `brick_cache` key (which takes every extra) and would not + remove `setuptools`, which some libraries require with no extra (torch on Python 3.12); + identifying an `.egg-info` by name and version would contradict ADR 0007 (b), which keeps + every other library without a `RECORD` uncertain. A first run under an uncertain identity now + warns that its output will never be reused (`EntryIdentityWarning`), and the refusal's fix + names an uncertain library rather than the brick. The ADR's record paragraph is to say that + the installers are not followed (a Spec note for the owner). diff --git a/src/morphobricks_preprocessing/__init__.py b/src/morphobricks_preprocessing/__init__.py index 31457c35..a0daf251 100644 --- a/src/morphobricks_preprocessing/__init__.py +++ b/src/morphobricks_preprocessing/__init__.py @@ -99,12 +99,14 @@ ) from .entry_record import ( ENTRY_FILENAME, + EntryIdentityWarning, EntryResult, brick_identity, build_record, check_entry_record, check_output_place, default_output, + identity_warning, publish, reuse_or_refuse, staging_folder, @@ -372,6 +374,7 @@ "DiscoveryResult", "EntryDeclaration", "EntryError", + "EntryIdentityWarning", "EntryResult", "EntrySettings", "FileEntry", @@ -510,6 +513,7 @@ "he_tissue_mask_array", "header_axes", "header_axis_issue", + "identity_warning", "image_type_issues", "inspect_experiment", "inspect_image", diff --git a/src/morphobricks_preprocessing/entry_errors.py b/src/morphobricks_preprocessing/entry_errors.py index 751dc530..29ae5af0 100644 --- a/src/morphobricks_preprocessing/entry_errors.py +++ b/src/morphobricks_preprocessing/entry_errors.py @@ -229,8 +229,50 @@ def entry_output_incomplete(output: str | Path, brick: str, reason: str) -> Entr ) +def uncertain_code_fix( + brick: str = "the brick", library: tuple[str, str | None, str] | None = None +) -> str: + """Return the fix of ``ENTRY_IDENTITY_UNCERTAIN`` cases (a)-(c): the installed code. + + Parameters + ---------- + brick + The brick's distribution name. + library + When a library, not the brick, is what is uncertain: its name, installed version and + why (``"editable install"`` or ``"RECORD missing"``, from + :func:`.entry_identity.library_identity`). + The ADR's text names the brick; telling the user to reinstall a brick that is already a + released install would not help, so the fix names the library instead. + """ + if library is None: + return ( + f"Install a released {brick} (not editable, its files as its RECORD lists them), " + "or give another --output." + ) + name, version, why = library + pinned = f"{name}=={version}" if version else name + if why == "RECORD missing": + return ( + f"The library {name} {version or ''}".rstrip() + + " is installed without a RECORD file (conda and setup.py installs write none), " + f"so its files cannot be identified; {brick} itself needs no change. Reinstall " + f'{name} with pip (pip install --force-reinstall --no-deps "{pinned}"), or give ' + "another --output." + ) + return ( + f"The library {name} is an editable install; {brick} itself needs no change. Install a " + f'released {name} (pip install "{pinned}"), or give another --output.' + ) + + def entry_identity_uncertain( - output: str | Path, reason: str, case: str, brick: str = "the brick" + output: str | Path, + reason: str, + case: str, + brick: str = "the brick", + *, + library: tuple[str, str | None, str] | None = None, ) -> EntryError: """Return ``ENTRY_IDENTITY_UNCERTAIN``: the output cannot be compared with this run. @@ -245,14 +287,15 @@ def entry_identity_uncertain( :data:`UNCERTAIN_MOVED` ((e)); it chooses the fix. brick The brick's distribution name, for case (a)-(c)'s fix. + library + For case (a)-(c), the library that is uncertain when the brick itself is not + (:func:`.entry_identity.uncertain_library`); the fix then names it + (:func:`uncertain_code_fix`). """ if case not in _UNCERTAIN_CASES: raise ValueError(f"{case!r} is not one of {_UNCERTAIN_CASES}") fix = { - UNCERTAIN_CODE: ( - f"Install a released {brick} (not editable, its files as its RECORD lists them), " - "or give another --output." - ), + UNCERTAIN_CODE: uncertain_code_fix(brick, library), UNCERTAIN_RECORD: "Give another --output.", UNCERTAIN_MOVED: ( "Open the run folder with the experiment and masks folders at the location the " diff --git a/src/morphobricks_preprocessing/entry_identity.py b/src/morphobricks_preprocessing/entry_identity.py index 4d0abced..f89726f8 100644 --- a/src/morphobricks_preprocessing/entry_identity.py +++ b/src/morphobricks_preprocessing/entry_identity.py @@ -5,14 +5,21 @@ commit, with **every installed file of the brick hashed** against ``RECORD`` on each run (:func:`.code_identity.code_identity`, owner decision of 19 November 2026); the Python version and the machine; every library the brick may compute with (each requirement of its -distribution, directly or through another, whatever its extra or marker; the names a caller -adds, such as MorphoFeature's ``RESULT_LIBRARIES``; every installed ``nvidia-*``), each by name, +distribution, directly or through another, whatever its extra or marker, except the installers +:data:`INSTALL_TOOLS`; the names a caller adds, such as MorphoFeature's ``RESULT_LIBRARIES``; +every installed ``nvidia-*``), each by name, version, Git commit and the SHA-256 of its ``RECORD``, with **no per-file hashing of libraries**; the thread setting (recorded in the ``brick`` part but left out of the record's identity digest: ADR 0007 RE7, owner decision 3 of 1 December 2026); a provider manifest's and the model weights' SHA-256. An editable install of the brick or of a library, a brick or library without ``RECORD``, or a brick file that differs from its ``RECORD`` makes the identity ``uncertain`` (never reused). + +The installers ``pip``, ``setuptools`` and ``wheel`` are not followed as requirements (v0.10.1): +they install and build distributions, no brick computes a value with them, and conda installs +``setuptools`` as an ``.egg-info`` without ``RECORD``, which made every entry output written in a +conda environment uncertain (never reused). A caller that names one in ``libraries`` still has +it identified. """ from __future__ import annotations @@ -37,6 +44,8 @@ "NUMBA_NUM_THREADS", ) """The thread variables MorphoFeature's ``brick_cache`` keys on (its ``threads.py``).""" +INSTALL_TOOLS = frozenset({"pip", "setuptools", "wheel"}) +"""Installers left out of the requirement closure: no brick computes with them (v0.10.1).""" _REQUIREMENT_NAME = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?") @@ -57,7 +66,8 @@ def _normalized(name: str) -> str: def _requirements(name: str) -> set[str]: """Return every distribution ``name`` requires, directly or through an installed one. - Every requirement counts, whatever its extra or marker (MorphoFeature's ``brick_cache``). + Every requirement counts, whatever its extra or marker (MorphoFeature's ``brick_cache``), + except the installers :data:`INSTALL_TOOLS`, which are neither listed nor followed. """ found: set[str] = set() pending = [_normalized(name)] @@ -68,7 +78,9 @@ def _requirements(name: str) -> set[str]: continue # recorded as absent for requirement in requires: match = _REQUIREMENT_NAME.match(requirement.strip()) - if match and _normalized(match.group()) not in found: + if not match or _normalized(match.group()) in INSTALL_TOOLS: + continue + if _normalized(match.group()) not in found: found.add(_normalized(match.group())) pending.append(_normalized(match.group())) return found @@ -111,6 +123,23 @@ def library_identity(name: str) -> dict[str, object]: return found +def uncertain_library(brick: Mapping[str, object]) -> tuple[str, str | None, str] | None: + """Return the library that makes a ``brick`` part uncertain: name, version and why. + + None when the brick is certain or when its own code is what is uncertain (the brick's + reason comes first, as in :func:`brick_identity`). + """ + code = brick.get("code") + if not brick.get("uncertain") or not isinstance(code, Mapping) or not code.get("verified"): + return None + libraries = brick.get("libraries") + for name, found in (libraries if isinstance(libraries, Mapping) else {}).items(): + if isinstance(found, Mapping) and found.get("uncertain"): + version = found.get("version") + return str(name), version if isinstance(version, str) else None, str(found["uncertain"]) + return None + + def thread_setting(threads: Mapping[str, object] | None = None) -> dict[str, object]: """Return the thread setting of the identity (RE7, MorphoFeature's ``thread_identity``). @@ -141,7 +170,8 @@ def brick_identity( The brick's ID, as the output name uses it. libraries Libraries the brick computes with besides its requirements (MorphoFeature's - ``RESULT_LIBRARIES``); every installed ``nvidia-*`` is always added. + ``RESULT_LIBRARIES``), identified even when one is in :data:`INSTALL_TOOLS`; every + installed ``nvidia-*`` is always added. provider_manifest_sha256 For a MorphoFeature provider, its manifest's SHA-256. weights diff --git a/src/morphobricks_preprocessing/entry_record.py b/src/morphobricks_preprocessing/entry_record.py index 53a5daf5..502b419b 100644 --- a/src/morphobricks_preprocessing/entry_record.py +++ b/src/morphobricks_preprocessing/entry_record.py @@ -43,6 +43,7 @@ import json import os import re +import warnings from collections.abc import Iterable, Mapping from dataclasses import dataclass from pathlib import Path @@ -56,10 +57,12 @@ entry_identity_uncertain, entry_output_exists, entry_output_incomplete, + uncertain_code_fix, ) from .entry_identity import brick_identity as brick_identity from .entry_identity import library_identity as library_identity from .entry_identity import plain as _plain +from .entry_identity import uncertain_library as uncertain_library from .entry_publish import ENTRY_FILENAME as ENTRY_FILENAME from .entry_publish import check_output_place as check_output_place from .entry_publish import default_output as default_output @@ -90,6 +93,29 @@ class EntryRecordError(ValueError): """A ``morphobricks_entry.json`` that is not a record this package reads (the reason).""" +class EntryIdentityWarning(UserWarning): + """An output written under an uncertain code identity: it will never be reused (RE10).""" + + +def identity_warning(record: Mapping, output: str | os.PathLike | None = None) -> str | None: + """Return what a first run under an uncertain identity tells its user, or None if certain. + + ADR 0007 RE10 publishes such an output and never reuses it; saying so when it is written + spares the user a refusal they cannot explain on the next run. ``output`` is the published + output's path, when known (:func:`write_entry_record` writes into the staging folder). + """ + brick = record["brick"] + if not brick.get("uncertain"): + return None + fix = uncertain_code_fix(str(brick.get("distribution")), uncertain_library(brick)) + subject = "This output" if output is None else f"The output {output}" + return ( + f"{subject} is written, but its code identity is uncertain ({brick['uncertain']}), so " + "it will never be reused: a later run or check with this output is refused with " + f"ENTRY_IDENTITY_UNCERTAIN. {fix}" + ) + + @dataclass(frozen=True) class EntryResult: """What a brick's entry returns (ADR 0007 "The entry contract"). @@ -254,10 +280,14 @@ def write_entry_record(folder: str | os.PathLike, record: Mapping) -> Path: """Write ``record`` as ``morphobricks_entry.json`` in ``folder`` (canonical, UTF-8, LF). Call it last: the record marks a complete output. It is checked by :func:`check_entry_record` - before it is written, and never replaces an existing record. + before it is written, and never replaces an existing record. A record whose ``brick`` is + uncertain is written and an :class:`EntryIdentityWarning` (:func:`identity_warning`) says that + the output will never be reused. """ data = _plain(record) _checked(data, Path(folder) / ENTRY_FILENAME) + if (message := identity_warning(data)) is not None: + warnings.warn(message, EntryIdentityWarning, stacklevel=2) text = json.dumps(data, sort_keys=True, ensure_ascii=False, indent=1) + "\n" path = Path(folder) / ENTRY_FILENAME with open(path, "x", encoding="utf-8", newline="\n") as handle: @@ -475,7 +505,11 @@ def reuse_or_refuse( return None if record["brick"].get("uncertain"): raise entry_identity_uncertain( - folder, record["brick"]["uncertain"], UNCERTAIN_CODE, record["brick"]["distribution"] + folder, + record["brick"]["uncertain"], + UNCERTAIN_CODE, + record["brick"]["distribution"], + library=uncertain_library(record["brick"]), ) path = folder / ENTRY_FILENAME if not path.is_file() or path.is_symlink(): diff --git a/tests/code_identity_tree.py b/tests/code_identity_tree.py index 08bc3060..040521d3 100644 --- a/tests/code_identity_tree.py +++ b/tests/code_identity_tree.py @@ -19,14 +19,19 @@ def _hash(data): return "sha256=" + base64.urlsafe_b64encode(digest).rstrip(b"=").decode() -def install(site, files=FILES, *, editable=False, unhashed=(), commit=COMMIT): - """Install ``files`` as the distribution ``fakepkg`` 1.0 under ``site``; return it.""" +def install(site, files=FILES, *, editable=False, unhashed=(), commit=COMMIT, requires=()): + """Install ``files`` as the distribution ``fakepkg`` 1.0 under ``site``; return it. + + ``requires`` are its ``Requires-Dist`` lines. + """ info = site / "fakepkg-1.0.dist-info" info.mkdir(parents=True) for name, data in files.items(): (site / name).parent.mkdir(parents=True, exist_ok=True) (site / name).write_bytes(data) - (info / "METADATA").write_bytes(b"Metadata-Version: 2.1\nName: fakepkg\nVersion: 1.0\n") + lines = ["Metadata-Version: 2.1", "Name: fakepkg", "Version: 1.0"] + lines += [f"Requires-Dist: {requirement}" for requirement in requires] + (info / "METADATA").write_text("\n".join(lines) + "\n", encoding="utf-8") url = {"url": "file:///src/fakepkg"} url |= {"dir_info": {"editable": True}} if editable else {"vcs_info": {"commit_id": commit}} (info / "direct_url.json").write_text(json.dumps(url), encoding="utf-8") @@ -41,6 +46,17 @@ def install(site, files=FILES, *, editable=False, unhashed=(), commit=COMMIT): return metadata.PathDistribution(info) +def install_egg_info(site, name, version, requires=()): + """Install ``name`` as conda installs ``setuptools``: an ``.egg-info`` with no ``RECORD``.""" + info = site / f"{name}-{version}-py3.egg-info" + info.mkdir(parents=True) + (info / "PKG-INFO").write_text( + f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n", encoding="utf-8" + ) + (info / "requires.txt").write_text("".join(f"{r}\n" for r in requires), encoding="utf-8") + return metadata.PathDistribution(info) + + def modules_of(site, names=("fakepkg", "fakepkg.mod")): """Imported modules of the installation, as ``sys.modules`` would hold them.""" paths = {"fakepkg": "fakepkg/__init__.py", "fakepkg.mod": "fakepkg/mod.py"} diff --git a/tests/test_entry_identity.py b/tests/test_entry_identity.py new file mode 100644 index 00000000..53f49b64 --- /dev/null +++ b/tests/test_entry_identity.py @@ -0,0 +1,84 @@ +"""The requirement closure of an entry's code identity (Spec ADR 0007 "The run record"). + +A conda environment installs ``setuptools`` as an ``.egg-info`` with no ``RECORD``; every entry +output written there was uncertain (never reused) because the closure, every extra included, +reached it. The installers pip, setuptools and wheel are left out of the closure (v0.10.1); any +other library without a ``RECORD`` stays uncertain (ADR 0007 (b)), and the refusal's fix names +that library instead of telling the user to reinstall the brick. +""" + +from __future__ import annotations + +from code_identity_tree import install, install_egg_info +from morphobricks_preprocessing import entry_identity +from morphobricks_preprocessing.entry_errors import ( + UNCERTAIN_CODE, + entry_identity_uncertain, + uncertain_code_fix, +) + + +def test_a_conda_setuptools_egg_info_no_longer_makes_the_identity_uncertain(tmp_path, monkeypatch): + site = tmp_path / "site" + install(site, requires=("setuptools>=60", 'wheel; extra == "build"', "pip")) + install_egg_info(site, "setuptools", "65.6.3", requires=("eggy",)) + install_egg_info(site, "wheel", "0.41.0") + install_egg_info(site, "pip", "24.0") + monkeypatch.syspath_prepend(str(site)) + # The fake egg-info is what metadata finds: without the exclusion it would be uncertain. + assert entry_identity.library_identity("setuptools")["uncertain"] == "RECORD missing" + identity = entry_identity.brick_identity("fakepkg", "fake") + assert identity["uncertain"] is None + assert not {"setuptools", "wheel", "pip", "eggy"} & set(identity["libraries"]) + assert entry_identity.uncertain_library(identity) is None + + +def test_an_installer_the_caller_names_is_still_identified(tmp_path, monkeypatch): + site = tmp_path / "site" + install(site) + install_egg_info(site, "setuptools", "65.6.3") + monkeypatch.syspath_prepend(str(site)) + identity = entry_identity.brick_identity("fakepkg", "fake", libraries=["setuptools"]) + assert identity["uncertain"] == "setuptools: RECORD missing" + + +def test_another_egg_info_library_stays_uncertain_and_the_fix_names_it(tmp_path, monkeypatch): + site = tmp_path / "site" + install(site, requires=("eggy>=2",)) + install_egg_info(site, "eggy", "2.0") + monkeypatch.syspath_prepend(str(site)) + identity = entry_identity.brick_identity("fakepkg", "fake") + assert identity["code"]["verified"] is True # the brick itself is a released install + assert identity["uncertain"] == "eggy: RECORD missing" + library = entry_identity.uncertain_library(identity) + assert library == ("eggy", "2.0", "RECORD missing") + error = entry_identity_uncertain( + "/out", identity["uncertain"], UNCERTAIN_CODE, "fakepkg", library=library + ) + assert "Install a released fakepkg" not in error.message + assert "(eggy: RECORD missing)" in error.message + assert error.fix == ( + "The library eggy 2.0 is installed without a RECORD file (conda and setup.py installs " + "write none), so its files cannot be identified; fakepkg itself needs no change. " + 'Reinstall eggy with pip (pip install --force-reinstall --no-deps "eggy==2.0"), or give ' + "another --output." + ) + + +def test_the_fix_for_the_brick_itself_is_the_adrs(): + assert uncertain_code_fix("fakepkg") == ( + "Install a released fakepkg (not editable, its files as its RECORD lists them), or give " + "another --output." + ) + editable = uncertain_code_fix("fakepkg", ("lib", "1.0", "editable install")) + assert editable.startswith("The library lib is an editable install; fakepkg itself") + assert 'pip install "lib==1.0"' in editable + + +def test_an_uncertain_brick_comes_before_its_libraries(): + brick = { + "uncertain": "demo: editable install", + "code": {"verified": False}, + "libraries": {"eggy": {"version": "2.0", "uncertain": "RECORD missing"}}, + } + assert entry_identity.uncertain_library(brick) is None diff --git a/tests/test_entry_record.py b/tests/test_entry_record.py index 9a6b9053..27d608fe 100644 --- a/tests/test_entry_record.py +++ b/tests/test_entry_record.py @@ -12,6 +12,7 @@ import json import os import sys +import warnings import pytest from morphobricks_normalization.contracts import ResolverVersionError @@ -163,12 +164,49 @@ def test_uncertain_identities_are_refused(run): def test_a_first_run_under_an_uncertain_identity_is_published_and_never_reused(run): output = entry.default_output(run.output, "demo") editable = dict(BRICK, uncertain="demo: editable install") - published, record = _compute(run, output, brick=editable) + with pytest.warns(entry.EntryIdentityWarning, match="will never be reused") as caught: + published, record = _compute(run, output, brick=editable) + assert len(caught) == 1 and "(demo: editable install)" in str(caught[0].message) + assert "Install a released demo" in str(caught[0].message) assert published and record["brick"]["uncertain"] == "demo: editable install" with pytest.raises(EntryError, match="computed under an uncertain identity"): entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(3,)) +def test_a_certain_first_run_warns_nothing(run): + with warnings.catch_warnings(): + warnings.simplefilter("error", entry.EntryIdentityWarning) + _compute(run, entry.default_output(run.output, "demo")) + + +def test_an_uncertain_library_is_named_on_first_write_and_in_the_refusal(run): + """A released brick with one library installed without RECORD: the fix names the library.""" + libraries = dict( + BRICK["libraries"], + eggy={ + "version": "2.0", + "vcs_commit": None, + "record_sha256": None, + "uncertain": "RECORD missing", + }, + ) + brick = dict(BRICK, libraries=libraries, uncertain="eggy: RECORD missing") + output = entry.default_output(run.output, "demo") + with pytest.warns(entry.EntryIdentityWarning) as caught: + _compute(run, output, brick=brick) + message = str(caught[0].message) + assert "Reinstall eggy with pip" in message and "Install a released demo" not in message + assert entry.identity_warning(_record(run, brick=brick), output).startswith( + f"The output {output} is written, but its code identity is uncertain" + ) + with pytest.raises(EntryError) as raised: + entry.reuse_or_refuse(output, _record(run, brick=brick), supported_resolver_versions=(3,)) + assert raised.value.code == "ENTRY_IDENTITY_UNCERTAIN" + assert "(eggy: RECORD missing)" in raised.value.message + assert raised.value.fix.startswith("The library eggy 2.0 is installed without a RECORD file") + assert "demo itself needs no change" in raised.value.fix + + def test_an_unsupported_resolver_version_is_refused(run): output = entry.default_output(run.output, "demo") _compute(run, output) From add0367b0c587e94a462270be73150e48d65340b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:18:02 +0000 Subject: [PATCH 02/25] Fix the command-line gaps before the next brick (v0.10.1) - describe: fast mode no longer crashes on images fewer than three folder levels deep (condition/img.tif, an image in the experiment folder); the tagged unit comes from the discovered leaf folder. - describe --rgb-header-override [FOLDER]: records rgb_header_override = true as the notebook does; the refusal of minisblack RGB TIFFs names it. - check reports an undeclared mask type (OME-Zarr labels included) as run refuses it; declare-masks prints next commands without a placeholder masks folder when none was given. - describe lists open questions only while the fast-mode options leave some. - check and run suggest rgb when the published description declares every acquisition rgb (OME-Zarr states no colour interpretation). - convert --store ome-zarr. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp983bS22og2asjnEc8P --- AGENTS.md | 4 +- CHANGELOG.md | 46 +++ docs/contract.md | 2 +- docs/user_guide.md | 53 +++- src/morphobricks_preprocessing/cli.py | 30 +- src/morphobricks_preprocessing/cli_convert.py | 41 ++- .../cli_declare_masks.py | 43 ++- .../cli_describe.py | 137 +++++++-- src/morphobricks_preprocessing/cli_run.py | 8 +- .../description_run_text.py | 27 +- .../fast_answers.py | 30 +- src/morphobricks_preprocessing/image_type.py | 45 ++- .../physical_check.py | 22 +- .../physical_unit.py | 10 +- .../run/description_run.py | 12 + tests/test_cli_usability.py | 277 ++++++++++++++++++ 16 files changed, 736 insertions(+), 51 deletions(-) create mode 100644 tests/test_cli_usability.py diff --git a/AGENTS.md b/AGENTS.md index b513a96f..08ef154a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1033,7 +1033,9 @@ functions the tests use. (the normalization brick's `check_rgb`), else `rgb_not_possible` in a run. - **Suggestion:** `rgb` only when every analysed image is a TIFF stored as RGB colour (`TiffMetadata.rgb_samples`: photometric RGB, three samples per pixel, axis `S`), the - confirmed C role is on `S`, and RGB is possible. Never applied without confirmation. + confirmed C role is on `S`, and RGB is possible; in `check` and `run` also when the + published description declares every acquisition `rgb` (`declared_image_type`, v0.10.1: + OME-Zarr states no colour). Never applied without confirmation. - **Notebook:** step 2's "Image type" card appears once the axis roles are confirmed (also when embedded); radio buttons with the suggestion preselected, disabled at fluorescence when RGB is impossible; `ConfirmToggle` **Yes, this is the right image diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cca45e7..0fe35195 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,52 @@ The design is [`docs/design-v0.4.md`](docs/design-v0.4.md), imported unchanged f are in [docs/plan.md](docs/plan.md) §12. (The v0.3 to v0.4 migration guide was removed in v0.5.1: no run before v0.5.1 is read.) +## Unreleased (v0.10.1) + +Patch release: command-line gaps a new user met before reaching the next brick (the clean +environment test of the v0.10.0 wave, 3 December 2026). No format change. + +### Fixed + +- **Fast `describe` with images fewer than three folder levels deep** no longer crashes + (`IndexError` in `cli_describe._unit_of`): images directly in condition folders + (`exp/condition_x/img.tif`, a documented layout) and an image in the experiment folder itself + (one OME-Zarr mosaic) take their unit from the discovered leaf folder (`single` for the missing + levels), as the draft does. +- **`check` reports an undeclared mask type** (an OME-Zarr label image, for example) as `run` + refuses it, `R_MASK_TYPE_NOT_DECLARED` with the same message and fix + (`physical_check.undeclared_mask_types`, shared); it exits with status 1. The message no + longer says "the masks folder" for label images, and its fix names the type found + (`--type cells=REPRESENTATION`), never a guessed representation. +- **`declare-masks` names the right next commands:** without `--masks` it no longer prints + `run --masks MASKS`; OME-Zarr label images and masks beside the images need no masks folder, + and the experiment folder is named (`EXPERIMENT`) only when no run of the output folder + records it. +- **Fast `describe` prints "N open questions (answered by you, in the notebook)" only when + questions remain:** with `--accept-ids`, `--comparable` and `--confirmed-on` it says the + options answer them; otherwise it lists only the questions left, naming the options. +- **The image-type suggestion of `check` and `run` follows the published description** when it + declares every acquisition `rgb` and RGB is possible (`image_type.declared_image_type`, + `review_image_type(..., declared=)`). An OME-Zarr copy written by + `convert_experiment(..., store="ome-zarr")` from RGB TIFFs cannot itself say it is RGB: + OME-NGFF 0.4 has no colour field (its `omero` colours are display only) and the conversion + record does not record it, so the suggestion cannot follow the converter; before, `run` + recorded such a run as `fluorescence` unless given `--image-type rgb`. + +### Added + +- **`describe --rgb-header-override [FOLDER]`** (fast mode, with `--image-type rgb`): records + `rgb_header_override = true` on every acquisition, or on the acquisition folders named + (repeatable), exactly as the notebook's Image type card does, for colour scanner TIFFs whose + header says *minisblack* (for example the Zenodo 4550300 cores). Refused with a channel list, + an unknown folder, a published description or `--strict`. The refusal of such images + (`R_FAST_LAYOUT_CONTRADICTION` and `R_IMAGE_TYPE_CONTRADICTS_HEADER`) now names the option + beside the notebook card. +- **`convert --store ome-zarr`** writes every image that is read as an OME-Zarr copy (OME-NGFF + 0.4, `.ome.zarr`), as `convert_experiment(..., store="ome-zarr")` and the notebook do; + RGB TIFFs included. Default `ome-tiff`, as before. The user guide (§5) shows the H&E route: + `convert --store ome-zarr`, `describe --image-type rgb`, `run`. + ## v0.10.0 (3 December 2026) Minor release with a **breaking change of file format**: the histogram table is diff --git a/docs/contract.md b/docs/contract.md index 0a46176c..5f8765f5 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -911,7 +911,7 @@ plan N34); this brick suggests it, asks for it after the axis roles, and records |---|---| | Types | `fluorescence` (any number of channels, every pixel type) and `rgb` (exactly three channels of an integer pixel type, the rule of the normalization brick's `check_rgb`). | | RGB samples | A TIFF image is stored as RGB colour when its first series has the photometric interpretation RGB with three samples per pixel (`tifffile` axis `S`; `TiffMetadata.rgb_samples`). RGB with an alpha sample, several grey samples and OME-Zarr images are not. | -| Suggestion | `rgb` when every analysed image is stored as RGB colour, the confirmed C role is on its samples axis, and `rgb` is possible; `fluorescence` otherwise. `review_image_type` gives the suggestion, why, and why `rgb` is not possible (from the headers and the confirmed axis roles; no pixels are read). | +| Suggestion | `rgb` when every analysed image is stored as RGB colour, the confirmed C role is on its samples axis, and `rgb` is possible; also `rgb` when the published description declares every acquisition `rgb` and `rgb` is possible (v0.10.1: OME-Zarr images, OME-Zarr copies of RGB TIFFs included, state no colour interpretation; `declared_image_type`); `fluorescence` otherwise. `review_image_type` gives the suggestion, why, and why `rgb` is not possible (from the headers and the confirmed axis roles; no pixels are read). | | Confirmation | Never applied without the user's confirmation. The notebook proposes it at the quick scan (display only, from the headers; nothing is recorded there) and asks on the Channels step once the axis roles are confirmed (owner, 12 November 2026), pre-filled only when every header agrees and recorded only by a click (**Use for all folders**, or each folder); folders of different types are refused (`R_HETEROGENEOUS_LAYOUT_NOT_ENABLED`). Changing the axis roles or the folder asks again. The run takes the type the saved description states. The command line takes `--image-type`, or uses the suggestion and prints it. | | Run | `run_experiment(..., image_type=...)` records the type and `channels_from_rgb_samples` in the manifest (§9). `rgb` for images that cannot be RGB is the error `rgb_not_possible`; any other value raises `ValueError`. Without a type the manifest records null. | | Outputs | `plane_histograms.parquet` and `experiment_design.csv` do not depend on the type: a plane of an RGB image is one row with channels C0, C1 and C2, as for any image. Changing the type on a later run reads no image again. | diff --git a/docs/user_guide.md b/docs/user_guide.md index 1d4ade7c..af6519f8 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1107,6 +1107,31 @@ notebook. A published description is never switched between modes by `describe`. output folder holds answers saved in the notebook (`morphobricks.draft.json`), the command publishes nothing (`R_DRAFT_EXISTS`): they are finished and published in the notebook. +Images need not be three folder levels deep: images directly in condition folders +(`exp1/condition_x/img.tif`) or in the experiment folder itself (one OME-Zarr mosaic, say) have +the repeat and acquisition `single`, as everywhere. The draft lists the open questions only +while some remain: `--accept-ids`, `--comparable` and `--confirmed-on` answer them, and the +output says so. + +**Colour scanner files whose header does not say colour.** Some scanners (and some public H&E +datasets) store red, green and blue as three interleaved samples per pixel under the TIFF +photometric interpretation *minisblack*. Fast mode then refuses them +(`R_FAST_LAYOUT_CONTRADICTION`, `image_type`), and the message names the fix. If the three +samples are red, green and blue in this order, say so with `--rgb-header-override`: + +```bash +morphobricks-preprocessing describe /data/he_cores --channels R,G,B --image-type rgb \ + --accept-ids --comparable --confirmed-on 2026-12-03 --rgb-header-override --publish +``` + +Without a folder the statement covers every acquisition; `--rgb-header-override tumour/rep1` +(repeatable, an acquisition folder relative to the experiment) covers only that one. It records +`rgb_header_override = true` on those acquisitions, exactly as the notebook's Image type card +does (see `R_IMAGE_TYPE_CONTRADICTS_HEADER` in §8); an image that is not three interleaved +samples is still refused (`R_RGB_OVERRIDE_NOT_THREE_SAMPLES`). The option needs `--image-type +rgb`, and it is a statement of a new fast-mode description only: a published description, or +the strict mode, records it in the notebook. + ### Stating pixel sizes (`calibrate`) Each image's pixel size (X and Y) and z-step (Z) come from its metadata. When the @@ -1193,6 +1218,24 @@ never converted: keep using your masks folder, and keep the copies out of it (`copy_folder_overlaps_masks`; give `--masks` if your runs' masks folder is not the one recorded in the default output folder). +**OME-Zarr copies (`--store ome-zarr`).** `convert EXPERIMENT --to FOLDER --axes ROLES --store +ome-zarr` writes every image that is read as an OME-Zarr image (OME-NGFF 0.4, named +`.ome.zarr`, so its position ID is unchanged), with the same plan, lock, conversion +record and refusals as the OME-TIFF copies; the notebook's **Also save a copy as OME-Zarr** and +Python's `convert_experiment(..., store="ome-zarr")` write the same copies. RGB colour TIFFs are +converted too (`--axes YXC`: their three samples become the copy's channel axis). OME-NGFF has +no field for colour, so the copies cannot say RGB themselves: describe them with +`--image-type rgb --channels R,G,B`, and `check` and `run` then suggest the image type `rgb` +from the published description (no `--image-type rgb` needed). Reading OME-Zarr copies needs the +`zarr` extra; writing them does not. `--project` writes OME-Zarr projections the same way. + +```bash +morphobricks-preprocessing convert /data/he --to /data/he_zarr --axes YXC --store ome-zarr +morphobricks-preprocessing describe /data/he_zarr --channels R,G,B --image-type rgb \ + --accept-ids --comparable --confirmed-on 2026-12-03 --publish +morphobricks-preprocessing run /data/he_zarr +``` + Pixel sizes follow the roles. An axis you give another role than its metadata gets no size in the copy: after a Y/X swap the copy has no X or Y pixel size (the metadata's X size belongs to the axis you call Y), unless the metadata give X and Y exactly the same size, @@ -1337,6 +1380,12 @@ morphobricks-preprocessing masks --output /data/exp1_MorphoBricks_Preprocessing describe steps. - `--masks` also checks each mask type against the masks folder (no folder there that differs only in upper/lower case). +- Masks that are not in a masks folder of their own, OME-Zarr label images (`.zarr/labels/`) + or `_.tif` beside the images, need no `--masks`: the command then prints the next + commands without it (`run EXPERIMENT --output FOLDER`, the experiment folder left out when a + run of the output folder records it). +- `check` reports a mask type the description does not declare exactly as `run` refuses it + (`R_MASK_TYPE_NOT_DECLARED`, naming the type), so you see it before the run. - In Python: `morphobricks_preprocessing.mask_declare.declare_masks(output, {"Cells": "instances"})`. ### Converting a mask (`convert-mask`) @@ -1614,8 +1663,8 @@ continues. | `partial_channel_coverage` | Warning | A biological repeat has a stain in only some of its imaging units (for example one technical repeat imaged an extra stain); the message counts imaging units (`rep1: PHASE in 1 of 2 imaging units`). The images are measured as acquired (the stain is blank where it was not acquired) and the coverage is in the manifest. Later analyses that pool the stain over the whole repeat refuse it (`A_SCOPE_INCOMPLETE`) unless you choose the imaging units that have it; that refusal counts images ("present in 2 of 4 images"). | | `R_MASK_CONTRADICTS_REPRESENTATION` | Error | The masks step found a file of a mask declared `binary` that is stored as floats, or holds, over all its planes together, a negative value or two or more different positive values (the message names the file and the values found, or its pixel type). A binary mask holds 0 and at most one positive value (an all-zero or all-foreground file is accepted), stored as integers or true/false. Declare the mask as `instances` in the description if every value is an object, or as `parent_labels` (grouped labels) if every value is one group, such as the mitochondria of one cell; or fix the file (save a float mask as integers). The file stays `not yet checked`, so an analysis that names the mask refuses it (`A_MASK_UNCHECKED`) without reading it. | | `R_UNIT_NOT_FOUND`, `R_UNIT_NOT_DECLARED`, `R_UNIT_NOT_HOMOGENEOUS`, `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER`, `R_MASK_TYPE_NOT_DECLARED` | Error | The published description and the folder or the image headers disagree (the message says where). Correct the description, publish it again and run again. | -| `R_IMAGE_TYPE_CONTRADICTS_HEADER` for colour scanner files, `R_RGB_OVERRIDE_NOT_THREE_SAMPLES`, `E_RGB_OVERRIDE_WITHOUT_RGB` | Error | Some scanners store colour (RGB) images with a header that does not say RGB (for example TIFF photometric *minisblack* with three samples per pixel). The acquisition declared `image_type = "rgb"` is then refused, and the message says so and names `rgb_header_override`. If the three samples are red, green and blue in this order, add `rgb_header_override = true` to that acquisition in `morphobricks.toml` (beside `image_type = "rgb"`; in the notebook, tick **Read these folders as colour (RGB) although their header does not say colour** on the Image type card of the Channels step) and publish again: the run then accepts the header and records the acquisition in the manifest as declared RGB with the header overridden (`image_type_header_overridden`, `header_photometric`). Every image whose header does not say RGB must have exactly three interleaved samples per pixel, else `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` names the image (reported before `R_UNIT_NOT_HOMOGENEOUS`); the key on an acquisition that is not declared `rgb` is `E_RGB_OVERRIDE_WITHOUT_RGB`. Images of the acquisition that differ only in colour interpretation (some *minisblack*, some RGB) are then one layout. Images whose header already says RGB, or whose format states no colour interpretation (OME-Zarr), do not use the key; the manifest records, per image, whether it was used (`rgb_header_override_images`). Adding, removing or changing the key reopens the "same way" confirmation of that replicate. Only headers are read, never pixels. | -| `R_FAST_LAYOUT_CONTRADICTION` | Error | The published description is in **fast mode** (it has a `channel_layout` table: "every imaging unit has the same channels in the same order", Spec ADR 0006) and some images of the acquisitions that follow it (`channels_from = "experiment"`) contradict that list. One message lists **every** contradicting image, with its FOV key (condition, repeat and acquisition folders, then the image name) and path, and every contradiction found in it: `image_type` (the header says colour where the list is not, or the reverse), `channel_count` (another number of channels), `header_order` (header names of the list in another order) or `header_names` (a header name that is no confirmed name of any channel of the list), each with its C index and what was expected and found. It is decided from the image headers only, before any pixel is read; nothing is reordered, dropped or guessed, and nothing was processed. Tag the acquisitions of these images on their own (`channels_from = "unit"`, confirmed per acquisition), publish again and run again. An image whose header gives no channel names (or an empty name) needs no evidence and follows the list; the manifest records each image of a fast acquisition in `fast_layout_images` (`header_verified` true only when every channel was confirmed by its header name). In such acquisitions this one code replaces `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER` and `R_UNIT_NOT_HOMOGENEOUS` (which stays for the other axes); `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` keeps its priority. An acquisition tagged on its own is checked as in a description without fast mode. Experiments with extra channels in some acquisitions are refused here: tag those acquisitions on their own. | +| `R_IMAGE_TYPE_CONTRADICTS_HEADER` for colour scanner files, `R_RGB_OVERRIDE_NOT_THREE_SAMPLES`, `E_RGB_OVERRIDE_WITHOUT_RGB` | Error | Some scanners store colour (RGB) images with a header that does not say RGB (for example TIFF photometric *minisblack* with three samples per pixel). The acquisition declared `image_type = "rgb"` is then refused, and the message says so and names `rgb_header_override`. If the three samples are red, green and blue in this order, add `rgb_header_override = true` to that acquisition in `morphobricks.toml` (beside `image_type = "rgb"`; in the notebook, tick **Read these folders as colour (RGB) although their header does not say colour** on the Image type card of the Channels step; on the command line, for a new fast-mode description, `describe ... --image-type rgb --channels R,G,B --rgb-header-override`, §5) and publish again: the run then accepts the header and records the acquisition in the manifest as declared RGB with the header overridden (`image_type_header_overridden`, `header_photometric`). Every image whose header does not say RGB must have exactly three interleaved samples per pixel, else `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` names the image (reported before `R_UNIT_NOT_HOMOGENEOUS`); the key on an acquisition that is not declared `rgb` is `E_RGB_OVERRIDE_WITHOUT_RGB`. Images of the acquisition that differ only in colour interpretation (some *minisblack*, some RGB) are then one layout. Images whose header already says RGB, or whose format states no colour interpretation (OME-Zarr), do not use the key; the manifest records, per image, whether it was used (`rgb_header_override_images`). Adding, removing or changing the key reopens the "same way" confirmation of that replicate. Only headers are read, never pixels. | +| `R_FAST_LAYOUT_CONTRADICTION` | Error | The published description is in **fast mode** (it has a `channel_layout` table: "every imaging unit has the same channels in the same order", Spec ADR 0006) and some images of the acquisitions that follow it (`channels_from = "experiment"`) contradict that list. One message lists **every** contradicting image, with its FOV key (condition, repeat and acquisition folders, then the image name) and path, and every contradiction found in it: `image_type` (the header says colour where the list is not, or the reverse), `channel_count` (another number of channels), `header_order` (header names of the list in another order) or `header_names` (a header name that is no confirmed name of any channel of the list), each with its C index and what was expected and found. It is decided from the image headers only, before any pixel is read; nothing is reordered, dropped or guessed, and nothing was processed. Tag the acquisitions of these images on their own (`channels_from = "unit"`, confirmed per acquisition), publish again and run again. When the contradiction is an `image_type` of colour scanner files whose header does not say colour (three interleaved samples), the message names the RGB header override instead: `describe ... --image-type rgb --channels R,G,B --rgb-header-override [FOLDER]` (§5), or the notebook's Image type card. An image whose header gives no channel names (or an empty name) needs no evidence and follows the list; the manifest records each image of a fast acquisition in `fast_layout_images` (`header_verified` true only when every channel was confirmed by its header name). In such acquisitions this one code replaces `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER` and `R_UNIT_NOT_HOMOGENEOUS` (which stays for the other axes); `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` keeps its priority. An acquisition tagged on its own is checked as in a description without fast mode. Experiments with extra channels in some acquisitions are refused here: tag those acquisitions on their own. | | `folder_and_id_changed` | Error | *Check and save* (and publication) found an ID changed in the same save as a folder change of the same entity: for example a repeat ID `Day1 -> DayX` while one of its folders was renamed or removed, a condition ID changed while its folder was renamed, or a removed folder's ID typed for the new folder. Neither change is guessed from the other, so the message names the entity, its saved ID and its folders. Undo the ID edit: put the saved ID back (the folder change then saves on its own). A removed folder's ID stays used and is not given to another folder (experiment-v1 4.9). Nothing was published. | | `R_DRAFT_CHANGED` | Error | Notebook: `morphobricks.draft.json` was changed since this notebook read or saved it (another notebook, or a program, saved its own answers in the same output folder). Nothing was saved or published, and the answers saved there are kept. Press **Check folder** in step 1 to read them, then give your change again. | | `R_DRAFT_EXISTS` | Error | Command line (`describe --publish`): the output folder holds `morphobricks.draft.json`, answers saved in the notebook that the command does not read. Nothing was published or written. Finish those answers and publish them in the notebook (step 1, **Check folder**, then **Check and save**), or, if they are not wanted, remove or archive that file yourself and run the command again. | diff --git a/src/morphobricks_preprocessing/cli.py b/src/morphobricks_preprocessing/cli.py index 46f2fe5b..4e1760d5 100644 --- a/src/morphobricks_preprocessing/cli.py +++ b/src/morphobricks_preprocessing/cli.py @@ -51,6 +51,7 @@ add_missing_as_singleton, add_run_arguments, command_preflight, + declared_type, description_refusal, missing_as_singleton, parse_size, @@ -61,11 +62,13 @@ ) from .cli_settings import add_settings_parser, settings_command from .cli_tissue_mask import add_tissue_mask_parser, tissue_mask_command +from .description_run_text import physical_issues from .discovery import default_output_folder from .image_type import review_image_type from .log_target import log_refusal, run_log_refusal from .mask_text import mask_summary from .masks import mask_axes_option +from .physical_check import undeclared_mask_types from .report import ( axis_check_summary, balance_summary, @@ -79,6 +82,9 @@ write_check_report, ) from .run.check_step import suggested_review +from .run.description_run import load_description +from .run.preflight import Preflight +from .validation import ValidationIssue __all__ = ["build_parser", "main", "parse_size"] @@ -285,6 +291,10 @@ def _check(args: argparse.Namespace) -> int: if pre.issues: print() print(format_issues(pre.issues)) + undeclared = undeclared_mask_issues(args, pre) + if undeclared: # as 'run' refuses them, with its words + print() + print(format_issues(undeclared)) axis_errors = () if review is not None: # The suggested roles are the header's own, so they never contradict it; 'run' @@ -306,7 +316,7 @@ def _check(args: argparse.Namespace) -> int: f"Suggested option for 'run': --axes {pre.suggested_mapping.roles_string}" f"{singleton} (axes in the files: {pre.suggested_mapping.axes})" ) - type_review = review_image_type(pre.metadata, review) + type_review = review_image_type(pre.metadata, review, declared=declared_type(args, pre)) print( f"Suggested image type: {type_review.suggested}, because {type_review.reason}. " "'run' uses it unless you give --image-type." @@ -314,10 +324,26 @@ def _check(args: argparse.Namespace) -> int: path, refusal = write_check_report(pre, args.output, review) print() print(format_issues([refusal]) if refusal else f"Report written to {path}" if path else "") - blocked = not pre.ok or axis_errors or refusal is not None + blocked = not pre.ok or axis_errors or undeclared or refusal is not None return 1 if blocked else 0 # every error printed exits with 1, as 'run' does +def undeclared_mask_issues(args: argparse.Namespace, pre: Preflight) -> list[ValidationIssue]: + """Return ``run``'s refusal of every mask type found that the description does not declare. + + ``check`` reads no pixel and confirms no axis role, so it does not run the description's + physical checks; the mask types are names only, so it reports them exactly as ``run`` + would refuse them (``R_MASK_TYPE_NOT_DECLARED``), OME-Zarr label images included. + """ + if pre.masks is None or not pre.masks.types: + return [] + output = Path(args.output) if args.output else default_output_folder(pre.discovery.root) + found, _ = load_description(output.resolve()) + if found is None: # an unreadable description is refused by 'run' with its own words + return [] + return physical_issues(undeclared_mask_types(found.description, pre.masks.types)) + + def _log_refusal(args: argparse.Namespace) -> str | None: """Return why ``--log`` may not be written for this command, or None.""" if args.command == "convert": diff --git a/src/morphobricks_preprocessing/cli_convert.py b/src/morphobricks_preprocessing/cli_convert.py index 347c6cbf..6a0259e5 100644 --- a/src/morphobricks_preprocessing/cli_convert.py +++ b/src/morphobricks_preprocessing/cli_convert.py @@ -8,6 +8,13 @@ folder of the runs on the originals (``--output``, by default the experiment's default one). The command is offered for any experiment. +``--store ome-zarr`` writes every image that is read as an OME-Zarr copy instead (OME-NGFF 0.4, +``.ome.zarr``, :mod:`.ome_zarr_copy`), exactly as +``convert_experiment(..., store="ome-zarr")`` and the notebook's *Also save a copy as +OME-Zarr*; RGB colour TIFFs included (their three samples are the copy's channel axis; OME-NGFF +states no colour interpretation, so the published description's ``rgb`` is what ``check`` and +``run`` follow). Reading the copies needs the ``zarr`` extra; writing them does not. + ``--project max|mean|sum`` (issue #176) writes every image as a recorded 2-D projection of its Z-stack instead (no default method; ``--z-range START:STOP`` for the whole experiment). The projected copies are a different source, so the next commands name a new output folder, @@ -26,6 +33,7 @@ from .conversion import ConversionResult, convert_experiment from .conversion_record import RECORD_FILENAME from .discovery import default_output_folder +from .ome_zarr_copy import OME_TIFF, OME_ZARR, STORES from .planes import DEFAULT_MEMORY_LIMIT from .projection import METHODS, Projection from .report import format_issues @@ -50,7 +58,8 @@ def add_convert_parser(commands: argparse._SubParsersAction) -> argparse.Argumen convert = commands.add_parser( "convert", help="save the images whose axes are wrong or not named as named-axis OME-TIFF copies " - "with your roles, in a new folder (the originals are only read)", + "with your roles (or every image as OME-Zarr, --store ome-zarr), in a new folder (the " + "originals are only read)", ) convert.add_argument("experiment", help="the experiment folder") convert.add_argument( @@ -93,6 +102,15 @@ def add_convert_parser(commands: argparse._SubParsersAction) -> argparse.Argumen help="remove the lock of an earlier conversion into --to that was stopped; give it " "only when you are sure no other conversion writes there", ) + convert.add_argument( + "--store", + choices=STORES, + default=OME_TIFF, + help="how the copies are written: ome-tiff (default; only the images whose axes are " + "wrong or not named, the others copied as they are) or ome-zarr (every image that is " + "read, as an OME-Zarr image .ome.zarr, OME-NGFF 0.4; RGB colour images " + "too). Reading OME-Zarr copies needs the zarr extra", + ) _add_folder_options(convert) _add_projection_options(convert) convert.add_argument("--log", metavar="FILE", help="write technical details to this file") @@ -188,17 +206,20 @@ def convert_command(args: argparse.Namespace) -> int: progress=print_progress, masks_folder=args.masks or recorded_masks_of(output), projection=None if args.project is None else Projection(args.project, args.z_range), + store=args.store, ) if result.issues: print(format_issues(result.issues)) print() if result.projection is not None: output, given = default_output_folder(Path(args.to).resolve()), True - print(conversion_text(result, output, given=given)) + print(conversion_text(result, output, given=given, store=args.store)) return 0 if result.written else 1 -def conversion_text(result: ConversionResult, output: Path, *, given: bool = True) -> str: +def conversion_text( + result: ConversionResult, output: Path, *, given: bool = True, store: str = OME_TIFF +) -> str: """Say what a conversion wrote and what to run next, in plain ASCII-safe words. Parameters @@ -210,22 +231,25 @@ def conversion_text(result: ConversionResult, output: Path, *, given: bool = Tru given False when ``output`` is the default one, not given with ``--output``: the text then says to give the folder of the runs on the originals if it is another one. + store + ``"ome-tiff"`` or ``"ome-zarr"``: the format the copies were written in. Returns ------- str """ dest = result.destination + fmt = "OME-Zarr" if store == OME_ZARR else "OME-TIFF" if not result.written: return f"No copies were written in {dest}: read the messages above." if result.projection is not None: - return projection_text(result, output) + return projection_text(result, output, store=store) # Cross-brick test F8: the next commands name the output folder of the user's runs, # given with --output; a default one may hold no run (the user then gives theirs). where = "" if given else f" (by default {output}; if your runs used another one, give it)" lines = [ f"Named-axis copies in {dest}:", - f" written as OME-TIFF with your roles: {plural(len(result.converted), 'image')}", + f" written as {fmt} with your roles: {plural(len(result.converted), 'image')}", f" copied as they are: {plural(len(result.copied), 'image')}", f" already there and unchanged: {plural(len(result.reused), 'image')}", f"Conversion record: {dest / RECORD_FILENAME} (SHA-256 {result.record_sha256})", @@ -239,7 +263,7 @@ def conversion_text(result: ConversionResult, output: Path, *, given: bool = Tru return "\n".join(lines) -def projection_text(result: ConversionResult, output: Path) -> str: +def projection_text(result: ConversionResult, output: Path, *, store: str = OME_TIFF) -> str: """Say what a projection wrote and what to run next (a new output folder, a new source). Parameters @@ -249,6 +273,8 @@ def projection_text(result: ConversionResult, output: Path) -> str: output The output folder for the runs on the projected copies: the projected tree is a different source, so its description starts a new lineage. + store + ``"ome-tiff"`` or ``"ome-zarr"``: the format the copies were written in. Returns ------- @@ -261,7 +287,8 @@ def projection_text(result: ConversionResult, output: Path) -> str: return "\n".join( [ f"Projected copies in {dest}:", - f" {projection.method} projections of {slices}, written as 2-D OME-TIFF: " + f" {projection.method} projections of {slices}, written as 2-D " + f"{'OME-Zarr' if store == OME_ZARR else 'OME-TIFF'}: " f"{plural(len(result.projected), 'image')}", f" copied as they are (excluded): {plural(len(result.copied), 'image')}", f" already there and unchanged: {plural(len(result.reused), 'image')}", diff --git a/src/morphobricks_preprocessing/cli_declare_masks.py b/src/morphobricks_preprocessing/cli_declare_masks.py index 729654ae..aa48352a 100644 --- a/src/morphobricks_preprocessing/cli_declare_masks.py +++ b/src/morphobricks_preprocessing/cli_declare_masks.py @@ -7,7 +7,10 @@ is no default: the command never guesses what a mask is. The ID is the mask type's folder name unless ``:ID`` is given (needed when the folder name is not a valid mask ID). ``--masks`` also checks each mask type against the masks folder. The command prints what it declared and the two -commands that follow (``run --masks``, then ``masks``). Exit status 1 for a refusal, with +commands that follow (``run``, then ``masks``): with ``--masks`` they name that folder; without +it they name none, because OME-Zarr label images and ``_.tif`` masks beside the +images are found without a masks folder, and say when to add one. The experiment folder is +named only when no run of the output folder records it. Exit status 1 for a refusal, with nothing written, else 0 (also when every mask type was declared as asked already). """ @@ -15,9 +18,17 @@ import argparse import shlex +from pathlib import Path from .description_rules import REPRESENTATIONS from .mask_declare import MaskDeclaration, MaskDeclarationRefused, declare_masks +from .run.reuse import recorded_experiment_root + +NO_MASKS_FOLDER = ( + "Add --masks FOLDER to both only when the masks are in a masks folder of their own: " + "OME-Zarr label images, and masks named _.tif beside their images, are found " + "without it." +) def add_declare_masks_parser(commands: argparse._SubParsersAction) -> argparse.ArgumentParser: @@ -90,9 +101,29 @@ def declare_masks_command(args: argparse.Namespace) -> int: print("Every mask type is declared as asked already; nothing was written.") else: print(f"Declared in {done.publication.path}: {', '.join(done.added)}.") - output = shlex.quote(str(args.output)) - masks = shlex.quote(str(args.masks)) if args.masks else "MASKS" - print("Next, run preprocessing with the masks folder, then describe the masks:") - print(f" morphobricks-preprocessing run --output {output} --masks {masks}") - print(f" morphobricks-preprocessing masks --output {output} --masks {masks}") + for line in next_commands(args.output, args.masks): + print(line) return 0 + + +def next_commands(output: str, masks: str | None) -> list[str]: + """Return the lines naming the commands that follow a declaration. + + ``masks`` is the masks folder given, or None: the masks may then be OME-Zarr label images + or masks beside the images, which ``run`` finds without ``--masks``, so no placeholder + folder is named. The experiment folder is named (``EXPERIMENT``) unless a run of the + output folder records it. + """ + recorded, _ = recorded_experiment_root(Path(output).resolve()) + target = ("" if recorded is not None else "EXPERIMENT ") + f"--output {shlex.quote(output)}" + if masks is not None: + option = f" --masks {shlex.quote(masks)}" + lines = ["Next, run preprocessing with the masks folder, then describe the masks:"] + else: + option = "" + lines = ["Next, run preprocessing again, then describe the masks:"] + lines += [ + f" morphobricks-preprocessing run {target}{option}", + f" morphobricks-preprocessing masks {target}{option}", + ] + return lines if masks is not None else [*lines, NO_MASKS_FOLDER] diff --git a/src/morphobricks_preprocessing/cli_describe.py b/src/morphobricks_preprocessing/cli_describe.py index 5c7765be..e26d3f17 100644 --- a/src/morphobricks_preprocessing/cli_describe.py +++ b/src/morphobricks_preprocessing/cli_describe.py @@ -30,7 +30,10 @@ ``--comparable`` and ``--confirmed-on``, every answer is the user's, stated in the command (:mod:`.fast_answers`), and ``--publish`` publishes a fast-mode file in one command after every image's header was checked against the list (a contradiction lists every image, -``R_FAST_LAYOUT_CONTRADICTION``, and nothing is written). ``--strict`` keeps the per-unit +``R_FAST_LAYOUT_CONTRADICTION``, and nothing is written). ``--rgb-header-override [FOLDER]`` +states that colour scanner TIFFs whose header does not say colour are R, G and B (recorded as +``rgb_header_override = true`` on those units, as the notebook records it). The open questions +are listed only while the options leave some open. ``--strict`` keeps the per-unit mode, whose per-acquisition answers are given in the notebook. A published description is never switched between modes here. @@ -57,7 +60,7 @@ from .description_run_text import physical_issues from .discovery import DiscoveryResult, default_output_folder, discover_experiment from .draft import Draft, DraftError, draft_from_discovery -from .draft_answers import DraftAnswers, description_from_draft +from .draft_answers import DraftAnswers, description_from_draft, valid_day from .draft_ids import IdKind, id_problems from .fast_answers import fast_answers, tagged_unit from .metadata import inspect_images @@ -76,6 +79,11 @@ "--comparable, --confirmed-on and --publish; --strict tags each acquisition on its own in " "the notebook." ) +OVERRIDE_ONLY_FAST = ( + "--rgb-header-override is a statement of a new fast-mode description (with --channels " + "R,G,B --image-type rgb); a published description, or the strict mode, records it in the " + "notebook (Channels, Image type). Nothing was written." +) QUESTION_TEXT = { "id_pending": "choose the ID of {subject} (accept the proposal or type another)", "repeat_not_confirmed": ( @@ -144,6 +152,19 @@ def add_describe_parser(commands: argparse._SubParsersAction) -> argparse.Argume "its own (in the notebook). Default: fast mode, one channel list for the experiment " "(Spec ADR 0006)", ) + _add_fast_options(describe) + describe.add_argument( + "--publish", + action="store_true", + help="publish the description only when no question is open and every decision is " + "confirmed; otherwise exit with status 1 and list what is missing. Nothing is " + "confirmed for you", + ) + return describe + + +def _add_fast_options(describe: argparse.ArgumentParser) -> None: + """Add the fast-mode statements of ``describe`` (Spec ADR 0006, :mod:`.fast_answers`).""" describe.add_argument( "--channels", metavar="ID,ID,...", @@ -171,13 +192,19 @@ def add_describe_parser(commands: argparse._SubParsersAction) -> argparse.Argume help="fast mode: the day of your statements (never read from the clock)", ) describe.add_argument( - "--publish", - action="store_true", - help="publish the description only when no question is open and every decision is " - "confirmed; otherwise exit with status 1 and list what is missing. Nothing is " - "confirmed for you", + "--rgb-header-override", + action="append", + nargs="?", + const=True, + default=[], + metavar="FOLDER", + help="fast mode, with --image-type rgb: the images of this acquisition folder (relative " + "to the experiment, for example CTRL/rep1; repeatable; without a folder: every " + "acquisition) store R, G and B as three interleaved samples per pixel although their " + "TIFF header does not say colour. Records rgb_header_override = true on those units, " + "as the notebook's Image type card does; an image that is not three interleaved " + "samples is still refused", ) - return describe def describe_command(args: argparse.Namespace) -> int: @@ -202,11 +229,15 @@ def describe_command(args: argparse.Namespace) -> int: lines, blockers = _published(found.description, discovery, excluded, output) else: draft = draft_from_discovery(discovery, excluded) - lines, blockers = draft_lines(draft, root), draft_blockers(draft) if not args.strict and args.channels is not None: + lines = draft_lines(draft, root, questions=False) return describe_fast(args, draft, discovery, excluded, output, lines) + lines, blockers = draft_lines(draft, root), draft_blockers(draft) if not args.strict: lines.append(FAST_HINT) + if args.rgb_header_override: + print(OVERRIDE_ONLY_FAST) + return 1 print("\n".join(lines)) if not args.publish: return 0 @@ -245,12 +276,14 @@ def describe_fast( images = [image for image in discovery.images if image not in excluded] inspected = inspect_images(discovery.root, images) headers = inspected.files + units = _image_units(discovery) tagged = next( - (m for m in headers if key is not None and _unit_of(m.relative_path) == key), None + (m for m in headers if key is not None and units.get(m.relative_path) == key), None ) names = () if tagged is None else tuple(tagged.raw_channel_names) lines = [ *lines, + *_fast_question_lines(draft, args), "", "Fast mode (the default; --strict for the per-unit mode): one channel list for the " "experiment, the order of the tagged unit " @@ -261,6 +294,7 @@ def describe_fast( return 0 print() channels = [c for c in (args.channels or "").split(",") if c] + override, unknown = override_units(args.rgb_header_override, discovery, draft) answers, blockers = fast_answers( draft, channels, @@ -269,7 +303,9 @@ def describe_fast( accept_ids=args.accept_ids, comparable=args.comparable, confirmed_on=args.confirmed_on, + rgb_override=override, ) + blockers += unknown if not channels: blockers.insert(0, "give the tagged unit's channel IDs in order (--channels)") if args.image_type is None: @@ -288,10 +324,40 @@ def describe_fast( return _publish_fast(draft, answers, discovery, headers, output) -def _unit_of(path: str) -> tuple[str, str, str]: - """Return the unit key of an image path (condition, repeat, technical or ``single``).""" - parts = path.split("/")[:-1] - return (parts[0], parts[1], parts[2] if len(parts) > 2 else "single") +def override_units( + given: list[str | bool], discovery: DiscoveryResult, draft: Draft +) -> tuple[list[tuple[str, str, str]], list[str]]: + """Return the units ``--rgb-header-override`` names, and every folder it names in vain. + + ``True`` (the option without a folder) names every imaging unit of the draft (an + acquisition folder whose images are all excluded is none); a folder is an acquisition + (leaf) folder relative to the experiment, with ``/`` (or Windows) separators. + """ + leaves = {leaf.relative_path: leaf.labels for leaf in discovery.leaves} + if any(value is True for value in given): + rows = draft.unit_rows() + return sorted({(r.condition, r.biological_repeat, r.technical_repeat) for r in rows}), [] + found, unknown = set(), [] + for value in given: + folder = str(value).replace("\\", "/").strip("/") or "." + if folder in leaves: + found.add(leaves[folder]) + else: + unknown.append( + f"--rgb-header-override {value}: not an acquisition folder of this experiment " + f"(acquisition folders: {', '.join(sorted(leaves))})" + ) + return sorted(found), unknown + + +def _image_units(discovery: DiscoveryResult) -> dict[str, tuple[str, str, str]]: + """Return each image's unit key (condition, repeat, technical) from its leaf folder. + + The labels are discovery's, so a branch that stops early (``condition/image.tif``, or an + image in the experiment folder itself) has ``single`` for its missing levels, as in the + draft; the path is never split into levels here. + """ + return {image: leaf.labels for leaf in discovery.leaves for image in leaf.images} def _publish_fast( @@ -342,8 +408,44 @@ def _proposal(kind: IdKind, folder: str, slot_proposed: str | None) -> str: return f"no ID can be proposed ({why or 'in use'}): you name it" -def draft_lines(draft: Draft, root: Path) -> list[str]: - """Return the plain-language report of a draft.""" +def _fast_question_lines(draft: Draft, args: argparse.Namespace) -> list[str]: + """Return the draft's questions the fast-mode options leave open, or say none is left. + + ``--accept-ids`` answers every ID question (a folder with no proposal is named when + publishing), ``--comparable`` with a valid ``--confirmed-on`` every repeat question. The + questions are listed only while some remain, so a command that answers them all never + says that they are answered in the notebook. + """ + dated = args.confirmed_on is not None and valid_day(args.confirmed_on) + questions = draft.open_questions() + left = [ + q + for q in questions + if not (args.accept_ids if q.code == "id_pending" else args.comparable and dated) + ] + if not questions: + return ["", "No question is open."] + if not left: + return [ + "", + f"The draft's {len(questions)} open questions are answered by your options " + "(--accept-ids, --comparable, --confirmed-on).", + ] + out = [ + "", + f"{len(left)} open questions (answer them with --accept-ids, --comparable and " + "--confirmed-on YYYY-MM-DD, or in the notebook):", + ] + out += [f" - {QUESTION_TEXT[q.code].format(subject=q.subject)}" for q in left] + return out + + +def draft_lines(draft: Draft, root: Path, *, questions: bool = True) -> list[str]: + """Return the plain-language report of a draft. + + Its open questions are listed unless ``questions`` is False: fast mode says itself which + of them its options leave open. + """ out = [ f"Draft experiment description of {root}", "Drawn from the folders alone. Nothing here is confirmed: IDs below are proposals.", @@ -369,7 +471,8 @@ def draft_lines(draft: Draft, root: Path) -> list[str]: if draft.references: out += ["", "References (condition is compared against)"] out += [f" {c} -> {r}" for c, r in sorted(draft.references.items())] - out += _question_lines(draft) + if questions: + out += _question_lines(draft) return out diff --git a/src/morphobricks_preprocessing/cli_run.py b/src/morphobricks_preprocessing/cli_run.py index 4292e5f6..16b2bff1 100644 --- a/src/morphobricks_preprocessing/cli_run.py +++ b/src/morphobricks_preprocessing/cli_run.py @@ -47,6 +47,7 @@ ) from .required_description import description_required_issue, is_published from .run import MODES, RESTART, Preflight, RunMode, preflight, run_experiment +from .run.description_run import published_image_type from .run.recorded import usable from .run.reuse import read_previous, recorded_experiment_root from .validation import ValidationIssue, error @@ -571,7 +572,7 @@ def _print_inputs( if reused: print(reused) print() - type_review = review_image_type(pre.metadata, review) + type_review = review_image_type(pre.metadata, review, declared=declared_type(args, pre)) given = args.image_type or (recorded.image_type if recorded else None) image_type = given or type_review.suggested print(f"Image type: {image_type}") @@ -580,6 +581,11 @@ def _print_inputs( return image_type +def declared_type(args: argparse.Namespace, pre: Preflight) -> str | None: + """Return ``"rgb"`` when the published description declares every acquisition ``rgb``.""" + return published_image_type(Path(args.output or default_output_folder(pre.discovery.root))) + + def _image_type_note(review: ImageTypeReview, given: str | None) -> str: """Say where the image type comes from and how to choose the other one.""" if given is not None: diff --git a/src/morphobricks_preprocessing/description_run_text.py b/src/morphobricks_preprocessing/description_run_text.py index f60555d5..07e64944 100644 --- a/src/morphobricks_preprocessing/description_run_text.py +++ b/src/morphobricks_preprocessing/description_run_text.py @@ -34,6 +34,7 @@ PhysicalIssue, UnitKey, ) +from .physical_unit import OVERRIDE_HOW from .type_names import type_name from .validation import ValidationIssue, error, warning @@ -45,8 +46,9 @@ UNIT_NOT_DECLARED: "Add the acquisition to the description, or exclude its images.", MASK_TYPE_NOT_DECLARED: ( "Declare the mask type in the description (the notebook's describe steps, or " - "morphobricks-preprocessing declare-masks --output FOLDER --type TYPE=instances), or " - "remove its files." + "morphobricks-preprocessing declare-masks --output FOLDER --type " + "TYPE=REPRESENTATION, where REPRESENTATION is what the mask is: instances, binary or " + "parent_labels), or remove its files." ), } @@ -69,7 +71,10 @@ def _what(issue: PhysicalIssue) -> str: if issue.code == UNIT_NOT_DECLARED: return f"The experiment has images in {where}, which the description does not list." if issue.code == MASK_TYPE_NOT_DECLARED: - return f"The masks folder has masks of type {issue.detail!r} that are not declared." + return ( + f"Masks of type {issue.detail!r} were found (in the masks folder, beside the " + "images or as OME-Zarr label images), but are not declared in the description." + ) reasons = { UNIT_NOT_HOMOGENEOUS: "Images of one acquisition differ in their layout", CHANNEL_COUNT_MISMATCH: "An image has another number of channels than described", @@ -87,7 +92,10 @@ def _what(issue: PhysicalIssue) -> str: def physical_issue(issue: PhysicalIssue) -> ValidationIssue: """Return one physical check refusal as an error naming its code, unit and image.""" paths = () if issue.path is None else (issue.path,) - return error(issue.code, _what(issue), paths, _ACTIONS.get(issue.code, FIX)) + action = _ACTIONS.get(issue.code, FIX) + if issue.code == MASK_TYPE_NOT_DECLARED: # the type found, never a guessed representation + action = action.replace("TYPE=REPRESENTATION", f"{issue.detail}=REPRESENTATION") + return error(issue.code, _what(issue), paths, action) def fast_layout_issue(issues: Iterable[PhysicalIssue]) -> ValidationIssue: @@ -104,6 +112,17 @@ def fast_layout_issue(issues: Iterable[PhysicalIssue]) -> ValidationIssue: } units = sorted({unit_text(i.unit) for i in issues if i.code == FAST_LAYOUT_CONTRADICTION}) action = f"{FAST_FIX} Units: " + "; ".join(units) + "." + if any( + "rgb_header_override" in item.found + for issue in issues + if issue.code == FAST_LAYOUT_CONTRADICTION + for item in issue.contradictions + ): + action += ( + " Images that store R, G and B as three interleaved samples under a header that " + "does not say colour need no own tags: declare the RGB header override instead " + f"({OVERRIDE_HOW})." + ) paths = [path for _, path in listed] return error(FAST_LAYOUT_CONTRADICTION, contradiction_message(listed), paths, action) diff --git a/src/morphobricks_preprocessing/fast_answers.py b/src/morphobricks_preprocessing/fast_answers.py index f5d24632..f5681123 100644 --- a/src/morphobricks_preprocessing/fast_answers.py +++ b/src/morphobricks_preprocessing/fast_answers.py @@ -11,7 +11,13 @@ - ``--image-type`` is the list's image type, never inferred; - ``--accept-ids`` accepts every proposed ID (a folder with no proposal stops publication); - ``--comparable`` is the N35 answer for every biological repeat; -- ``--confirmed-on`` is the day of those statements, never the clock's. +- ``--confirmed-on`` is the day of those statements, never the clock's; +- ``--rgb-header-override`` (with ``--image-type rgb`` only) is the user's statement that the + named units' images, whose TIFF header does not say colour, store R, G and B as three + interleaved samples per pixel: the unit records ``rgb_header_override = true`` + (experiment-v1 4.4b, RH1), exactly as the notebook's Image type card records it. The check + at publication still refuses an image that is not three interleaved samples + (``R_RGB_OVERRIDE_NOT_THREE_SAMPLES``). Every unit is drafted with ``channels_from = "experiment"`` and the list materialised; a unit that contradicts the list is refused at publication with ``R_FAST_LAYOUT_CONTRADICTION``, never @@ -20,16 +26,18 @@ from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Collection, Sequence from .draft import Draft from .draft_answers import ( CHANNELS, + EXPERIMENT, ChannelAnswer, ConditionAnswer, DraftAnswers, LayoutAnswer, RepeatAnswer, + UnitAnswer, UnitKey, valid_day, ) @@ -79,11 +87,14 @@ def fast_answers( accept_ids: bool, comparable: bool, confirmed_on: str | None, + rgb_override: Collection[UnitKey] = (), ) -> tuple[DraftAnswers | None, list[str]]: """Return the fast-mode answers the command states, or None with everything missing. ``header_names`` are the tagged unit's header channel names as read (None or ``""`` where the header names none); a non-empty one is confirmed for the channel at its index. + ``rgb_override`` are the units the user declares ``rgb_header_override = true`` on (a + colour list only; every key must be a unit of the draft). """ blockers = [] if not accept_ids: @@ -97,6 +108,17 @@ def fast_answers( blockers.append("give the day of your statements as YYYY-MM-DD (--confirmed-on)") if image_type == "rgb" and tuple(channels) != RGB_LIST: blockers.append("a colour (RGB) list is exactly R,G,B (--channels R,G,B)") + if rgb_override and image_type != "rgb": + blockers.append( + "--rgb-header-override is for a colour (RGB) list only (--image-type rgb " + "--channels R,G,B)" + ) + known = {(r.condition, r.biological_repeat, r.technical_repeat) for r in draft.unit_rows()} + blockers += [ + f"--rgb-header-override names {' / '.join(key)}, which is not an imaging unit of " + "this experiment" + for key in sorted(set(rgb_override) - known) + ] if len(set(channels)) != len(channels) or not channels: blockers.append("--channels lists each channel ID once") if len(header_names) not in (0, len(channels)): @@ -121,6 +143,10 @@ def fast_answers( conditions=conditions, technical_repeats=technical, repeats={k: RepeatAnswer(v.id, day) for k, v in repeats.items()}, + units={ + key: UnitAnswer((), "rgb", channels_from=EXPERIMENT, rgb_header_override=True) + for key in sorted(set(rgb_override)) + }, channels=declared, channel_layout=LayoutAnswer( tuple(channels), "rgb" if image_type == "rgb" else CHANNELS, day diff --git a/src/morphobricks_preprocessing/image_type.py b/src/morphobricks_preprocessing/image_type.py index 9fe9fb74..a21292d4 100644 --- a/src/morphobricks_preprocessing/image_type.py +++ b/src/morphobricks_preprocessing/image_type.py @@ -10,6 +10,12 @@ integer pixel type; the rule is the normalization brick's :func:`~morphobricks_normalization.rgb.check_rgb`. +A described run (every run since v0.5.1) also passes the published description's answer: +when every acquisition is declared ``rgb``, ``rgb`` is suggested from it (when RGB is +possible), because a format that states no colour interpretation (an OME-Zarr image, also one +written by ``convert --store ome-zarr`` from RGB TIFFs: OME-NGFF 0.4 has no field for it) or a +TIFF whose header does not say colour under the RGB header override cannot suggest it. + The histograms are the same for both types, so the type changes no row of ``plane_histograms.parquet``; it is recorded in the run manifest (contract §9). """ @@ -17,6 +23,7 @@ from __future__ import annotations from dataclasses import dataclass +from typing import TYPE_CHECKING from morphobricks_normalization.rgb import check_rgb @@ -25,6 +32,9 @@ from .metadata import MetadataReport from .validation import ValidationIssue, error +if TYPE_CHECKING: + from .description import Description + FLUORESCENCE = "fluorescence" RGB = "rgb" IMAGE_TYPES = (FLUORESCENCE, RGB) @@ -77,7 +87,26 @@ def check_image_type(image_type: str) -> str: return image_type -def review_image_type(metadata: MetadataReport, review: AxisReview) -> ImageTypeReview: +def declared_image_type(description: Description | None) -> str | None: + """Return ``"rgb"`` when every acquisition of the description is declared ``rgb``. + + None without a description, without an acquisition, or when any acquisition is an + ordinary channel image: only the user's own declaration of every unit is taken. + """ + if description is None: + return None + types = { + unit.image_type + for repeat in description.repeats.values() + for member in repeat.members.values() + for unit in member.technical_repeats.values() + } + return RGB if types == {RGB} else None + + +def review_image_type( + metadata: MetadataReport, review: AxisReview, *, declared: str | None = None +) -> ImageTypeReview: """Suggest the image type and say whether RGB is possible, from the headers alone. Parameters @@ -86,12 +115,15 @@ def review_image_type(metadata: MetadataReport, review: AxisReview) -> ImageType The image headers. review The confirmed axis roles, resolved for every image. + declared + ``"rgb"`` when the published description declares every acquisition ``rgb`` + (:func:`declared_image_type`), else None. Returns ------- ImageTypeReview ``rgb`` is suggested only when the images are RGB colour on the channel - axis and can be of type ``rgb``. + axis, or the description declares them ``rgb``, and they can be of type ``rgb``. """ headers = {f.relative_path: f for f in metadata.files} files = [(headers[rel], mapping) for rel, mapping in sorted(review.file_mappings.items())] @@ -109,6 +141,15 @@ def review_image_type(metadata: MetadataReport, review: AxisReview) -> ImageType True, count, ) + if declared == RGB and problem is None: + return ImageTypeReview( + RGB, + "the published description declares every acquisition rgb (colour), and the " + "images have three channels of a whole-number type (not every header says " + "colour; an OME-Zarr image states no colour interpretation)", + from_samples, + count, + ) if from_samples: reason = "the images are stored as RGB colour, but cannot be of type RGB" elif any(f.rgb_samples for f, _ in files): diff --git a/src/morphobricks_preprocessing/physical_check.py b/src/morphobricks_preprocessing/physical_check.py index 8b3bc622..4ece9ff6 100644 --- a/src/morphobricks_preprocessing/physical_check.py +++ b/src/morphobricks_preprocessing/physical_check.py @@ -282,6 +282,22 @@ def _check_unit( return issues, None if issues else reference, verified, unchecked, unnamed +def undeclared_mask_types( + description: Description, mask_types: Iterable[str] +) -> list[PhysicalIssue]: + """Return ``R_MASK_TYPE_NOT_DECLARED`` for each mask type found that is not declared. + + The one rule of ``run`` (through :func:`check_physical`) and ``check``: a mask type found + (a masks folder's subfolder, ``_.tif`` beside the images, or an OME-Zarr + label image) must be the ``source_type`` of a declared mask. Only names are compared. + """ + known = {mask.source_type for mask in description.masks.values()} + return [ + PhysicalIssue(MASK_TYPE_NOT_DECLARED, None, detail=name) + for name in sorted(set(mask_types) - known) + ] + + def check_physical( description: Description, discovery: DiscoveryResult, @@ -359,11 +375,7 @@ def check_physical( if layout is not None: layouts[key] = layout if mask_types is not None: - known = {mask.source_type for mask in description.masks.values()} - issues += [ - PhysicalIssue(MASK_TYPE_NOT_DECLARED, None, detail=name) - for name in sorted(set(mask_types) - known) - ] + issues += undeclared_mask_types(description, mask_types) return PhysicalReport( tuple(issues), MappingProxyType(layouts), diff --git a/src/morphobricks_preprocessing/physical_unit.py b/src/morphobricks_preprocessing/physical_unit.py index 2b5626c6..70df0f0d 100644 --- a/src/morphobricks_preprocessing/physical_unit.py +++ b/src/morphobricks_preprocessing/physical_unit.py @@ -96,6 +96,13 @@ def layout_of( return Layout(count, tuple(meta.raw_channel_names), meta.rgb_samples or rgb, axes) +OVERRIDE_HOW = ( + "describe EXPERIMENT ... --image-type rgb --channels R,G,B --rgb-header-override FOLDER, " + "or Image type in the notebook" +) +"""How the user declares the RGB header override (the command line's option, the notebook).""" + + def type_issue(declared: Unit, layout: Layout, meta: TiffMetadata) -> tuple[str, str] | None: """Return the code and text of one image whose header contradicts its unit, else None. @@ -123,7 +130,8 @@ def type_issue(declared: Unit, layout: Layout, meta: TiffMetadata) -> tuple[str, what += ( f" (photometric {meta.photometric or 'not stated'}) but stores " f"{OVERRIDE_SAMPLES} interleaved samples per pixel: if they are R, G and B in this " - "order, declare rgb_header_override = true on this unit (experiment-v1 4.4b)" + "order, declare rgb_header_override = true on this unit (experiment-v1 4.4b: " + f"{OVERRIDE_HOW})" ) return IMAGE_TYPE_CONTRADICTS_HEADER, what diff --git a/src/morphobricks_preprocessing/run/description_run.py b/src/morphobricks_preprocessing/run/description_run.py index 6ddfe43f..4f5291f2 100644 --- a/src/morphobricks_preprocessing/run/description_run.py +++ b/src/morphobricks_preprocessing/run/description_run.py @@ -37,6 +37,7 @@ ) from ..design import DesignTable from ..design_derive import derive_design +from ..image_type import declared_image_type from ..lab_links import LabLinks, repeat_code_issues from ..mask_representation import NOT_CHECKED, file_status, read_checked from ..physical_check import PhysicalReport, check_physical @@ -172,6 +173,17 @@ def check_description( return replace(found, physical=report), [*units, *physical_issues(report.issues)] +def published_image_type(output: Path) -> str | None: + """Return ``"rgb"`` when the output folder's description declares every acquisition ``rgb``. + + The suggestion of ``check`` and ``run`` then follows the user's declaration where the + headers cannot say colour (OME-Zarr images, :func:`..image_type.declared_image_type`). + None without a readable published description. + """ + found, _ = load_description(output.resolve()) + return declared_image_type(None if found is None else found.description) + + GLOBAL_UNIT_CODES = frozenset({"mixed_dtypes", "inconsistent_dimensions"}) """The folder checks that compare pixel types and dimensions across the whole experiment. diff --git a/tests/test_cli_usability.py b/tests/test_cli_usability.py new file mode 100644 index 00000000..7845e6b4 --- /dev/null +++ b/tests/test_cli_usability.py @@ -0,0 +1,277 @@ +"""Command-line gaps a new user met before the next brick (v0.10.1). + +1. Fast ``describe`` with images fewer than three folder levels deep (``condition/img.tif``, + an image in the experiment folder itself). +2. ``describe --rgb-header-override``: RGB TIFFs whose header says ``minisblack``. +3. ``check`` reports an undeclared mask type as ``run`` refuses it; ``declare-masks`` names + the right next commands. +4. Fast ``describe`` lists open questions only while some remain. +5. ``check`` and ``run`` suggest ``rgb`` for RGB OME-Zarr copies the description declares rgb. +6. ``convert --store ome-zarr``. +""" + +from __future__ import annotations + +import numpy as np +import pytest +import tifffile + +from morphobricks_preprocessing.cli import main +from morphobricks_preprocessing.description import description_from_bytes +from morphobricks_preprocessing.description_file import DESCRIPTION_FILENAME + +DAY = "2026-12-03" +YES = ["--accept-ids", "--comparable", "--confirmed-on", DAY] +CHANNELS = ["--channels", "DNA,ACTIN", "--image-type", "channels", *YES] +COLOUR = ["--channels", "R,G,B", "--image-type", "rgb", *YES] + + +def _ome(path, names=("DAPI", "Phalloidin")): + path.parent.mkdir(parents=True, exist_ok=True) + tifffile.imwrite( + path, + np.zeros((len(names), 8, 8), np.uint8), + ome=True, + photometric="minisblack", + metadata={"axes": "CYX", "Channel": {"Name": list(names)}}, + ) + + +def _scanner(path, colour="minisblack"): + """Write an H&E-like TIFF: R, G and B interleaved, the header saying ``colour``.""" + path.parent.mkdir(parents=True, exist_ok=True) + pixels = np.random.default_rng(0).integers(0, 255, (8, 8, 3), dtype=np.uint8) + tifffile.imwrite( + path, pixels, photometric=colour, planarconfig="contig", metadata={"axes": "YXS"} + ) + + +def _units(out): + published = description_from_bytes((out / DESCRIPTION_FILENAME).read_bytes()) + return { + (cid, rid, tid): unit + for rid, repeat in published.repeats.items() + for cid, member in repeat.members.items() + for tid, unit in member.technical_repeats.items() + } + + +# --- 1. Images fewer than three levels deep ----------------------------------------------- + + +def test_fast_describe_publishes_images_directly_in_condition_folders(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + for condition in ("condition_x", "condition_y"): + _ome(root / condition / "img.ome.tif") + assert main(["describe", str(root), "--output", str(out), *CHANNELS, "--publish"]) == 0 + text = capsys.readouterr().out + assert "tagged unit condition_x / single / single, header names ['DAPI', 'Phalloidin']" in ( + text + ) + published = description_from_bytes((out / DESCRIPTION_FILENAME).read_bytes()) + assert published.channels["DNA"].header_names == ("DAPI",) # the tagged image was found + assert set(_units(out)) == { + ("condition_x", "single", "single"), + ("condition_y", "single", "single"), + } + + +def test_fast_describe_publishes_one_ome_zarr_in_the_experiment_folder(tmp_path, capsys): + from zarr_tree import write_ngff + + root, out = tmp_path / "exp", tmp_path / "out" + write_ngff(root / "mosaic.zarr", np.zeros((2, 8, 8), np.uint8), axes="cyx") + assert main(["describe", str(root), "--output", str(out), *CHANNELS, "--publish"]) == 0 + assert "tagged unit single / single / single" in capsys.readouterr().out + assert set(_units(out)) == {("single", "single", "single")} + + +# --- 2. The RGB header override ------------------------------------------------------------- + + +def _scanner_tree(root): + for path in ("tumour/core1.tif", "tumour/core2.tif", "normal/core3.tif"): + _scanner(root / path) + return root + + +def test_a_minisblack_rgb_contradiction_names_the_describe_option(tmp_path, capsys): + root, out = _scanner_tree(tmp_path / "exp"), tmp_path / "out" + assert main(["describe", str(root), "--output", str(out), *COLOUR, "--publish"]) == 1 + text = capsys.readouterr().out + assert "R_FAST_LAYOUT_CONTRADICTION" in text or "contradict the experiment" in text + assert "--rgb-header-override FOLDER" in text + assert "declare the RGB header override instead" in text # in the suggested action + assert not (out / DESCRIPTION_FILENAME).exists() + + +def test_rgb_header_override_for_every_unit_is_recorded_as_the_notebook_records_it(tmp_path): + root, out = _scanner_tree(tmp_path / "exp"), tmp_path / "out" + command = ["describe", str(root), "--output", str(out), *COLOUR, "--publish"] + assert main([*command, "--rgb-header-override"]) == 0 + units = _units(out) + assert {u.rgb_header_override for u in units.values()} == {True} + assert {(u.image_type, u.channels_from) for u in units.values()} == {("rgb", "experiment")} + data = (out / DESCRIPTION_FILENAME).read_text() + assert data.count("rgb_header_override = true") == 2 + + +def test_rgb_header_override_per_folder_names_only_that_unit(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + _scanner(root / "tumour" / "core1.tif") + _scanner(root / "normal" / "core3.tif", colour="rgb") # its header says colour + command = ["describe", str(root), "--output", str(out), *COLOUR, "--publish"] + assert main([*command, "--rgb-header-override", "tumour/"]) == 0 + units = _units(out) + assert units["tumour", "single", "single"].rgb_header_override is True + assert units["normal", "single", "single"].rgb_header_override is None + + +def test_rgb_header_override_refuses_an_unknown_folder_and_a_channel_list(tmp_path, capsys): + root, out = _scanner_tree(tmp_path / "exp"), tmp_path / "out" + command = ["describe", str(root), "--output", str(out), *YES, "--publish"] + colour = ["--channels", "R,G,B", "--image-type", "rgb"] + assert main([*command, *colour, "--rgb-header-override", "tumor"]) == 1 + text = capsys.readouterr().out + assert "--rgb-header-override tumor: not an acquisition folder" in text + assert "normal, tumour" in text + channels = ["--channels", "A,B,C", "--image-type", "channels"] + assert main([*command, *channels, "--rgb-header-override"]) == 1 + assert "for a colour (RGB) list only" in capsys.readouterr().out + assert not out.exists() + + +def test_rgb_header_override_outside_a_new_fast_description_is_refused(tmp_path, capsys): + root, out = _scanner_tree(tmp_path / "exp"), tmp_path / "out" + assert main(["describe", str(root), "--output", str(out), "--rgb-header-override"]) == 1 + assert "statement of a new fast-mode description" in capsys.readouterr().out + assert not out.exists() + + +# --- 3. Masks: check as run, declare-masks' next commands ----------------------------------- + + +def _labelled(tmp_path): + from zarr_tree import write_labels, write_ngff + + root, out = tmp_path / "exp", tmp_path / "out" + for condition in ("a", "b"): + image = write_ngff(root / condition / "img.zarr", np.zeros((2, 8, 8), np.uint8), "cyx") + labels = np.zeros((8, 8), np.uint8) + labels[2:5, 2:5] = 1 + write_labels(image, {"cells": labels}, axes="yx") + assert main(["describe", str(root), "--output", str(out), *CHANNELS, "--publish"]) == 0 + return root, out + + +def test_check_reports_an_undeclared_ome_zarr_label_mask_as_run_refuses_it(tmp_path, capsys): + root, out = _labelled(tmp_path) + capsys.readouterr() + assert main(["check", str(root), "--output", str(out)]) == 1 + checked = capsys.readouterr().out + assert main(["run", str(root), "--output", str(out)]) == 1 + ran = capsys.readouterr().out + message = ( + "Masks of type 'cells' were found (in the masks folder, beside the images or as " + "OME-Zarr label images), but are not declared in the description." + ) + action = "declare-masks --output FOLDER --type cells=REPRESENTATION" + for text in (checked, ran): + assert message in text and action in text + assert "--type TYPE=instances" not in checked # no representation is suggested for you + + +def test_declare_masks_without_a_masks_folder_names_no_placeholder_folder(tmp_path, capsys): + root, out = _labelled(tmp_path) + capsys.readouterr() + assert main(["declare-masks", "--output", str(out), "--type", "cells=instances"]) == 0 + text = capsys.readouterr().out + assert f"morphobricks-preprocessing run EXPERIMENT --output {out}\n" in text + assert f"morphobricks-preprocessing masks EXPERIMENT --output {out}\n" in text + assert "--masks MASKS" not in text and "OME-Zarr label images" in text + assert main(["check", str(root), "--output", str(out)]) == 0 + assert main(["run", str(root), "--output", str(out)]) == 0 # now recorded + capsys.readouterr() + assert main(["declare-masks", "--output", str(out), "--type", "cells=instances"]) == 0 + text = capsys.readouterr().out + assert f"morphobricks-preprocessing run --output {out}\n" in text # the recorded experiment + + +def test_declare_masks_with_a_masks_folder_names_it(tmp_path, capsys): + from morphobricks_preprocessing.cli_declare_masks import next_commands + + lines = next_commands(str(tmp_path / "out"), str(tmp_path / "my masks")) + assert lines[1].endswith(f"--masks '{tmp_path / 'my masks'}'") + assert all("Add --masks" not in line for line in lines) + + +# --- 4. Open questions in fast mode --------------------------------------------------------- + + +def test_fast_describe_lists_open_questions_only_while_some_remain(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + for condition in ("CTRL", "DrugA"): + _ome(root / condition / "rep1" / "img.ome.tif") + assert main(["describe", str(root), "--output", str(out), *CHANNELS, "--publish"]) == 0 + text = capsys.readouterr().out + assert "answered by you, in the notebook" not in text + assert "open questions are answered by your options" in text + partial = ["--channels", "DNA,ACTIN", "--image-type", "channels", "--accept-ids"] + assert main(["describe", str(root), "--output", str(tmp_path / "o2"), *partial]) == 0 + text = capsys.readouterr().out + assert "1 open questions (answer them with --accept-ids, --comparable" in text + assert "confirm that the folders of repeat rep1" in text + assert "choose the ID" not in text # --accept-ids answered those + + +# --- 5. and 6. RGB as OME-Zarr: convert --store ome-zarr, then the suggestion --------------- + + +def test_convert_store_ome_zarr_writes_every_image_as_ome_zarr(tmp_path, capsys): + pytest.importorskip("zarr") + src, copies = tmp_path / "src", tmp_path / "copies" + for condition in ("a", "b"): + _scanner(src / condition / "img.tif", colour="rgb") + command = ["convert", str(src), "--to", str(copies), "--axes", "YXC", "--store", "ome-zarr"] + assert main(command) == 0 + text = capsys.readouterr().out + assert "written as OME-Zarr with your roles: 2 images" in text + assert sorted(p.relative_to(copies).as_posix() for p in copies.rglob("*.ome.zarr")) == [ + "a/img.ome.zarr", + "b/img.ome.zarr", + ] + out = tmp_path / "out" + assert main(["describe", str(copies), "--output", str(out), *COLOUR, "--publish"]) == 0 + capsys.readouterr() + assert main(["check", str(copies), "--output", str(out)]) == 0 + assert "Suggested image type: rgb, because the published description declares" in ( + capsys.readouterr().out + ) + assert main(["run", str(copies), "--output", str(out)]) == 0 + assert "Image type: rgb\n" in capsys.readouterr().out + import json + + assert json.loads((out / "run_manifest.json").read_text())["image_type"] == "rgb" + + +def test_convert_store_is_ome_tiff_by_default_and_refuses_another(tmp_path, capsys): + src = tmp_path / "src" + _scanner(src / "a" / "img.tif", colour="rgb") + with pytest.raises(SystemExit): + main(["convert", str(src), "--to", str(tmp_path / "c"), "--axes", "YXC", "--store", "x"]) + assert "invalid choice: 'x'" in capsys.readouterr().err + + +def test_the_suggestion_follows_only_a_description_declaring_every_unit_rgb(): + from types import SimpleNamespace as NS + + from morphobricks_preprocessing.image_type import declared_image_type + + def described(*types): + units = {f"t{i}": NS(image_type=kind) for i, kind in enumerate(types)} + return NS(repeats={"r": NS(members={"c": NS(technical_repeats=units)})}) + + assert declared_image_type(described("rgb", "rgb")) == "rgb" + assert declared_image_type(described("rgb", None)) is None + assert declared_image_type(described()) is None + assert declared_image_type(None) is None From 3535b6875ff7ca830b406f4548c201be67c2537b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:32:51 +0000 Subject: [PATCH 03/25] Add he_tissue_v2: the H&E tissue mask with the white estimated from the plane he_tissue_v1 fixes the white at 255. On the Zenodo 4550300 TMA cores the glass is near (127, 135, 145), so every pixel read as stained (H >= 0.05 everywhere, no background) and tissue-mask kept 0.0 % of every core. he_tissue_v2 estimates each channel's white as the median of the brightest 0.1 % of pixels (by R+G+B), rescales with normalization's rescale_to_white and applies v1's components unchanged. It is the new default of RunInputs.he_tissue_mask, preview_he_tissue_mask, he_tissue_mask_array, tissue-mask and the notebook card; v1 is unchanged and still offered. Cores 1B_D9 and 2B_A6: 0.0 % -> 46.8 % and 44.4 % kept; white-glass slides are unchanged within 0.4 points; blank slides keep nothing. Regression fixture: a 320 x 320 crop of core 1B_D9 (CC-BY-4.0) with its generator script. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AEzaRH4WH1TyJRA61 --- AGENTS.md | 8 +- CHANGELOG.md | 24 +++ README.md | 4 +- docs/contract.md | 31 ++- docs/design/he-tissue-mask.md | 59 ++++++ docs/user_guide.md | 10 +- .../cli_tissue_mask.py | 29 +-- .../he_tissue_array.py | 33 ++-- .../he_tissue_mask.py | 48 +++-- .../he_tissue_rule.py | 58 +++++- .../notebook_tissue_mask.py | 2 +- .../run_inputs_tissue.py | 17 +- tests/data/he_core_1B_D9_crop.npz | Bin 0 -> 164267 bytes tests/data/make_he_core_crop.py | 55 ++++++ tests/test_brick_api_surface.py | 4 +- tests/test_cli_tissue_mask.py | 2 +- tests/test_he_tissue_array.py | 19 +- tests/test_he_tissue_mask.py | 8 +- tests/test_he_tissue_rule.py | 4 +- tests/test_he_tissue_v2.py | 178 ++++++++++++++++++ tests/test_notebook_tissue_mask.py | 2 +- 21 files changed, 506 insertions(+), 89 deletions(-) create mode 100644 tests/data/he_core_1B_D9_crop.npz create mode 100644 tests/data/make_he_core_crop.py create mode 100644 tests/test_he_tissue_v2.py diff --git a/AGENTS.md b/AGENTS.md index b513a96f..12931ef8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -378,8 +378,10 @@ src/morphobricks_preprocessing/ he_tissue_mask.py the opt-in H&E tissue mask (Spec ADR 0005 BM15; RunInputs.he_tissue_mask and preview_he_tissue_mask through run_inputs_tissue.py's lazy mixin, the he-mask extra): the FOV resolved from the run, every refusal before any read, BM15's - lineage line and own retry comparator; he_tissue_rule.py the fixed rule - he_tissue_v1 (provisional) as one canonical record, computed from its record + lineage line and own retry comparator; he_tissue_rule.py the fixed rules + he_tissue_v1 and he_tissue_v2 (the default: v1 on the plane rescaled to its + white, estimate_white; both provisional) as canonical records, computed from + their record (SciPy clean-up, 8-connected, disks clipped by the border); code_identity.py the verified code identity (RECORD digest, PEP 610); lineage_schema.py the reader's dispatch by operation and the duplicate-key refusal; @@ -1098,7 +1100,7 @@ Technical details go to `logging` (shown in the notebook's "Technical details" p | Histogram range (Q34, P6) | Step 3 **Settings**: the brick's `HistogramSettings` (`minmax` default, or `robust` with adjustable quantiles); recorded in the manifest's `settings.histogram`, any change recomputes every row. Every plane binned with `histogram_with_range_check` (memory estimate with `range_check=True`, through `planes._Binning`); `narrow_histogram_range` warnings from `range_check_issues`, one per channel, with the narrow planes recorded in the manifest's `narrow_histogram_ranges` so kept rows still report them. CSV schema 4 (underflow and overflow columns, zero with `minmax`); schema 3 tables recomputed. CLI `--histogram-range`, `--robust-quantiles`. Normalization brick pinned to v0.3.1 | | Position identity (Q20, D02) | `position_id` = image name without extension, in every CSV row and manifest file entry; FOV key = labels + `position_id`; duplicates in one leaf folder are the error `duplicate_position_id`. CSV columns and schema 2 unchanged; manifest version 1 with an optional key | | Masks (Q32) | Optional masks folder outside the experiment, one subfolder per mask type mirroring the experiment's folders, or the experiment's folders with `_.tif` (both may be mixed; `ambiguous_mask` when a name could fit two images or both layouts), paired by leaf folder + `position_id`; OME-Zarr label images are masks too. Header-only errors (`masks_folder_not_found`, `masks_inside_experiment`, `mask_names_differ_in_case`, `duplicate_mask`, `ambiguous_mask`, `unreadable_mask`, `mask_not_2d`, `mask_size_mismatch`, `mask_pixel_type`) and warnings (`mask_missing`, `mask_without_image`, `mask_outside_type_folder`) in `check`/`run`; manifest key `masks` (optional, version 1). Optional mask step (`masks` command, `scan_masks`): kinds, relations with evidence, direct-parent hierarchy, `mask_relationships.json` (report version 1); default thresholds the user may change (`thresholds=` keyword, one CLI option each, checked by `mask_thresholds`, written in the report); suggestions only, the user names and confirms. SciPy core dependency. Confirmed by the owner: 2D masks at the image's YX, integer/bool pixels, masks folder outside the experiment. Next: notebook step and a file of the user's answers; tag v0.2.0 proposed after merge. Plane identity (issue #36): masks may have Z and/or T named in their own metadata (never guessed: unnamed axes are `mask_not_2d`); the masks of an image share their planes (`mask_planes_differ`) and `run` checks them against the image's confirmed roles (`mask_planes_mismatch`, `mask_plane_issues`), so a 2D mask is refused for a Z-stack or time-lapse; manifest mask entries gain `axes` and `shape` (optional keys, version 1); `read_mask(z=, t=)` reads one plane; `scan_masks` scans plane by plane | -| H&E tissue mask (I1, BM15) | Opt-in only (`he-mask` extra; scikit-image, normalization's `stain` and the helper imported only when called). Fixed rule `he_tissue_v1`, provisional until its acceptance report is accepted; no per-call thresholds; sizes in pixels; colour maths from normalization only. One `uint8` region per image through BM12's publication with BM15's own line and comparator; an unverified code identity writes a mask never reused; freezing needs a new mask ID (design `docs/design/he-tissue-mask.md`, owner decisions of 16 November 2026) | +| H&E tissue mask (I1, BM15) | Opt-in only (`he-mask` extra; scikit-image, normalization's `stain` and the helper imported only when called). Fixed rules, provisional until an acceptance report is accepted: `he_tissue_v1` (white fixed at 255) and, the default since v0.10.1, `he_tissue_v2` (v1 on the plane rescaled to its white, the median of its brightest 0.1 %; v1 kept 0 % on grey-glass scans such as Zenodo 4550300); no per-call thresholds; sizes in pixels; colour maths from normalization only. One `uint8` region per image through BM12's publication with BM15's own line and comparator; an unverified code identity writes a mask never reused; freezing needs a new mask ID (design `docs/design/he-tissue-mask.md`, owner decisions of 16 November 2026) | | Settings (ADR 0011, Q89) | `defaults.toml` (package data) declares the run's (`common`) and Cellpose's (`cellpose`) settings with default, unit and help; `morphobricks_preprocessing.settings` loads, modifies, saves and passes them with the five shared names on the vendored `_brick_settings.py` (never edited; re-vendored from the Spec); the classes, CLI defaults and notebook widgets are copies held equal by `tests/test_settings.py`; no Cellpose CLI option | | Notebook style | Follow the lab's NucleiSky and LabChronicle notebooks (see §7) | | Widget widths | **99%**, never 100% | diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cca45e7..3aaf25eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,30 @@ The design is [`docs/design-v0.4.md`](docs/design-v0.4.md), imported unchanged f are in [docs/plan.md](docs/plan.md) §12. (The v0.3 to v0.4 migration guide was removed in v0.5.1: no run before v0.5.1 is read.) +## Unreleased (v0.10.1) + +### Fixed + +- **The H&E tissue mask kept nothing on scans whose glass is not white.** On the Zenodo 4550300 + H&E TMA cores (glass near (127, 135, 145), photometric tag MINISBLACK read with + `rgb_header_override = true`), `tissue-mask` printed "kept 0.0 % (nothing kept: an empty + region)" for every core, so fiberfeatures measured `roi_area_px = 0` and NaN features. The + channel order, the override and the mask's polarity were correct: rule `he_tissue_v1` fixes the + white at 255, so against it every pixel of these scans has an optical density of at least 0.22, + the background never fires, `H >= 0.05` holds everywhere and the whole plane was "nuclei". + New rule **`he_tissue_v2`** (provisional), the default of `RunInputs.he_tissue_mask`, + `RunInputs.preview_he_tissue_mask`, `he_tissue_mask_array`, `tissue-mask --rule` and the + notebook card: v1 on the plane rescaled to its own white, estimated per channel as the median + of the brightest 0.1 % of pixels (by R + G + B) and applied with normalization's + `rescale_to_white`. v1's thresholds and sizes are unchanged; v1 itself is unchanged and still + offered (`rule="he_tissue_v1"`). Kept share on cores 1B_D9 and 2B_A6: 0.0 % -> 46.8 % and + 44.4 %; on white-glass slides (CMU-1) v2 is within 0.4 points of v1, and identical when the + brightest pixels are 255; blank slides keep nothing. A mask written under v1 is not reused under + v2 (another rule record): use a new output mask ID. `TissueMaskPreview.white` gives the white + used (`None` under v1). Regression fixture: a 320 x 320 crop of core 1B_D9 + (`tests/data/he_core_1B_D9_crop.npz`, CC-BY-4.0, with its generator). Design: + `docs/design/he-tissue-mask.md` ("`he_tissue_v2`"). + ## v0.10.0 (3 December 2026) Minor release with a **breaking change of file format**: the histogram table is diff --git a/README.md b/README.md index 4392d910..dcb2d0bd 100644 --- a/README.md +++ b/README.md @@ -99,8 +99,8 @@ and installs missing requirements into the active kernel. A standalone download installs from GitHub if needed (internet access and Git required). The optional `he-mask` extra installs scikit-image (through `morphobricks-normalization[histology]`) -for the opt-in H&E tissue mask (`tissue-mask`, `RunInputs.he_tissue_mask`; rule `he_tissue_v1`, -provisional); without it, nothing of that helper is imported. `he_tissue_mask_array(rgb)` computes +for the opt-in H&E tissue mask (`tissue-mask`, `RunInputs.he_tissue_mask`; rule `he_tissue_v2` +by default, provisional); without it, nothing of that helper is imported. `he_tissue_mask_array(rgb)` computes the same mask on a `uint8` `(Y, X, 3)` array with no run and writes nothing (no lineage; for runs, use `tissue-mask`); see the [user guide](docs/user_guide.md#an-he-tissue-mask-optional) and [contract §15.4](docs/contract.md#154-the-he-tissue-mask-of-an-array-with-no-run-roadmap-k3). diff --git a/docs/contract.md b/docs/contract.md index 0a46176c..f15066d1 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1220,11 +1220,11 @@ time. An opt-in helper, never run by default, computes a `binary` **region** mask from one declared RGB image with a named, versioned, fixed rule whose colour maths is normalization's (`docs/design/he-tissue-mask.md`). `RunInputs.he_tissue_mask(fov, *, output_mask_id, -rule="he_tissue_v1")` writes it and returns `TissueMaskResult` (`image`, `mask_id`, `path`, +rule="he_tissue_v2")` writes it and returns `TissueMaskResult` (`image`, `mask_id`, `path`, `line`, `published`, `reusable`, `fractions`); `RunInputs.preview_he_tissue_mask(fov, *, -rule="he_tissue_v1")` computes it in memory and returns `TissueMaskPreview` (`E`, `H`, `od`, -`od_floored` exactly as normalization returns them, the components, `fractions`, the rule record -and the code identities); it writes nothing. The command `tissue-mask` and the notebook card +rule="he_tissue_v2")` computes it in memory and returns `TissueMaskPreview` (`E`, `H`, `od`, +`od_floored` exactly as normalization returns them, the components, `fractions`, the rule record, +the code identities and `white`, the white the plane was rescaled to, `None` under v1); it writes nothing. The command `tissue-mask` and the notebook card **Make an H&E tissue mask** call them. scikit-image (the `he-mask` extra: `pip install "morphobricks-preprocessing[he-mask]"`, which installs `morphobricks-normalization[histology]`), normalization's `stain` module and the helper's module @@ -1245,6 +1245,20 @@ means fewer than N pixels, a disk is `x*x + y*y <= r*r`, the structuring element the image border (never padded or wrapped; the opening's erosion counts only pixels inside the image), and every size is in pixels: no pixel size is read or used. +**The rule `he_tissue_v2` (v0.10.1, the default; also provisional)** is `he_tissue_v1` on the plane +rescaled to its own white. v1's white is fixed at 255, so on a scan whose glass is grey (the +Zenodo 4550300 TMA cores, glass near (127, 135, 145)) every pixel reads as stained and v1 keeps +0 %. v2 estimates the white per channel as the median of the pixels whose `R + G + B` is at or +above the 99.9th percentile of `R + G + B` (NumPy, method `linear`), at least 1; rescales the plane +with normalization's `rescale_to_white` (`clip(rint(I * 255 / white), 0, 255)` as `uint8`); and +applies v1's components, thresholds and clean-up unchanged to the rescaled plane (`E`, `H` and +`od` are then the rescaled plane's). When the plane's brightest pixels are white (255) the +rescaling is the identity and v2 equals v1. The white is read from the plane, so a plane with no +glass or empty space takes its brightest tissue as white. The rule record (version 2, +`input.white` `"estimated"`, a `white` entry stating the estimate and the rescaling) is written in +the lineage like v1's; the white itself is not a lineage key (it follows from the source content +digest and the rule record). `he_tissue_v1` stays offered unchanged with `rule="he_tissue_v1"`. + **Inputs, refused before any pixel is read** (a `ValueError` naming the position): the position is resolved by its image path from `RunInputs.fovs()`, and a caller's `image_type`, axes, counts or dtype are ignored; an image that is not the run's (`RunInputsError`); a unit not declared @@ -1295,10 +1309,10 @@ object at any depth is refused in both schemas (it was kept silently before). ### 15.4 The H&E tissue mask of an array, with no run (roadmap K3) -`he_tissue_mask_array(rgb, *, rule="he_tissue_v1") -> TissueMaskArray` (owner decision of +`he_tissue_mask_array(rgb, *, rule="he_tissue_v2") -> TissueMaskArray` (owner decision of 17 November 2026: in preprocessing) computes §15.3's rule on one image array in memory, for users who have pixels but no MorphoBricks run (a script, another brick's folder command). **The -rule is the same provisional `he_tissue_v1`**, and the computation is the run route's own: the +rules are the same provisional `he_tissue_v2` (the default) and `he_tissue_v1`**, and the computation is the run route's own: the array is moved to `(3, Y, X)` and given to the one function `RunInputs.he_tissue_mask` and `preview_he_tissue_mask` call after their read (`he_tissue_mask.rule_on_plane`), never a copy, so the mask is bitwise equal to the file the run route writes for the same pixels (tested on the @@ -1319,11 +1333,12 @@ a pixel type other than `uint8`, or a shape other than `(Y, X, 3)` (R, G, B last (`ImportError` naming `pip install "morphobricks-preprocessing[he-mask]"`). The input checks import nothing of the extra; scikit-image, normalization's `stain` module and the helper's module are imported only past them, never by `import morphobricks_preprocessing`. Like the run -route it takes no pixel size (sizes are pixels), no white (fixed at 255) and no thresholds. +route it takes no pixel size (sizes are pixels), no white (fixed at 255 under v1, estimated from +the plane under v2) and no thresholds. **Result.** `TissueMaskArray` (frozen): `mask`, boolean `(Y, X)`, `True` kept (a region, BM3; being boolean, an in-memory consumer refuses it as an object set, BM4); and `record`, a frozen -`TissueMaskArrayRecord`: `rule_id` (`"he_tissue_v1"`), `operation` (`"he_tissue_mask"`), +`TissueMaskArrayRecord`: `rule_id` (`"he_tissue_v2"` by default), `operation` (`"he_tissue_mask"`), `rule_text` (the complete rule record in its canonical JSON, keys sorted and no spaces: exactly the text `rule_sha256` is the SHA-256 of, as UTF-8; `rule` returns it as a new dict, with `rule_version`, `status` `"provisional"` and `provisional`), `rule_sha256`, `code` (BM15's code diff --git a/docs/design/he-tissue-mask.md b/docs/design/he-tissue-mask.md index 753407da..9631ac0f 100644 --- a/docs/design/he-tissue-mask.md +++ b/docs/design/he-tissue-mask.md @@ -184,6 +184,65 @@ changes v1. The complete rule record (below) and its SHA-256 are written to the tuned per image, and nothing is tuned silently. The preview and the "% kept" figure are how the user judges whether the rule suits their slides. +### `he_tissue_v2`: the white estimated from the plane (v0.10.1) + +**Why (3 December 2026).** On the Zenodo 4550300 H&E TMA cores (set B of criterion 3; 2048 x 2048 +`uint8` RGB, photometric tag wrongly MINISBLACK, read with `rgb_header_override = true`), +`tissue-mask` kept **0.0 %** of every core, so fiberfeatures measured `roi_area_px = 0`. The +channels are R, G, B in order (the override is applied before the rule) and the mask is not +inverted: the scanner's glass is near **(127, 135, 145)**, not 255, and the brightest pixel of +1B_D9 is (138, 154, 154). Against v1's fixed white of 255 every pixel has `OD >= 0.22`, so the +background (`max(OD) < 0.08`) never fires and `H >= 0.05` holds everywhere: the whole plane was +"nuclei" (`fractions` `nuclei` 1.0). + +**The rule.** `he_tissue_v2` is v1 on the plane rescaled to its own white: + +1. the white, per channel: the median of the pixels whose `R + G + B` is at or above the 99.9th + percentile of `R + G + B` (NumPy `percentile`, method `linear`), raised to at least 1 + (`he_tissue_rule.estimate_white`; counting only, no colour maths); +2. the plane rescaled with normalization's `rescale_to_white` (N69: + `clip(rint(I * 255 / white), 0, 255)` as `uint8`, `rint` half to even); +3. v1's components, thresholds and clean-up, unchanged, on the rescaled plane (`E` and `H` from + `he_eosin`, `OD` against 255). + +No threshold or size of v1 changed (the record's `components` are v1's). The record is version 2, +`input.white` `"estimated"`, with a `white` entry stating steps 1 and 2; v1 is unchanged and +still offered (`rule="he_tissue_v1"`). v2 is the default of `RunInputs.he_tissue_mask`, +`preview_he_tissue_mask`, `he_tissue_mask_array`, `tissue-mask` and the notebook card. Both are +provisional; the acceptance criteria above apply to v2 as they did to v1. The estimated white is +in the preview (`TissueMaskPreview.white`), not in the lineage line, whose source digest and rule +record determine it (the BM15 line keys are unchanged). + +**Measured (3 December 2026, scikit-image 0.26.0, normalization v0.10.0).** Kept share: + +| Image | v1 kept | v2 white | v2 kept | v2 background | v2 nuclei | +| --- | --- | --- | --- | --- | --- | +| Zenodo `1B_D9_WB.tif` (SHA-256 `8c74cadd…`) | 0.00 % | (130, 138, 149) | 46.8 % | 41.9 % | 11.3 % | +| Zenodo `2B_A6_WB.tif` (SHA-256 `6e49f686…`) | 0.00 % | (127, 134, 142) | 44.4 % | 52.6 % | 2.9 % | +| Zenodo `1B_F3_WB.tif` | 0.00 % | (136, 147, 168) | 52.6 % | 28.4 % | 19.1 % | +| Zenodo `2B_G5_WB.tif` | 0.00 % | (141, 143, 153) | 40.6 % | 44.7 % | 14.8 % | +| Zenodo `2B_H2_WB.tif` | 0.00 % | (141, 142, 152) | 38.3 % | 44.7 % | 17.0 % | +| Zenodo `2B_G3_WB.tif` | 0.00 % | (141, 143, 152) | 29.8 % | 66.4 % | 3.8 % | +| Zenodo `2B_E9_WB.tif` (a thin strip of tissue) | 0.00 % | (127, 134, 143) | 7.2 % | 85.8 % | 7.0 % | + +(the seven cores of the record's `validation2.zip`, SHA-256 `f7eb874b…`). On CMU-1 (set A, white +glass), 33 tiles of 1024 x 1024 at level 1 with at least 5 % tissue: the estimated white is +251 to 255 in every channel and v2's kept share is within 0.4 points of v1's on every tile; the 12 +level-1 tiles of 512 x 512 with the least near-white (2 to 7 %): Dice of v1 and v2 masks 0.978 to +0.998. Blank slides (uniform 255, glass at 242 or at (127, 135, 145) with noise): 0 % kept under +both rules. The PI-1 to PI-4 images (owner's, not public) were not rerun; their v1 numbers above +stand, and v2 equals v1 on any plane whose brightest 0.1 % are white. + +**Limitation.** The white is read from the plane: a plane with no glass, lumen or fat (tissue +from edge to edge) takes its brightest tissue as white, and pale tissue then moves towards +background. The preview and the printed kept share show it; `rule="he_tissue_v1"` is the choice +for such planes on a white-balanced scanner. + +**Regression fixture.** `tests/data/he_core_1B_D9_crop.npz`: rows 500-819, columns 80-399 of +`1B_D9_WB.tif` (CC-BY-4.0, Eliceiri, Li, Keikhosravi 2021, doi 10.5281/zenodo.4550300), written by +`tests/data/make_he_core_crop.py` from the checked zip. v1 keeps 0 % of it, v2 35.0 % +(`tests/test_he_tissue_v2.py`, also through a run with the header override). + ### The canonical rule record The rule is defined once, as an immutable record in the helper's module, and written whole into diff --git a/docs/user_guide.md b/docs/user_guide.md index 1d4ade7c..568a4ac2 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1385,8 +1385,12 @@ pip install "morphobricks-preprocessing[he-mask]" morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preprocessing --to HETissue ``` -- It is a **fixed rule**, `he_tissue_v1`, and it is **provisional**: its numbers are not frozen - until an acceptance report is accepted. It is not a trained segmentation. Its colour maths is +- It is a **fixed rule**, `he_tissue_v2` by default, and it is **provisional**: its numbers are + not frozen until an acceptance report is accepted. `he_tissue_v2` first measures each image's + white from its brightest pixels (the glass), so scans whose glass is grey rather than white + work; `--rule he_tissue_v1` keeps the white fixed at 255 (it keeps nothing on such scans). An + image with no glass or empty space at all takes its brightest tissue as white: check the + "kept" share. It is not a trained segmentation. Its colour maths is the normalization brick's (the eosin and hematoxylin maps of the `he_eosin` preset and the optical density per channel), and all its sizes are **in pixels**: the same rule on images of another magnification leaves out pieces of another physical size. Look at the preview (in the @@ -1409,7 +1413,7 @@ morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preproce source_type = "HETissue" representation = "binary" source_channels = ["R", "G", "B"] - display_name = "H&E tissue (he_tissue_v1)" + display_name = "H&E tissue (he_tissue_v2)" ``` For example fiberfeatures `MaskRequest("HETissue", "region")`. It is never a set of cells: do diff --git a/src/morphobricks_preprocessing/cli_tissue_mask.py b/src/morphobricks_preprocessing/cli_tissue_mask.py index dfc86b1a..2539f678 100644 --- a/src/morphobricks_preprocessing/cli_tissue_mask.py +++ b/src/morphobricks_preprocessing/cli_tissue_mask.py @@ -1,16 +1,16 @@ """The command line's ``tissue-mask``: the opt-in H&E tissue mask helper (Spec ADR 0005 BM15). -``tissue-mask --output FOLDER --to NEW_ID`` writes, for every image of the run in ``--output`` -whose unit is declared ``rgb`` (or only the ``--image`` paths given, repeatable), its H&E tissue -mask as the new ``binary`` region mask ``NEW_ID`` (``RunInputs.he_tissue_mask``, rule -``he_tissue_v1``, provisional): nuclei, red blood cells and empty space left out, sizes in -pixels. The outputs go to the run's masks folder, each with its line of ``mask_lineage.jsonl``; -the image is never changed and nothing is overwritten. A same call again is a no-op, unless a -code identity is unverified: such a mask is written but never reused, so a retry is refused. -The command prints what it wrote, the kept share, and the next steps (declare the mask -``binary``, run preprocessing and the masks step again, use it as a region). It stops at the -first refusal (exit status 1), naming it; the images written before it stay written. Without -scikit-image it names the extra to install and writes nothing (exit status 1). +``tissue-mask --output FOLDER --to NEW_ID`` writes, for every image of the run in ``--output`` whose +unit is declared ``rgb`` (or only the ``--image`` paths given, repeatable), its H&E tissue mask as +the new ``binary`` region mask ``NEW_ID`` (``RunInputs.he_tissue_mask``, rule ``he_tissue_v2`` by +default, provisional): nuclei, red blood cells and empty space left out, sizes in pixels. The +outputs go to the run's masks folder, each with its line of ``mask_lineage.jsonl``; the image is +never changed and nothing is overwritten. A same call again is a no-op, unless a code identity is +unverified: such a mask is written but never reused, so a retry is refused. The command prints what +it wrote, the kept share, and the next steps (declare the mask ``binary``, run preprocessing and the +masks step again, use it as a region). It stops at the first refusal (exit status 1), naming it; the +images written before it stay written. Without scikit-image it names the extra to install and writes +nothing (exit status 1). """ from __future__ import annotations @@ -20,7 +20,7 @@ from .plane_errors import PlaneReadError from .run_inputs import RunInputs from .run_inputs_tissue import ( - HE_TISSUE_V1, + HE_TISSUE_V2, NOT_REUSED, PROVISIONAL_NOTE, rgb_positions, @@ -66,8 +66,9 @@ def add_tissue_mask_parser(commands: argparse._SubParsersAction) -> argparse.Arg ) tissue.add_argument( "--rule", - default=HE_TISSUE_V1, - help=f"the fixed rule (default and only rule: {HE_TISSUE_V1}, provisional)", + default=HE_TISSUE_V2, + help=f"the fixed rule (default {HE_TISSUE_V2}, the white estimated from each image; or " + "he_tissue_v1, the white fixed at 255; both provisional)", ) return tissue diff --git a/src/morphobricks_preprocessing/he_tissue_array.py b/src/morphobricks_preprocessing/he_tissue_array.py index 6e8ed867..fb3bdfef 100644 --- a/src/morphobricks_preprocessing/he_tissue_array.py +++ b/src/morphobricks_preprocessing/he_tissue_array.py @@ -1,11 +1,11 @@ """The H&E tissue mask of an image array in memory, with no run (contract §15.4; roadmap K3). -``he_tissue_mask_array(rgb)`` computes the fixed rule ``he_tissue_v1`` (**provisional**) on one -``uint8`` ``(Y, X, 3)`` R, G, B array and returns the boolean mask (``True`` kept) with a small -immutable record of what computed it. It is for standalone users (a script, another brick's +``he_tissue_mask_array(rgb)`` computes a fixed rule (``he_tissue_v2`` by default, **provisional**) +on one ``uint8`` ``(Y, X, 3)`` R, G, B array and returns the boolean mask (``True`` kept) with a +small immutable record of what computed it. It is for standalone users (a script, another brick's folder command) who have pixels but no MorphoBricks run. The computation is the run route's own -(:func:`.he_tissue_mask.rule_on_plane`, called with the array moved to ``(3, Y, X)``), never a -copy, so the two masks are bitwise equal for the same pixels. +(:func:`.he_tissue_mask.rule_on_plane`, called with the array moved to ``(3, Y, X)``), never a copy, +so the two masks are bitwise equal for the same pixels. **Not a run artifact (Spec ADR 0005 BM15).** BM15 governs a derived region mask *written in a run*: a file in the masks folder with its ``mask_lineage.jsonl`` line, declared by the user and @@ -38,7 +38,7 @@ import numpy as np -HE_TISSUE_V1 = "he_tissue_v1" +HE_TISSUE_V2 = "he_tissue_v2" """The default rule, as in ``RunInputs.he_tissue_mask`` (provisional; :mod:`.he_tissue_rule`).""" IN_MEMORY = "" """The label of the plane in the shared computation: an array, not an image of a run.""" @@ -68,7 +68,7 @@ class TissueMaskArrayRecord: Attributes ---------- rule_id - The rule asked for (``"he_tissue_v1"``). + The rule asked for (``"he_tissue_v2"`` by default). operation The rule's operation (``"he_tissue_mask"``), as in the run route's lineage. rule_text @@ -113,12 +113,12 @@ def rule(self) -> dict: @property def rule_version(self) -> int: - """The rule record's ``version`` (``1`` for ``he_tissue_v1``).""" + """The rule record's ``version`` (``2`` for ``he_tissue_v2``).""" return self.rule["version"] @property def status(self) -> str: - """The rule record's ``status``: ``"provisional"`` for ``he_tissue_v1``.""" + """The rule record's ``status``: ``"provisional"`` for both rules.""" return self.rule["status"] @property @@ -154,14 +154,14 @@ class TissueMaskArray: record: TissueMaskArrayRecord -def he_tissue_mask_array(rgb: np.ndarray, *, rule: str = HE_TISSUE_V1) -> TissueMaskArray: +def he_tissue_mask_array(rgb: np.ndarray, *, rule: str = HE_TISSUE_V2) -> TissueMaskArray: """Compute the H&E tissue mask of one ``uint8`` ``(Y, X, 3)`` R, G, B array in memory. - The rule ``he_tissue_v1`` is **provisional** and fixed: it leaves out nuclei, red blood - cells and empty space, sizes in pixels, colour maths from normalization. The computation is - ``RunInputs.he_tissue_mask``'s own, so the mask is bitwise equal to the run route's for the - same pixels. Nothing is written and no run is read; for MorphoBricks runs use the run route, - which writes the mask with its lineage. + The rule (``he_tissue_v2`` by default) is **provisional** and fixed: it leaves out nuclei, + red blood cells and empty space, sizes in pixels, colour maths from normalization. The + computation is ``RunInputs.he_tissue_mask``'s own, so the mask is bitwise equal to the run + route's for the same pixels. Nothing is written and no run is read; for MorphoBricks runs use + the run route, which writes the mask with its lineage. Parameters ---------- @@ -169,7 +169,8 @@ def he_tissue_mask_array(rgb: np.ndarray, *, rule: str = HE_TISSUE_V1) -> Tissue A plain ``numpy.ndarray`` of pixel type ``uint8`` and shape ``(Y, X, 3)``, the last axis R, G, B. Nothing is converted and no axis is guessed. rule - The rule ID; ``"he_tissue_v1"`` is the only one. + The rule ID: ``"he_tissue_v2"`` (the default: the white estimated from the plane) or + ``"he_tissue_v1"`` (the white fixed at 255). Returns ------- diff --git a/src/morphobricks_preprocessing/he_tissue_mask.py b/src/morphobricks_preprocessing/he_tissue_mask.py index 971b38eb..0e969629 100644 --- a/src/morphobricks_preprocessing/he_tissue_mask.py +++ b/src/morphobricks_preprocessing/he_tissue_mask.py @@ -1,8 +1,9 @@ """The opt-in H&E tissue mask helper (Spec ADR 0005 BM15; design ``docs/design/he-tissue-mask.md``). ``RunInputs.he_tissue_mask(fov, output_mask_id=...)`` writes one ``uint8`` region mask of one RGB -position: ``1`` where the fixed rule (:mod:`.he_tissue_rule`, ``he_tissue_v1``, **provisional**) -keeps the pixel, ``0`` where it leaves out nuclei, red blood cells or empty space. +position: ``1`` where the fixed rule (:mod:`.he_tissue_rule`, ``he_tissue_v2`` by default, +``he_tissue_v1`` on request, both **provisional**) keeps the pixel, ``0`` where it leaves out +nuclei, red blood cells or empty space. ``RunInputs.preview_he_tissue_mask(fov)`` computes the same in memory and writes nothing. Both are reached through :class:`.run_inputs_tissue.TissueMaskInputs`, which imports this module only when called: scikit-image, normalization's ``stain`` module and this module stay out of a core @@ -24,8 +25,11 @@ **Colour maths: normalization's, never reimplemented.** ``E`` and ``H`` are ``stain.to_scalar(rgb, axes="CYX", preset="he_eosin")``'s ``image`` and ``exclusion``; the per-channel optical density is ``optical_density(rgb_yxc(rgb, "CYX"), check_white((255, 255, -255)))``, unpacked as ``(od, od_floored)``. The HED matrix is only looked up by the preset's own -name for it, to hash it into the rule record. +255)))``, unpacked as ``(od, od_floored)``. Under ``he_tissue_v2`` both are computed on the +plane rescaled to its estimated white by normalization's ``rescale_to_white`` +(:func:`.he_tissue_rule.estimate_white`); the white is in the preview, not in the lineage +line, whose ``source.content_sha256`` and rule record determine it. The HED matrix is only +looked up by the preset's own name for it, to hash it into the rule record. **Output and publication.** The file goes to ``///.tif`` with its line of ``mask_lineage.jsonl`` (the BM15 schema, @@ -55,16 +59,22 @@ import numpy as np import scipy from morphobricks_normalization import stain -from morphobricks_normalization.optical_density import check_white, optical_density +from morphobricks_normalization.optical_density import ( + check_white, + optical_density, + rescale_to_white, +) from morphobricks_normalization.scalar_inputs import rgb_yxc from .code_identity import code_identity from .he_tissue_rule import ( - HE_TISSUE_V1, + DEFAULT_RULE, OPERATION, PROVISIONAL, RULES, TissueComponents, + estimate_white, + estimates_white, rule_record, tissue_components, ) @@ -158,9 +168,12 @@ class TissueMaskPreview: fractions As :attr:`TissueMaskResult.fractions`, from the full-resolution mask. rule - The rule's canonical record (``status`` ``"provisional"`` for ``he_tissue_v1``). + The rule's canonical record (``status`` ``"provisional"``). code The two code identities; ``reusable`` is True only when both are verified. + white + The white the plane was rescaled to before ``E``, ``H`` and ``od`` (``he_tissue_v2``), + R, G, B; ``None`` for a rule with the fixed white 255 (``he_tissue_v1``). """ image: str @@ -173,6 +186,7 @@ class TissueMaskPreview: fractions: Mapping[str, float] rule: Mapping[str, Any] code: Mapping[str, Mapping[str, object]] + white: tuple[float, float, float] | None = None @property def reusable(self) -> bool: @@ -305,7 +319,7 @@ def resolved_fov(run: RunInputs, fov: object) -> Fov: return found -def preview(run: RunInputs, fov: object, *, rule: str = HE_TISSUE_V1) -> TissueMaskPreview: +def preview(run: RunInputs, fov: object, *, rule: str = DEFAULT_RULE) -> TissueMaskPreview: """Compute one position's tissue mask in memory (``RunInputs.preview_he_tissue_mask``).""" found = resolved_fov(run, fov) record = current_rule(rule) @@ -313,7 +327,7 @@ def preview(run: RunInputs, fov: object, *, rule: str = HE_TISSUE_V1) -> TissueM def he_tissue_mask( - run: RunInputs, fov: object, *, output_mask_id: str, rule: str = HE_TISSUE_V1 + run: RunInputs, fov: object, *, output_mask_id: str, rule: str = DEFAULT_RULE ) -> TissueMaskResult: """Write one position's tissue mask with its lineage line (``RunInputs.he_tissue_mask``). @@ -467,10 +481,19 @@ def rule_on_plane( Every route calls it (the run route through :func:`_compute`, after its read, and ``he_tissue_mask_array`` on its array moved to ``(3, Y, X)``), so their masks are one computation, never a copy. The caller has checked the plane and the rule - (:func:`current_rule`). ``image`` labels the plane in the result. + (:func:`current_rule`). ``image`` labels the plane in the result. A rule that estimates + the white (``he_tissue_v2``) rescales the plane to it with normalization's + ``rescale_to_white`` first; ``E``, ``H`` and ``od`` are then of the rescaled plane. """ - scalar = stain.to_scalar(pixels, axes=SOURCE_AXES, preset=PRESET) - od, od_floored = _optical_density(pixels) + white = None + measured = pixels + if estimates_white(record): + rgb = rgb_yxc(pixels, SOURCE_AXES) + white = estimate_white(rgb) + rescaled, _clipped = rescale_to_white(rgb, check_white(white)) + measured = np.ascontiguousarray(np.moveaxis(rescaled, -1, 0)) + scalar = stain.to_scalar(measured, axes=SOURCE_AXES, preset=PRESET) + od, od_floored = _optical_density(measured) components = tissue_components(scalar.image, scalar.exclusion, od, record) fractions = {**components.fractions(), "od_floored": od_floored} return TissueMaskPreview( @@ -484,6 +507,7 @@ def rule_on_plane( fractions=MappingProxyType(fractions), rule=MappingProxyType(record), code=code_identities(), + white=white, ) diff --git a/src/morphobricks_preprocessing/he_tissue_rule.py b/src/morphobricks_preprocessing/he_tissue_rule.py index 74e2f562..e15f194c 100644 --- a/src/morphobricks_preprocessing/he_tissue_rule.py +++ b/src/morphobricks_preprocessing/he_tissue_rule.py @@ -14,7 +14,20 @@ - background: ``max(OD_R, OD_G, OD_B) < 0.08``; opened by a disk of radius 2, then pieces under 1000 px removed (only lumens, fat and tears; not the gaps between fibres). -``keep = not (nuclei or red_cells or background)``. ``E`` and ``H`` are normalization's +``keep = not (nuclei or red_cells or background)``. + +``he_tissue_v2`` (status ``"provisional"``; the default since v0.10.1) is ``he_tissue_v1`` on the +plane rescaled to its own white: v1 fixes the white at 255, so a scan whose glass is grey (the +Zenodo 4550300 cores, glass near (127, 135, 145)) read as stained everywhere and v1 kept 0 %. +v2 estimates the white per channel as the **median of the pixels whose R + G + B is at or above +the 99.9th percentile of R + G + B** (NumPy ``percentile``, method ``linear``), raised to at +least 1 (:func:`estimate_white`), rescales the plane with normalization's +``rescale_to_white`` (``clip(rint(I * 255 / white), 0, 255)`` as uint8, N69) and then applies +v1's components unchanged to the rescaled plane. On a plane whose brightest pixels are white +(255) the rescaling is the identity and v2 equals v1. The white is read from the plane, so a +plane with no glass or empty space takes its brightest tissue as white (recorded in the design). + +``E`` and ``H`` are normalization's ``to_scalar(..., preset="he_eosin")`` ``image`` and ``exclusion`` (float32), ``OD`` its ``optical_density`` (float64, ``(Y, X, 3)``). Every comparison is made in float64 on the values as normalization returns them, as written (``>=`` or ``<``), with no rounding and no tolerance; @@ -43,6 +56,11 @@ OPERATION = "he_tissue_mask" """The lineage ``operation`` of every ``he_tissue`` rule (Spec ADR 0005 BM15).""" HE_TISSUE_V1 = "he_tissue_v1" +HE_TISSUE_V2 = "he_tissue_v2" +DEFAULT_RULE = HE_TISSUE_V2 +"""The rule used when none is named (since v0.10.1; ``he_tissue_v1`` stays offered unchanged).""" +WHITE_PERCENTILE = 99.9 +"""v2's white: the median of the pixels at or above this percentile of R + G + B.""" CONNECTIVITY = 8 DISK = "x*x + y*y <= r*r" COMPONENT_NAMES = ("nuclei", "red_cells", "background") @@ -94,8 +112,22 @@ "combine": "keep = not (nuclei or red_cells or background)", } -RULES: Mapping[str, str] = {HE_TISSUE_V1: PROVISIONAL} -"""The known rule IDs and the ``status`` each is offered with (v1 is provisional).""" +_V2 = copy.deepcopy(_V1) +_V2["version"] = 2 +_V2["input"]["white"] = "estimated" +_V2["white"] = { + "estimate": "per channel: median of the pixels whose R+G+B >= percentile(R+G+B, 99.9, " + "method='linear'), at least 1", + "rescale": { + "function": "morphobricks_normalization.optical_density.rescale_to_white", + "definition": "clip(rint(I * 255 / white), 0, 255) as uint8, rint half to even", + }, + "then": "the components of he_tissue v1 on the rescaled plane, white [255, 255, 255]", +} +_RECORDS = {HE_TISSUE_V1: _V1, HE_TISSUE_V2: _V2} + +RULES: Mapping[str, str] = {HE_TISSUE_V1: PROVISIONAL, HE_TISSUE_V2: PROVISIONAL} +"""The known rule IDs and the ``status`` each is offered with (both provisional).""" def rule_record(rule_id: str, *, hed_source: str, hed_sha256: str) -> dict: @@ -121,7 +153,7 @@ def rule_record(rule_id: str, *, hed_source: str, hed_sha256: str) -> dict: raise ValueError(f"The rule {rule_id!r} is not known; the known rules are {known}") if RULES[rule_id] not in STATUSES: raise ValueError(f"The rule {rule_id!r} has the unknown status {RULES[rule_id]!r}") - record = copy.deepcopy(_V1) + record = copy.deepcopy(_RECORDS[rule_id]) record["status"] = RULES[rule_id] record["colour"]["hed_matrix"] = {"source": hed_source, "sha256": hed_sha256} return record @@ -150,6 +182,24 @@ def fractions(self) -> dict[str, float]: } +def estimates_white(rule: Mapping[str, object]) -> bool: + """Return True when a rule record rescales the plane to its own white first (v2).""" + return "white" in rule + + +def estimate_white(rgb: np.ndarray) -> tuple[float, float, float]: + """Return a plane's white as v2 estimates it, from its ``uint8`` ``(Y, X, 3)`` pixels. + + Per channel, the median of the pixels whose ``R + G + B`` is at or above the 99.9th + percentile of ``R + G + B`` (NumPy ``percentile``, method ``linear``), raised to at least 1 + so that normalization accepts it as a white. Pure counting: no colour maths. + """ + total = rgb.astype(np.int32).sum(axis=-1) + bright = total >= np.percentile(total, WHITE_PERCENTILE, method="linear") + white = np.maximum(np.median(rgb[bright], axis=0), 1.0) + return tuple(float(value) for value in white) + + def disk(radius: int) -> np.ndarray: """Return the boolean disk ``x*x + y*y <= r*r`` of side ``2 r + 1``.""" yy, xx = np.mgrid[-radius : radius + 1, -radius : radius + 1] diff --git a/src/morphobricks_preprocessing/notebook_tissue_mask.py b/src/morphobricks_preprocessing/notebook_tissue_mask.py index c26ff730..4577417c 100644 --- a/src/morphobricks_preprocessing/notebook_tissue_mask.py +++ b/src/morphobricks_preprocessing/notebook_tissue_mask.py @@ -159,7 +159,7 @@ def _children(self) -> list[widgets.Widget]: return [ ui.help_text( "Writes a new region mask that leaves out nuclei, red blood cells and " - "empty space of H&E images, with a fixed rule (he_tissue_v1, " + "empty space of H&E images, with a fixed rule (he_tissue_v2, " "provisional; not a trained segmentation). The images are only read and nothing " "is overwritten. Each file gets a line in mask_lineage.jsonl. Declare the " "new mask as binary, run again and describe the masks before a brick uses it." diff --git a/src/morphobricks_preprocessing/run_inputs_tissue.py b/src/morphobricks_preprocessing/run_inputs_tissue.py index 6c4367cf..58da03c5 100644 --- a/src/morphobricks_preprocessing/run_inputs_tissue.py +++ b/src/morphobricks_preprocessing/run_inputs_tissue.py @@ -15,21 +15,21 @@ from .he_tissue_mask import TissueMaskPreview, TissueMaskResult from .run_inputs import Fov -HE_TISSUE_V1 = "he_tissue_v1" -"""The default rule (provisional; :mod:`.he_tissue_rule`).""" +HE_TISSUE_V2 = "he_tissue_v2" +"""The default rule (provisional; :mod:`.he_tissue_rule`; ``he_tissue_v1`` on request).""" class TissueMaskInputs: """The H&E tissue mask helper of ``RunInputs`` (mixed into it).""" def he_tissue_mask( - self, fov: Fov | str, *, output_mask_id: str, rule: str = HE_TISSUE_V1 + self, fov: Fov | str, *, output_mask_id: str, rule: str = HE_TISSUE_V2 ) -> TissueMaskResult: """Write one RGB position's H&E tissue mask as a new ``binary`` region mask. The position is resolved from this run by its image path (a ``Fov``'s other attributes - are ignored). The rule ``he_tissue_v1`` is **provisional** and fixed: it leaves out - nuclei, red blood cells and empty space, sizes in pixels, colour maths from + are ignored). The rule (``he_tissue_v2`` by default) is **provisional** and fixed: it + leaves out nuclei, red blood cells and empty space, sizes in pixels, colour maths from normalization. The output goes to ``//...`` with its line of ``mask_lineage.jsonl``; declare it ``representation = "binary"``, run preprocessing and the masks step again, and use it as a region: in memory, never pass it as @@ -42,7 +42,8 @@ def he_tissue_mask( output_mask_id The new mask ID (experiment-v1 section 3.2), typed by the user. rule - The rule ID; ``"he_tissue_v1"`` is the only one. + The rule ID: ``"he_tissue_v2"`` (the default: the white estimated from the + plane) or ``"he_tissue_v1"`` (the white fixed at 255). Returns ------- @@ -63,7 +64,7 @@ def he_tissue_mask( return he_tissue_mask(self, fov, output_mask_id=output_mask_id, rule=rule) def preview_he_tissue_mask( - self, fov: Fov | str, *, rule: str = HE_TISSUE_V1 + self, fov: Fov | str, *, rule: str = HE_TISSUE_V2 ) -> TissueMaskPreview: """Compute one RGB position's H&E tissue mask in memory; nothing is written. @@ -84,7 +85,7 @@ def preview_he_tissue_mask( PROVISIONAL_NOTE = ( - "Sizes are in pixels. Fixed rule he_tissue_v1 (provisional), not a trained segmentation." + "Sizes are in pixels. Fixed rule he_tissue_v2 (provisional), not a trained segmentation." ) NOT_REUSED = "this mask will not be reused on retry" """Said whenever a code identity is unverified (the mask is written but never reused).""" diff --git a/tests/data/he_core_1B_D9_crop.npz b/tests/data/he_core_1B_D9_crop.npz new file mode 100644 index 0000000000000000000000000000000000000000..5e25c26c2f8d5b03369f527f758e129a5b1c13bf GIT binary patch literal 164267 zcmV)rK$*W#O9KQg000080000X0KC=5ApigW|NsC0{|5jR0CHzyE^csn0RRvHfUpDr z00000CxHS000000l)ZO%6WP}8d+xvY1H8MN+$0+t6KrFQb5_nd=Txd3l#>Amc7qdr zzVDrDRjsNe!QSUw#vB^5B+J-Czj|g~KfMu;Kk@(kuh#$S&y_1mNuJwyGB?oP&%J&! zR~2McF7P=)E?3awCk0liz~f52AXeb(`IY5&ub=2QuU{crW(ZgO!Aj}I?yhxj$ai)&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RdDrbVChMC?L~ZhDR;D4yF8@g9o_Tv7Xh9+_IDQB!+lU@90u{;S^MASEO$^&Xd#8-aHAq#E8XxYu*;jiP_2nmTP} zJybEo*C2dA=Gz=d)JSR%M1XLuk3vY^Lnyf z^0L?YoqdOSbe_z|o^9upn}v}BvrJ*NfX(KesVlBQFaoZk(>cU1j@QP_m7jh5saWMs$^9;WUl}u<1Fy{m|q~LO3Q!0db+T4Dn5*nQ}n3TankOf3% zG~mVrJkl|_8ByT0V;Ym{i21%+9crzyx$rWP+t_G8p3GgDz?`CK7cnvCoX6%kAH-iA zxI!Ha0cf-NF$DIJ_4-h+4N%9U)RFT#{NVo&P)h* None: + """Check the downloaded zip and its member, then write the crop next to this script.""" + data = Path(zip_path).read_bytes() + if hashlib.sha256(data).hexdigest() != ZIP_SHA256: + raise SystemExit(f"{zip_path} is not the record's validation2.zip (SHA-256 differs)") + member = zipfile.ZipFile(io.BytesIO(data)).read(MEMBER) + if hashlib.sha256(member).hexdigest() != MEMBER_SHA256: + raise SystemExit(f"{MEMBER} differs from the one this crop was taken from") + with tifffile.TiffFile(io.BytesIO(member)) as tif: + rgb = tif.series[0].asarray() + crop = np.ascontiguousarray(rgb[ROWS, COLUMNS]) + assert crop.shape == (320, 320, 3) and crop.dtype == np.uint8 + np.savez_compressed(TARGET, rgb=crop) + print(f"wrote {TARGET} ({TARGET.stat().st_size} bytes)") + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/tests/test_brick_api_surface.py b/tests/test_brick_api_surface.py index 7beb473d..dcdedac4 100644 --- a/tests/test_brick_api_surface.py +++ b/tests/test_brick_api_surface.py @@ -84,11 +84,11 @@ "histograms": "(self) -> 'tuple[PlaneRecord, ...]'", # Spec ADR 0005 BM15: the opt-in H&E tissue mask helper (imported lazily, he-mask extra). "he_tissue_mask": ( - "(self, fov: 'Fov | str', *, output_mask_id: 'str', rule: 'str' = 'he_tissue_v1') " + "(self, fov: 'Fov | str', *, output_mask_id: 'str', rule: 'str' = 'he_tissue_v2') " "-> 'TissueMaskResult'" ), "preview_he_tissue_mask": ( - "(self, fov: 'Fov | str', *, rule: 'str' = 'he_tissue_v1') -> 'TissueMaskPreview'" + "(self, fov: 'Fov | str', *, rule: 'str' = 'he_tissue_v2') -> 'TissueMaskPreview'" ), "description": "(self) -> 'Description'", "section_digests": "(self) -> 'dict[str, str]'", diff --git a/tests/test_cli_tissue_mask.py b/tests/test_cli_tissue_mask.py index 9bfee5ca..87fb9f7a 100644 --- a/tests/test_cli_tissue_mask.py +++ b/tests/test_cli_tissue_mask.py @@ -44,7 +44,7 @@ def test_it_writes_every_rgb_image_and_names_the_next_steps(tmp_path, capsys, mo args = ["tissue-mask", "--output", str(run.output_folder), "--to", "HETissue"] assert main(args) == 0 printed = capsys.readouterr().out - assert "Fixed rule he_tissue_v1 (provisional)" in printed + assert "Fixed rule he_tissue_v2 (provisional)" in printed assert f"{IMAGE}: HETissue/{IMAGE} (written), kept 80.4 %" in printed assert "declare the mask HETissue (source type HETissue) as binary" in printed assert "run preprocessing and the masks step again" in printed diff --git a/tests/test_he_tissue_array.py b/tests/test_he_tissue_array.py index 6fd37cb8..bda6e8d6 100644 --- a/tests/test_he_tissue_array.py +++ b/tests/test_he_tissue_array.py @@ -119,13 +119,15 @@ def test_an_input_it_cannot_take_is_refused_before_any_computation( def test_an_unknown_rule_is_refused_before_any_computation(no_computation): - with pytest.raises(ValueError, match="'he_tissue_v2' is not known; the known rules are"): - he_tissue_mask_array(GOOD, rule="he_tissue_v2") + with pytest.raises(ValueError, match="'he_tissue_v3' is not known; the known rules are"): + he_tissue_mask_array(GOOD, rule="he_tissue_v3") @pytest.mark.parametrize("rule", [["he_tissue_v1"], ("he_tissue_v1",), None, 1]) def test_a_rule_that_is_not_one_id_is_a_clear_type_error(rule, no_computation): - with pytest.raises(TypeError, match="The rule is one ID, a str such as he_tissue_v1; got "): + with pytest.raises( + TypeError, match="The rule is one ID, a str such as he_tissue_v1, he_tissue_v2; got " + ): he_tissue_mask_array(GOOD, rule=rule) @@ -133,7 +135,7 @@ def test_its_parameters_are_the_run_routes_and_nothing_more(): signature = inspect.signature(he_tissue_mask_array) assert ( str(signature) - == "(rgb: 'np.ndarray', *, rule: 'str' = 'he_tissue_v1') -> 'TissueMaskArray'" + == "(rgb: 'np.ndarray', *, rule: 'str' = 'he_tissue_v2') -> 'TissueMaskArray'" ) run_route = inspect.signature(helper.he_tissue_mask).parameters["rule"] assert signature.parameters["rule"].default == run_route.default @@ -180,7 +182,8 @@ def test_the_threshold_image_gives_the_mask_its_parts_specify(): | ndimage.binary_dilation(red_cells, _disk(1)) | background ) - found = he_tissue_mask_array(rgb) + # The thresholds of v1 on the image as it is; v2 rescales its white (240) first. + found = he_tissue_mask_array(rgb, rule="he_tissue_v1") assert found.mask.shape == (100, 220) assert np.array_equal(found.mask, ~excluded) for name in ON_THRESHOLD: # one side of each threshold excluded, the other kept @@ -219,13 +222,13 @@ def test_the_record_states_the_rule_its_status_and_the_code_identities_as_found( record = found.record assert isinstance(record, TissueMaskArrayRecord) assert (record.rule_id, record.rule_version, record.status, record.provisional) == ( - "he_tissue_v1", - 1, + "he_tissue_v2", + 2, "provisional", True, ) assert record.operation == "he_tissue_mask" - assert record.rule == helper.current_rule("he_tissue_v1") + assert record.rule == helper.current_rule("he_tissue_v2") assert record.rule_sha256 == rule_sha256(record.rule) # rule_text is the canonical form itself: the exact text its digest is of (issue #345). assert hashlib.sha256(record.rule_text.encode("utf-8")).hexdigest() == record.rule_sha256 diff --git a/tests/test_he_tissue_mask.py b/tests/test_he_tissue_mask.py index ee06ce21..6b8b89c8 100644 --- a/tests/test_he_tissue_mask.py +++ b/tests/test_he_tissue_mask.py @@ -291,10 +291,10 @@ def test_other_refusals_before_any_read(run, monkeypatch, tmp_path): no_reads(monkeypatch) with pytest.raises(RunInputsError, match="CTRL/rep1/z.tif is not an image of this run"): run.he_tissue_mask(f"{UNIT}/z.tif", output_mask_id="HETissue") - with pytest.raises(ValueError, match="known rules are he_tissue_v1"): - run.he_tissue_mask(IMAGE, output_mask_id="HETissue", rule="he_tissue_v2") + with pytest.raises(ValueError, match="known rules are he_tissue_v1, he_tissue_v2"): + run.he_tissue_mask(IMAGE, output_mask_id="HETissue", rule="he_tissue_v3") # A list of rules is a clear TypeError, not an unhashable one (issue #345). - with pytest.raises(TypeError, match="The rule is one ID, a str such as he_tissue_v1; got list"): + with pytest.raises(TypeError, match="a str such as he_tissue_v1, he_tissue_v2; got list"): run.he_tissue_mask(IMAGE, output_mask_id="HETissue", rule=["he_tissue_v1"]) with pytest.raises(TypeError, match="The rule is one ID, a str"): run.preview_he_tissue_mask(IMAGE, rule=["he_tissue_v1"]) @@ -422,7 +422,7 @@ def test_freezing_makes_a_new_mask_under_a_new_id_never_a_relabelled_one( ): provisional = run.he_tissue_mask(IMAGE, output_mask_id="HETissue") before = tree(run.masks_root) - monkeypatch.setitem(helper.RULES, "he_tissue_v1", "frozen") + monkeypatch.setitem(helper.RULES, "he_tissue_v2", "frozen") with pytest.raises(ValueError) as refused: run.he_tissue_mask(IMAGE, output_mask_id="HETissue") assert "differs in: rule, rule_sha256" in str(refused.value) diff --git a/tests/test_he_tissue_rule.py b/tests/test_he_tissue_rule.py index 68732ee9..a23e9a64 100644 --- a/tests/test_he_tissue_rule.py +++ b/tests/test_he_tissue_rule.py @@ -234,8 +234,8 @@ def test_the_rule_record_is_the_designs_and_provisional(): ["remove_pieces_smaller_than_px", 1000], ] assert RULE["connectivity"] == 8 and RULE["disk"] == "x*x + y*y <= r*r" - with pytest.raises(ValueError, match="known rules are he_tissue_v1"): - rule_record("he_tissue_v2", hed_source="x", hed_sha256="0" * 64) + with pytest.raises(ValueError, match="known rules are he_tissue_v1, he_tissue_v2"): + rule_record("he_tissue_v3", hed_source="x", hed_sha256="0" * 64) # B4: the boundary table of §1 ----------------------------------------------------------------- diff --git a/tests/test_he_tissue_v2.py b/tests/test_he_tissue_v2.py new file mode 100644 index 00000000..e8b4a98e --- /dev/null +++ b/tests/test_he_tissue_v2.py @@ -0,0 +1,178 @@ +"""The rule ``he_tissue_v2``: ``he_tissue_v1`` on the plane rescaled to its own white (v0.10.1). + +``he_tissue_v1`` fixes the white at 255. On scans whose glass is grey (Zenodo 4550300's TMA +cores: glass near (127, 135, 145)) every pixel reads as stained, ``H >= 0.05`` everywhere, and +v1 keeps 0 % ("nothing kept: an empty region"). v2 estimates the white per channel as the median +of the brightest 0.1 % of pixels (by ``R + G + B``), rescales with normalization's +``rescale_to_white`` and applies v1's components unchanged. + +- the record: v1's components, version 2, the white stated; v1's record unchanged; +- the estimate, against a plain re-statement of its definition; +- v2 is exactly v1 on the rescaled plane, and v1 itself when the brightest pixels are white; +- a crop of a real core (``tests/data/he_core_1B_D9_crop.npz``, CC-BY-4.0, see + ``tests/data/make_he_core_crop.py``): v1 keeps 0 %, v2 a plausible tissue share, through the + array route and through a run whose TIFF is tagged MINISBLACK with the RGB header override; +- blank slides, white or grey glass: nothing kept. +""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +import numpy as np +import pytest + +pytest.importorskip("skimage") + +from morphobricks_normalization.optical_density import check_white, rescale_to_white # noqa: E402 + +from he_tissue_tree import ( # noqa: E402 + IDENTITY_PATCH, + UNIT, + identities, + pi_style, + rgb_run, + synthetic_he, + threshold_image, +) +from morphobricks_preprocessing import he_tissue_mask as helper # noqa: E402 +from morphobricks_preprocessing import he_tissue_mask_array # noqa: E402 +from morphobricks_preprocessing.he_tissue_rule import ( # noqa: E402 + DEFAULT_RULE, + estimate_white, + rule_record, +) + +CROP = Path(__file__).parent / "data" / "he_core_1B_D9_crop.npz" +CROP_SHA256 = "1d6f85da792938f00b9d64f61016e9a4fbc0cd5981240bf37d6de3f6353dfd14" + + +def record(rule): + return rule_record(rule, hed_source="skimage.color.hed_from_rgb", hed_sha256="0" * 64) + + +def core_crop(): + rgb = np.load(CROP)["rgb"] + assert hashlib.sha256(rgb.tobytes()).hexdigest() == CROP_SHA256 + return rgb + + +def blank(colour, noise, seed=0): + rng = np.random.default_rng(seed) + pixels = rng.normal(colour, noise, (256, 256, 3)) if noise else np.full((256, 256, 3), colour) + return np.clip(np.rint(pixels), 0, 255).astype(np.uint8) + + +# The record ------------------------------------------------------------------------------------- + + +def test_v2_is_v1s_components_with_the_white_estimated(): + v1, v2 = record("he_tissue_v1"), record("he_tissue_v2") + assert DEFAULT_RULE == "he_tissue_v2" + assert (v2["id"], v2["version"], v2["status"]) == ("he_tissue", 2, "provisional") + assert v2["components"] == v1["components"] # no threshold or size changed + assert v2["colour"] == v1["colour"] and v2["combine"] == v1["combine"] + assert v2["input"] == {"image_type": "rgb", "dtype": "uint8", "white": "estimated"} + assert "99.9" in v2["white"]["estimate"] and "median" in v2["white"]["estimate"] + assert v2["white"]["rescale"]["function"] == ( + "morphobricks_normalization.optical_density.rescale_to_white" + ) + # v1 is unchanged: its white fixed, no estimate. + assert v1["version"] == 1 and v1["input"]["white"] == [255, 255, 255] and "white" not in v1 + + +# The estimate ----------------------------------------------------------------------------------- + + +@pytest.mark.parametrize("seed", [0, 1, 2]) +def test_the_white_is_the_median_of_the_brightest_tenth_of_a_percent(seed): + rgb = np.random.default_rng(seed).integers(0, 256, (97, 131, 3), dtype=np.uint8) + flat = rgb.reshape(-1, 3).astype(np.int64) + sums = flat.sum(axis=1) + ordered = np.sort(sums) + position = 0.999 * (len(ordered) - 1) # NumPy's "linear" percentile, written out + below = int(np.floor(position)) + limit = ordered[below] + (position - below) * (ordered[below + 1] - ordered[below]) + expected = tuple(float(np.median(flat[sums >= limit][:, c])) for c in range(3)) + assert estimate_white(rgb) == expected + + +def test_the_white_is_at_least_1_and_a_uniform_plane_is_its_own_white(): + assert estimate_white(np.zeros((8, 8, 3), np.uint8)) == (1.0, 1.0, 1.0) + assert estimate_white(np.full((8, 8, 3), (127, 135, 145), np.uint8)) == (127.0, 135.0, 145.0) + + +# v2 = v1 on the rescaled plane ------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "image", + ["crop", "threshold", "pi1", "pi3", "synthetic"], +) +def test_v2_is_v1_on_the_plane_rescaled_to_its_white(image): + rgb = { + "crop": core_crop, + "threshold": lambda: threshold_image()[0], + "pi1": lambda: pi_style("pi1"), + "pi3": lambda: pi_style("pi3"), + "synthetic": lambda: synthetic_he()[0], + }[image]() + rescaled, _ = rescale_to_white(rgb, check_white(estimate_white(rgb))) + v2 = he_tissue_mask_array(rgb, rule="he_tissue_v2") + v1 = he_tissue_mask_array(rescaled, rule="he_tissue_v1") + assert np.array_equal(v2.mask, v1.mask) + assert dict(v2.record.fractions) == dict(v1.record.fractions) + + +def test_v2_is_v1_itself_when_the_brightest_pixels_are_white(): + rgb = pi_style("pi2") + rgb[:40, :40] = 255 # glass at full white + assert estimate_white(rgb) == (255.0, 255.0, 255.0) + v1 = he_tissue_mask_array(rgb, rule="he_tissue_v1") + v2 = he_tissue_mask_array(rgb, rule="he_tissue_v2") + assert np.array_equal(v1.mask, v2.mask) + + +def test_the_preview_states_the_white_it_rescaled_to(): + rgb = core_crop() + pixels = np.ascontiguousarray(np.moveaxis(rgb, -1, 0)) + v2 = helper.rule_on_plane(pixels, helper.current_rule("he_tissue_v2"), image="crop") + v1 = helper.rule_on_plane(pixels, helper.current_rule("he_tissue_v1"), image="crop") + assert v2.white == estimate_white(rgb) and v1.white is None + assert np.array_equal(v2.rgb, pixels) # the plane read, not the rescaled one + + +# The regression: a real core -------------------------------------------------------------------- + + +def test_v1_keeps_nothing_on_a_grey_glass_core_and_v2_keeps_its_tissue(): + rgb = core_crop() + v1 = he_tissue_mask_array(rgb, rule="he_tissue_v1").record.fractions + assert v1["kept"] == 0.0 and v1["nuclei"] == 1.0 # the reported failure + v2 = he_tissue_mask_array(rgb).record.fractions # the default rule + assert 0.25 <= v2["kept"] <= 0.6 # 0.350: stroma kept + assert 0.3 <= v2["background"] <= 0.7 # 0.515: the glass and the lumen + assert 0.05 <= v2["nuclei"] <= 0.3 # 0.135 + assert v2["red_cells"] < 0.01 + + +@pytest.mark.parametrize( + ("colour", "noise"), + [((255, 255, 255), 0), ((242, 242, 244), 2), ((127, 135, 145), 2), ((127, 135, 145), 0)], +) +def test_a_blank_slide_keeps_nothing(colour, noise): + found = he_tissue_mask_array(blank(colour, noise)) + assert found.record.fractions["kept"] < 0.01 + + +def test_the_run_route_with_the_header_override_keeps_the_cores_tissue(tmp_path, monkeypatch): + monkeypatch.setattr(IDENTITY_PATCH, lambda: identities()) + rgb = core_crop() + # The scanner wrote MINISBLACK for its R, G, B samples: read with the RGB header override. + run = rgb_run(tmp_path, {"a.tif": rgb}, override=True, scanner={"a.tif"}) + result = run.he_tissue_mask(f"{UNIT}/a.tif", output_mask_id="HETissue") + assert result.record["rule"]["version"] == 2 + assert result.record["rgb_header_override"]["image"]["override"] == "used" + assert 0.25 <= result.fractions["kept"] <= 0.6 + assert dict(result.fractions) == dict(he_tissue_mask_array(rgb).record.fractions) diff --git a/tests/test_notebook_tissue_mask.py b/tests/test_notebook_tissue_mask.py index 17c74729..fcd965c1 100644 --- a/tests/test_notebook_tissue_mask.py +++ b/tests/test_notebook_tissue_mask.py @@ -91,7 +91,7 @@ def test_the_preview_writes_nothing_and_shows_the_shares_and_notes(tmp_path, mon ) text = card.numbers.value assert "kept 80.4 % · nuclei 1.6 % · red cells 0.8 % · empty 17.2 %" in text - assert "Sizes are in pixels. Fixed rule he_tissue_v1 (provisional)" in text + assert "Sizes are in pixels. Fixed rule he_tissue_v2 (provisional)" in text assert "this mask will not be reused on retry" in text # an unverified identity From 57338fd701491bac6e87b66c30f76ca3618dea22 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:39:30 +0000 Subject: [PATCH 04/25] Record the owner's decisions of the v0.10.1 CLI fixes (plan question 93) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp983bS22og2asjnEc8P --- docs/plan.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/plan.md b/docs/plan.md index a391f787..592e05fb 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -1819,3 +1819,12 @@ Raised during review; to be decided before the milestones that need them: hashes is `RUN_FOLDER_CONTENT_NOT_RECORDED` (ahead of the ADR, Spec issue 84); masks stay `fingerprint` for now (the run records no mask hash; a separate issue). +93. How should the command line close the gaps a new user met before the next brick (v0.10.1, + pull request 620)? *Decided (owner, 3 December 2026):* the image-type suggestion of `check` + and `run` follows the published description when it declares every acquisition `rgb` (no + marker is written into OME-Zarr copies: OME-NGFF 0.4 has no colour field); an image type + recorded by an earlier run still comes before the suggestion (`--image-type`, then the + recorded type, then the suggestion); `describe --rgb-header-override [FOLDER]` stays one + option, without a folder for every acquisition, with a folder (repeatable, relative to the + experiment) for that one; `check` reports an undeclared mask type as an error, as `run` + refuses it, and exits with status 1. From c065049d4b8e21c7717186e06560f05a1f638fd5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:53:50 +0000 Subject: [PATCH 05/25] Entry identity: warn only after the record is written; force the editable fix - write_entry_record warned before the exclusive open, so a record that was not written (one already there) still said the output was written; the warning now follows the write. - The fix for an editable library said pip install "==", which pip skips as already satisfied; it now forces the reinstall (--force-reinstall --no-deps), as the RECORD-missing fix does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp98tSnytZ9QCrHt6297 --- src/morphobricks_preprocessing/entry_errors.py | 7 +++++-- src/morphobricks_preprocessing/entry_record.py | 5 +++-- tests/test_entry_identity.py | 3 ++- tests/test_entry_record.py | 12 ++++++++++++ 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/morphobricks_preprocessing/entry_errors.py b/src/morphobricks_preprocessing/entry_errors.py index 29ae5af0..46f1cfa2 100644 --- a/src/morphobricks_preprocessing/entry_errors.py +++ b/src/morphobricks_preprocessing/entry_errors.py @@ -243,7 +243,9 @@ def uncertain_code_fix( why (``"editable install"`` or ``"RECORD missing"``, from :func:`.entry_identity.library_identity`). The ADR's text names the brick; telling the user to reinstall a brick that is already a - released install would not help, so the fix names the library instead. + released install would not help, so the fix names the library instead. Both library + fixes force the reinstall: pip leaves an installed version that already satisfies the + pin (an editable one included) as it is. """ if library is None: return ( @@ -262,7 +264,8 @@ def uncertain_code_fix( ) return ( f"The library {name} is an editable install; {brick} itself needs no change. Install a " - f'released {name} (pip install "{pinned}"), or give another --output.' + f'released {name} (pip install --force-reinstall --no-deps "{pinned}"), or give ' + "another --output." ) diff --git a/src/morphobricks_preprocessing/entry_record.py b/src/morphobricks_preprocessing/entry_record.py index 502b419b..2daa7c69 100644 --- a/src/morphobricks_preprocessing/entry_record.py +++ b/src/morphobricks_preprocessing/entry_record.py @@ -286,14 +286,15 @@ def write_entry_record(folder: str | os.PathLike, record: Mapping) -> Path: """ data = _plain(record) _checked(data, Path(folder) / ENTRY_FILENAME) - if (message := identity_warning(data)) is not None: - warnings.warn(message, EntryIdentityWarning, stacklevel=2) text = json.dumps(data, sort_keys=True, ensure_ascii=False, indent=1) + "\n" path = Path(folder) / ENTRY_FILENAME with open(path, "x", encoding="utf-8", newline="\n") as handle: handle.write(text) handle.flush() os.fsync(handle.fileno()) + # Only once the record is on disk: the warning says the output is written. + if (message := identity_warning(data)) is not None: + warnings.warn(message, EntryIdentityWarning, stacklevel=2) return path diff --git a/tests/test_entry_identity.py b/tests/test_entry_identity.py index 53f49b64..2d1eb0dc 100644 --- a/tests/test_entry_identity.py +++ b/tests/test_entry_identity.py @@ -72,7 +72,8 @@ def test_the_fix_for_the_brick_itself_is_the_adrs(): ) editable = uncertain_code_fix("fakepkg", ("lib", "1.0", "editable install")) assert editable.startswith("The library lib is an editable install; fakepkg itself") - assert 'pip install "lib==1.0"' in editable + # A plain install of the same version would be "already satisfied": pip must reinstall. + assert 'pip install --force-reinstall --no-deps "lib==1.0"' in editable def test_an_uncertain_brick_comes_before_its_libraries(): diff --git a/tests/test_entry_record.py b/tests/test_entry_record.py index 27d608fe..403aba22 100644 --- a/tests/test_entry_record.py +++ b/tests/test_entry_record.py @@ -173,6 +173,18 @@ def test_a_first_run_under_an_uncertain_identity_is_published_and_never_reused(r entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(3,)) +def test_no_warning_when_the_record_is_not_written(run, tmp_path): + editable = dict(BRICK, uncertain="demo: editable install") + record = _record(run, brick=editable) + folder = tmp_path / "out" + folder.mkdir() + (folder / entry.ENTRY_FILENAME).write_text("{}", encoding="utf-8") + with warnings.catch_warnings(): + warnings.simplefilter("error", entry.EntryIdentityWarning) + with pytest.raises(FileExistsError): + entry.write_entry_record(folder, record) + + def test_a_certain_first_run_warns_nothing(run): with warnings.catch_warnings(): warnings.simplefilter("error", entry.EntryIdentityWarning) From 2da8c1767954802c2b5c66505cfd785082682123 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 16:57:42 +0000 Subject: [PATCH 06/25] Fix the review findings of the CLI usability changes - The shared run/check texts no longer name a describe option; describe adds its own command-line line, and the override hint appears only for images it can lift (PhysicalIssue.override_fits). - check's discovery_report.json records R_MASK_TYPE_NOT_DECLARED; the mask fix is shell-quoted. - --rgb-header-override: without --channels says what is missing; the bare form mixed with folders is refused. - --accept-ids leaves ID questions without a proposal open; counts use plural(). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp983bS22og2asjnEc8P --- CHANGELOG.md | 17 ++-- docs/user_guide.md | 15 ++-- src/morphobricks_preprocessing/cli.py | 2 +- .../cli_describe.py | 72 ++++++++++++---- .../description_run_text.py | 26 +++--- .../physical_fast.py | 11 ++- .../physical_unit.py | 36 ++++++-- .../run/check_step.py | 8 +- tests/test_cli_usability.py | 83 ++++++++++++++++++- 9 files changed, 212 insertions(+), 58 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fe35195..7302b312 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,16 +20,18 @@ environment test of the v0.10.0 wave, 3 December 2026). No format change. levels), as the draft does. - **`check` reports an undeclared mask type** (an OME-Zarr label image, for example) as `run` refuses it, `R_MASK_TYPE_NOT_DECLARED` with the same message and fix - (`physical_check.undeclared_mask_types`, shared); it exits with status 1. The message no + (`physical_check.undeclared_mask_types`, shared); it exits with status 1, and the report it + writes records the error too. The message no longer says "the masks folder" for label images, and its fix names the type found - (`--type cells=REPRESENTATION`), never a guessed representation. + (`--type cells=REPRESENTATION`, shell-quoted), never a guessed representation. - **`declare-masks` names the right next commands:** without `--masks` it no longer prints `run --masks MASKS`; OME-Zarr label images and masks beside the images need no masks folder, and the experiment folder is named (`EXPERIMENT`) only when no run of the output folder records it. - **Fast `describe` prints "N open questions (answered by you, in the notebook)" only when questions remain:** with `--accept-ids`, `--comparable` and `--confirmed-on` it says the - options answer them; otherwise it lists only the questions left, naming the options. + options answer them; otherwise it lists only the questions left, naming the options (an ID + with no proposal stays open: `--accept-ids` cannot answer it). Counts use `plural`. - **The image-type suggestion of `check` and `run` follows the published description** when it declares every acquisition `rgb` and RGB is possible (`image_type.declared_image_type`, `review_image_type(..., declared=)`). An OME-Zarr copy written by @@ -44,9 +46,12 @@ environment test of the v0.10.0 wave, 3 December 2026). No format change. `rgb_header_override = true` on every acquisition, or on the acquisition folders named (repeatable), exactly as the notebook's Image type card does, for colour scanner TIFFs whose header says *minisblack* (for example the Zenodo 4550300 cores). Refused with a channel list, - an unknown folder, a published description or `--strict`. The refusal of such images - (`R_FAST_LAYOUT_CONTRADICTION` and `R_IMAGE_TYPE_CONTRADICTS_HEADER`) now names the option - beside the notebook card. + an unknown folder, a published description or `--strict`. Both forms + together are refused, and so is the option without `--channels` (the message says what is + missing). The fast-mode refusal of such images (`R_FAST_LAYOUT_CONTRADICTION`) names the RGB + header override once in its action (from a flag set when the issue is built, never a search + of the text), and `describe` adds a line naming the option; the shared texts that `run` also + prints name only the notebook, since a published description is changed there. - **`convert --store ome-zarr`** writes every image that is read as an OME-Zarr copy (OME-NGFF 0.4, `.ome.zarr`), as `convert_experiment(..., store="ome-zarr")` and the notebook do; RGB TIFFs included. Default `ome-tiff`, as before. The user guide (§5) shows the H&E route: diff --git a/docs/user_guide.md b/docs/user_guide.md index af6519f8..9e7e6a45 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1116,7 +1116,8 @@ output says so. **Colour scanner files whose header does not say colour.** Some scanners (and some public H&E datasets) store red, green and blue as three interleaved samples per pixel under the TIFF photometric interpretation *minisblack*. Fast mode then refuses them -(`R_FAST_LAYOUT_CONTRADICTION`, `image_type`), and the message names the fix. If the three +(`R_FAST_LAYOUT_CONTRADICTION`, `image_type`): the suggested action names the RGB header +override, and `describe` adds a line naming this option. If the three samples are red, green and blue in this order, say so with `--rgb-header-override`: ```bash @@ -1125,11 +1126,13 @@ morphobricks-preprocessing describe /data/he_cores --channels R,G,B --image-type ``` Without a folder the statement covers every acquisition; `--rgb-header-override tumour/rep1` -(repeatable, an acquisition folder relative to the experiment) covers only that one. It records +(repeatable, an acquisition folder relative to the experiment) covers only that one; both forms +together are refused. Give the experiment folder before the option, or it is taken as the +folder. It records `rgb_header_override = true` on those acquisitions, exactly as the notebook's Image type card does (see `R_IMAGE_TYPE_CONTRADICTS_HEADER` in §8); an image that is not three interleaved -samples is still refused (`R_RGB_OVERRIDE_NOT_THREE_SAMPLES`). The option needs `--image-type -rgb`, and it is a statement of a new fast-mode description only: a published description, or +samples is still refused (`R_RGB_OVERRIDE_NOT_THREE_SAMPLES`). The option needs `--channels R,G,B --image-type +rgb` (without `--channels` the command says so and writes nothing), and it is a statement of a new fast-mode description only: a published description, or the strict mode, records it in the notebook. ### Stating pixel sizes (`calibrate`) @@ -1663,8 +1666,8 @@ continues. | `partial_channel_coverage` | Warning | A biological repeat has a stain in only some of its imaging units (for example one technical repeat imaged an extra stain); the message counts imaging units (`rep1: PHASE in 1 of 2 imaging units`). The images are measured as acquired (the stain is blank where it was not acquired) and the coverage is in the manifest. Later analyses that pool the stain over the whole repeat refuse it (`A_SCOPE_INCOMPLETE`) unless you choose the imaging units that have it; that refusal counts images ("present in 2 of 4 images"). | | `R_MASK_CONTRADICTS_REPRESENTATION` | Error | The masks step found a file of a mask declared `binary` that is stored as floats, or holds, over all its planes together, a negative value or two or more different positive values (the message names the file and the values found, or its pixel type). A binary mask holds 0 and at most one positive value (an all-zero or all-foreground file is accepted), stored as integers or true/false. Declare the mask as `instances` in the description if every value is an object, or as `parent_labels` (grouped labels) if every value is one group, such as the mitochondria of one cell; or fix the file (save a float mask as integers). The file stays `not yet checked`, so an analysis that names the mask refuses it (`A_MASK_UNCHECKED`) without reading it. | | `R_UNIT_NOT_FOUND`, `R_UNIT_NOT_DECLARED`, `R_UNIT_NOT_HOMOGENEOUS`, `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER`, `R_MASK_TYPE_NOT_DECLARED` | Error | The published description and the folder or the image headers disagree (the message says where). Correct the description, publish it again and run again. | -| `R_IMAGE_TYPE_CONTRADICTS_HEADER` for colour scanner files, `R_RGB_OVERRIDE_NOT_THREE_SAMPLES`, `E_RGB_OVERRIDE_WITHOUT_RGB` | Error | Some scanners store colour (RGB) images with a header that does not say RGB (for example TIFF photometric *minisblack* with three samples per pixel). The acquisition declared `image_type = "rgb"` is then refused, and the message says so and names `rgb_header_override`. If the three samples are red, green and blue in this order, add `rgb_header_override = true` to that acquisition in `morphobricks.toml` (beside `image_type = "rgb"`; in the notebook, tick **Read these folders as colour (RGB) although their header does not say colour** on the Image type card of the Channels step; on the command line, for a new fast-mode description, `describe ... --image-type rgb --channels R,G,B --rgb-header-override`, §5) and publish again: the run then accepts the header and records the acquisition in the manifest as declared RGB with the header overridden (`image_type_header_overridden`, `header_photometric`). Every image whose header does not say RGB must have exactly three interleaved samples per pixel, else `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` names the image (reported before `R_UNIT_NOT_HOMOGENEOUS`); the key on an acquisition that is not declared `rgb` is `E_RGB_OVERRIDE_WITHOUT_RGB`. Images of the acquisition that differ only in colour interpretation (some *minisblack*, some RGB) are then one layout. Images whose header already says RGB, or whose format states no colour interpretation (OME-Zarr), do not use the key; the manifest records, per image, whether it was used (`rgb_header_override_images`). Adding, removing or changing the key reopens the "same way" confirmation of that replicate. Only headers are read, never pixels. | -| `R_FAST_LAYOUT_CONTRADICTION` | Error | The published description is in **fast mode** (it has a `channel_layout` table: "every imaging unit has the same channels in the same order", Spec ADR 0006) and some images of the acquisitions that follow it (`channels_from = "experiment"`) contradict that list. One message lists **every** contradicting image, with its FOV key (condition, repeat and acquisition folders, then the image name) and path, and every contradiction found in it: `image_type` (the header says colour where the list is not, or the reverse), `channel_count` (another number of channels), `header_order` (header names of the list in another order) or `header_names` (a header name that is no confirmed name of any channel of the list), each with its C index and what was expected and found. It is decided from the image headers only, before any pixel is read; nothing is reordered, dropped or guessed, and nothing was processed. Tag the acquisitions of these images on their own (`channels_from = "unit"`, confirmed per acquisition), publish again and run again. When the contradiction is an `image_type` of colour scanner files whose header does not say colour (three interleaved samples), the message names the RGB header override instead: `describe ... --image-type rgb --channels R,G,B --rgb-header-override [FOLDER]` (§5), or the notebook's Image type card. An image whose header gives no channel names (or an empty name) needs no evidence and follows the list; the manifest records each image of a fast acquisition in `fast_layout_images` (`header_verified` true only when every channel was confirmed by its header name). In such acquisitions this one code replaces `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER` and `R_UNIT_NOT_HOMOGENEOUS` (which stays for the other axes); `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` keeps its priority. An acquisition tagged on its own is checked as in a description without fast mode. Experiments with extra channels in some acquisitions are refused here: tag those acquisitions on their own. | +| `R_IMAGE_TYPE_CONTRADICTS_HEADER` for colour scanner files, `R_RGB_OVERRIDE_NOT_THREE_SAMPLES`, `E_RGB_OVERRIDE_WITHOUT_RGB` | Error | Some scanners store colour (RGB) images with a header that does not say RGB (for example TIFF photometric *minisblack* with three samples per pixel). The acquisition declared `image_type = "rgb"` is then refused, and the message says so and names `rgb_header_override`. If the three samples are red, green and blue in this order, add `rgb_header_override = true` to that acquisition in `morphobricks.toml` (beside `image_type = "rgb"`; in the notebook, tick **Read these folders as colour (RGB) although their header does not say colour** on the Image type card of the Channels step; on the command line, only while a new fast-mode description is published, `describe ... --image-type rgb --channels R,G,B --rgb-header-override`, §5; a published description is changed in the notebook) and publish again: the run then accepts the header and records the acquisition in the manifest as declared RGB with the header overridden (`image_type_header_overridden`, `header_photometric`). Every image whose header does not say RGB must have exactly three interleaved samples per pixel, else `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` names the image (reported before `R_UNIT_NOT_HOMOGENEOUS`); the key on an acquisition that is not declared `rgb` is `E_RGB_OVERRIDE_WITHOUT_RGB`. Images of the acquisition that differ only in colour interpretation (some *minisblack*, some RGB) are then one layout. Images whose header already says RGB, or whose format states no colour interpretation (OME-Zarr), do not use the key; the manifest records, per image, whether it was used (`rgb_header_override_images`). Adding, removing or changing the key reopens the "same way" confirmation of that replicate. Only headers are read, never pixels. | +| `R_FAST_LAYOUT_CONTRADICTION` | Error | The published description is in **fast mode** (it has a `channel_layout` table: "every imaging unit has the same channels in the same order", Spec ADR 0006) and some images of the acquisitions that follow it (`channels_from = "experiment"`) contradict that list. One message lists **every** contradicting image, with its FOV key (condition, repeat and acquisition folders, then the image name) and path, and every contradiction found in it: `image_type` (the header says colour where the list is not, or the reverse), `channel_count` (another number of channels), `header_order` (header names of the list in another order) or `header_names` (a header name that is no confirmed name of any channel of the list), each with its C index and what was expected and found. It is decided from the image headers only, before any pixel is read; nothing is reordered, dropped or guessed, and nothing was processed. Tag the acquisitions of these images on their own (`channels_from = "unit"`, confirmed per acquisition), publish again and run again. When the contradiction is an `image_type` of colour scanner files whose header does not say colour (three interleaved samples), the suggested action names the RGB header override instead (`rgb_header_override = true`, the notebook's Image type card), once; while a new description is published from the command line, `describe` also names `--rgb-header-override [FOLDER]` (§5). An image whose header gives no channel names (or an empty name) needs no evidence and follows the list; the manifest records each image of a fast acquisition in `fast_layout_images` (`header_verified` true only when every channel was confirmed by its header name). In such acquisitions this one code replaces `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER` and `R_UNIT_NOT_HOMOGENEOUS` (which stays for the other axes); `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` keeps its priority. An acquisition tagged on its own is checked as in a description without fast mode. Experiments with extra channels in some acquisitions are refused here: tag those acquisitions on their own. | | `folder_and_id_changed` | Error | *Check and save* (and publication) found an ID changed in the same save as a folder change of the same entity: for example a repeat ID `Day1 -> DayX` while one of its folders was renamed or removed, a condition ID changed while its folder was renamed, or a removed folder's ID typed for the new folder. Neither change is guessed from the other, so the message names the entity, its saved ID and its folders. Undo the ID edit: put the saved ID back (the folder change then saves on its own). A removed folder's ID stays used and is not given to another folder (experiment-v1 4.9). Nothing was published. | | `R_DRAFT_CHANGED` | Error | Notebook: `morphobricks.draft.json` was changed since this notebook read or saved it (another notebook, or a program, saved its own answers in the same output folder). Nothing was saved or published, and the answers saved there are kept. Press **Check folder** in step 1 to read them, then give your change again. | | `R_DRAFT_EXISTS` | Error | Command line (`describe --publish`): the output folder holds `morphobricks.draft.json`, answers saved in the notebook that the command does not read. Nothing was published or written. Finish those answers and publish them in the notebook (step 1, **Check folder**, then **Check and save**), or, if they are not wanted, remove or archive that file yourself and run the command again. | diff --git a/src/morphobricks_preprocessing/cli.py b/src/morphobricks_preprocessing/cli.py index 4e1760d5..4db3a546 100644 --- a/src/morphobricks_preprocessing/cli.py +++ b/src/morphobricks_preprocessing/cli.py @@ -321,7 +321,7 @@ def _check(args: argparse.Namespace) -> int: f"Suggested image type: {type_review.suggested}, because {type_review.reason}. " "'run' uses it unless you give --image-type." ) - path, refusal = write_check_report(pre, args.output, review) + path, refusal = write_check_report(pre, args.output, review, extra=undeclared) print() print(format_issues([refusal]) if refusal else f"Report written to {path}" if path else "") blocked = not pre.ok or axis_errors or undeclared or refusal is not None diff --git a/src/morphobricks_preprocessing/cli_describe.py b/src/morphobricks_preprocessing/cli_describe.py index e26d3f17..61f83bbd 100644 --- a/src/morphobricks_preprocessing/cli_describe.py +++ b/src/morphobricks_preprocessing/cli_describe.py @@ -59,7 +59,7 @@ ) from .description_run_text import physical_issues from .discovery import DiscoveryResult, default_output_folder, discover_experiment -from .draft import Draft, DraftError, draft_from_discovery +from .draft import Draft, DraftError, OpenQuestion, draft_from_discovery from .draft_answers import DraftAnswers, description_from_draft, valid_day from .draft_ids import IdKind, id_problems from .fast_answers import fast_answers, tagged_unit @@ -71,7 +71,7 @@ from .run.description_file import PublicationRefused, publish_description from .run.description_run import load_description, without_global_channel_checks from .run.recorded import normalise_relative_path -from .validation import has_errors +from .validation import has_errors, plural FAST_HINT = ( "\nFast mode is the default for a new description (one channel list for the experiment, " @@ -79,6 +79,15 @@ "--comparable, --confirmed-on and --publish; --strict tags each acquisition on its own in " "the notebook." ) +OVERRIDE_NEEDS_CHANNELS = ( + "--rgb-header-override needs the colour channel list of a new fast-mode description: " + "add --channels R,G,B --image-type rgb. Nothing was written." +) +OVERRIDE_CLI = ( + "On the command line: describe again with --rgb-header-override (every acquisition) or " + "--rgb-header-override FOLDER (that acquisition folder, repeatable), if their three " + "samples are R, G and B in this order." +) OVERRIDE_ONLY_FAST = ( "--rgb-header-override is a statement of a new fast-mode description (with --channels " "R,G,B --image-type rgb); a published description, or the strict mode, records it in the " @@ -198,7 +207,8 @@ def _add_fast_options(describe: argparse.ArgumentParser) -> None: const=True, default=[], metavar="FOLDER", - help="fast mode, with --image-type rgb: the images of this acquisition folder (relative " + help="fast mode, with --image-type rgb (give the experiment folder before this " + "option, or it is taken as FOLDER): the images of this acquisition folder (relative " "to the experiment, for example CTRL/rep1; repeatable; without a folder: every " "acquisition) store R, G and B as three interleaved samples per pixel although their " "TIFF header does not say colour. Records rgb_header_override = true on those units, " @@ -235,8 +245,9 @@ def describe_command(args: argparse.Namespace) -> int: lines, blockers = draft_lines(draft, root), draft_blockers(draft) if not args.strict: lines.append(FAST_HINT) - if args.rgb_header_override: - print(OVERRIDE_ONLY_FAST) + if args.rgb_header_override: # never silently ignored + new_fast = found is None and not args.strict + print(OVERRIDE_NEEDS_CHANNELS if new_fast else OVERRIDE_ONLY_FAST) return 1 print("\n".join(lines)) if not args.publish: @@ -334,10 +345,18 @@ def override_units( (leaf) folder relative to the experiment, with ``/`` (or Windows) separators. """ leaves = {leaf.relative_path: leaf.labels for leaf in discovery.leaves} - if any(value is True for value in given): - rows = draft.unit_rows() - return sorted({(r.condition, r.biological_repeat, r.technical_repeat) for r in rows}), [] found, unknown = set(), [] + every = any(value is True for value in given) + if every and len(given) > 1: # a folder beside "every acquisition" is never dropped + unknown.append( + "--rgb-header-override is given both without a folder (every acquisition) and with " + "folders: give one or the other" + ) + if every: + rows = draft.unit_rows() + return sorted({(r.condition, r.biological_repeat, r.technical_repeat) for r in rows}), ( + unknown + ) for value in given: folder = str(value).replace("\\", "/").strip("/") or "." if folder in leaves: @@ -376,6 +395,8 @@ def _publish_fast( report = check_physical(candidate, discovery, headers) if report.issues: print(format_issues(physical_issues(report.issues))) + if any(issue.override_fits for issue in report.issues): + print(OVERRIDE_CLI) return 1 if report.unchecked: # every image's count and type checked, never a guessed count print( @@ -417,29 +438,44 @@ def _fast_question_lines(draft: Draft, args: argparse.Namespace) -> list[str]: says that they are answered in the notebook. """ dated = args.confirmed_on is not None and valid_day(args.confirmed_on) + unproposed = _unproposed(draft) questions = draft.open_questions() - left = [ - q - for q in questions - if not (args.accept_ids if q.code == "id_pending" else args.comparable and dated) - ] + left = [q for q in questions if not _answered(q, args, dated, unproposed)] if not questions: return ["", "No question is open."] if not left: return [ "", - f"The draft's {len(questions)} open questions are answered by your options " - "(--accept-ids, --comparable, --confirmed-on).", + f"The draft's {plural(len(questions), 'open question')} are answered by your " + "options (--accept-ids, --comparable, --confirmed-on).", ] out = [ "", - f"{len(left)} open questions (answer them with --accept-ids, --comparable and " - "--confirmed-on YYYY-MM-DD, or in the notebook):", + f"{plural(len(left), 'open question')} (answer them with --accept-ids, --comparable " + "and --confirmed-on YYYY-MM-DD, or in the notebook):", ] out += [f" - {QUESTION_TEXT[q.code].format(subject=q.subject)}" for q in left] return out +def _unproposed(draft: Draft) -> set[str]: + """Return the ID questions with no proposal: --accept-ids cannot answer them.""" + out = {f"condition {k}" for k, slot in draft.conditions.items() if slot.proposed is None} + out |= { + f"technical repeat {k}" + for k, slot in draft.technical_repeats.items() + if slot.proposed is None + } + return out | {f"repeat {k}" for k, rep in draft.repeats.items() if rep.id.proposed is None} + + +def _answered(q: OpenQuestion, args: argparse.Namespace, dated: bool, unproposed: set) -> bool: + """Return whether the fast-mode options answer one open question of the draft.""" + if q.code == "id_pending": + return args.accept_ids and q.subject not in unproposed + return args.comparable and dated + + def draft_lines(draft: Draft, root: Path, *, questions: bool = True) -> list[str]: """Return the plain-language report of a draft. @@ -481,7 +517,7 @@ def _question_lines(draft: Draft) -> list[str]: questions = draft.open_questions() if not questions: return ["", "No question is open."] - out = ["", f"{len(questions)} open questions (answered by you, in the notebook):"] + out = ["", f"{plural(len(questions), 'open question')} (answered by you, in the notebook):"] out += [f" - {QUESTION_TEXT[q.code].format(subject=q.subject)}" for q in questions] return out diff --git a/src/morphobricks_preprocessing/description_run_text.py b/src/morphobricks_preprocessing/description_run_text.py index 07e64944..98876083 100644 --- a/src/morphobricks_preprocessing/description_run_text.py +++ b/src/morphobricks_preprocessing/description_run_text.py @@ -8,6 +8,7 @@ from __future__ import annotations +import shlex from collections.abc import Iterable from .channel_plan import channel_coverage, partial_repeats @@ -34,7 +35,6 @@ PhysicalIssue, UnitKey, ) -from .physical_unit import OVERRIDE_HOW from .type_names import type_name from .validation import ValidationIssue, error, warning @@ -53,6 +53,14 @@ } +OVERRIDE_FIX = ( + "Images that store R, G and B as three interleaved samples under a header that does not " + "say colour need no own tags: declare the RGB header override on their acquisitions " + "instead (rgb_header_override = true; the notebook's Image type card)." +) +"""The fix of a type contradiction the RGB header override would accept (RH1), said once.""" + + def unit_text(key: UnitKey | None) -> str: """Name a unit by its folders: condition, biological repeat and acquisition.""" if key is None: @@ -94,7 +102,8 @@ def physical_issue(issue: PhysicalIssue) -> ValidationIssue: paths = () if issue.path is None else (issue.path,) action = _ACTIONS.get(issue.code, FIX) if issue.code == MASK_TYPE_NOT_DECLARED: # the type found, never a guessed representation - action = action.replace("TYPE=REPRESENTATION", f"{issue.detail}=REPRESENTATION") + typed = shlex.quote(f"{issue.detail}=REPRESENTATION") + action = action.replace("TYPE=REPRESENTATION", typed) return error(issue.code, _what(issue), paths, action) @@ -112,17 +121,8 @@ def fast_layout_issue(issues: Iterable[PhysicalIssue]) -> ValidationIssue: } units = sorted({unit_text(i.unit) for i in issues if i.code == FAST_LAYOUT_CONTRADICTION}) action = f"{FAST_FIX} Units: " + "; ".join(units) + "." - if any( - "rgb_header_override" in item.found - for issue in issues - if issue.code == FAST_LAYOUT_CONTRADICTION - for item in issue.contradictions - ): - action += ( - " Images that store R, G and B as three interleaved samples under a header that " - "does not say colour need no own tags: declare the RGB header override instead " - f"({OVERRIDE_HOW})." - ) + if any(i.override_fits for i in issues if i.code == FAST_LAYOUT_CONTRADICTION): + action += f" {OVERRIDE_FIX}" paths = [path for _, path in listed] return error(FAST_LAYOUT_CONTRADICTION, contradiction_message(listed), paths, action) diff --git a/src/morphobricks_preprocessing/physical_fast.py b/src/morphobricks_preprocessing/physical_fast.py index 422e9a22..af8c7295 100644 --- a/src/morphobricks_preprocessing/physical_fast.py +++ b/src/morphobricks_preprocessing/physical_fast.py @@ -20,6 +20,7 @@ Layout, PhysicalIssue, UnitKey, + override_fits, type_issue, unit_images, unnamed_positions, @@ -89,8 +90,16 @@ def _fast_issue( if not found: return None detail = "; ".join(item.text() for item in found) + fits = typed is not None and override_fits(unit, layout, meta) return PhysicalIssue( - FAST_LAYOUT_CONTRADICTION, key, path, position_id(path), None, detail, found + FAST_LAYOUT_CONTRADICTION, + key, + path, + position_id(path), + None, + detail, + found, + override_fits=fits, ) diff --git a/src/morphobricks_preprocessing/physical_unit.py b/src/morphobricks_preprocessing/physical_unit.py index 70df0f0d..af7673d0 100644 --- a/src/morphobricks_preprocessing/physical_unit.py +++ b/src/morphobricks_preprocessing/physical_unit.py @@ -50,6 +50,11 @@ class PhysicalIssue: contradictions: tuple[Contradiction, ...] = () """For ``R_FAST_LAYOUT_CONTRADICTION``: every contradiction of the image with the experiment list, in the order of the kinds (:mod:`.fast_layout`); empty for every other code.""" + override_fits: bool = False + """True when the image type contradiction is one the RGB header override would accept: a + unit declared ``rgb`` without the override, a TIFF header that does not say colour, and + three interleaved samples per pixel (:func:`override_fits`). Set when the issue is built, + so the texts never search a message for it.""" @dataclass(frozen=True) @@ -96,11 +101,19 @@ def layout_of( return Layout(count, tuple(meta.raw_channel_names), meta.rgb_samples or rgb, axes) -OVERRIDE_HOW = ( - "describe EXPERIMENT ... --image-type rgb --channels R,G,B --rgb-header-override FOLDER, " - "or Image type in the notebook" -) -"""How the user declares the RGB header override (the command line's option, the notebook).""" +def override_fits(declared: Unit, layout: Layout, meta: TiffMetadata) -> bool: + """Return whether the RGB header override would accept this image's type contradiction. + + The unit is declared ``rgb`` without ``rgb_header_override``, the image is a TIFF whose + header does not say colour, and it stores three interleaved samples per pixel (RH1). + """ + return ( + meta.kind != OME_ZARR + and declared.image_type == RGB + and not declares_override(declared) + and not layout.rgb + and meta.interleaved_samples == OVERRIDE_SAMPLES + ) def type_issue(declared: Unit, layout: Layout, meta: TiffMetadata) -> tuple[str, str] | None: @@ -130,8 +143,7 @@ def type_issue(declared: Unit, layout: Layout, meta: TiffMetadata) -> tuple[str, what += ( f" (photometric {meta.photometric or 'not stated'}) but stores " f"{OVERRIDE_SAMPLES} interleaved samples per pixel: if they are R, G and B in this " - "order, declare rgb_header_override = true on this unit (experiment-v1 4.4b: " - f"{OVERRIDE_HOW})" + "order, declare rgb_header_override = true on this unit (experiment-v1 4.4b)" ) return IMAGE_TYPE_CONTRADICTS_HEADER, what @@ -142,7 +154,15 @@ def type_issues( """Compare the declared image type with each header that states a colour interpretation.""" found = ((path, type_issue(declared, layout, metas[path])) for path, layout in layouts.items()) return [ - PhysicalIssue(issue[0], key, path, position_id(path), None, issue[1]) + PhysicalIssue( + issue[0], + key, + path, + position_id(path), + None, + issue[1], + override_fits=override_fits(declared, layouts[path], metas[path]), + ) for path, issue in found if issue is not None ] diff --git a/src/morphobricks_preprocessing/run/check_step.py b/src/morphobricks_preprocessing/run/check_step.py index d0452fcf..5ba61271 100644 --- a/src/morphobricks_preprocessing/run/check_step.py +++ b/src/morphobricks_preprocessing/run/check_step.py @@ -9,6 +9,7 @@ from __future__ import annotations import os +from collections.abc import Sequence from dataclasses import replace from pathlib import Path @@ -78,6 +79,7 @@ def write_check_report( pre: Preflight, output_folder: str | os.PathLike | None = None, review: AxisReview | None = None, + extra: Sequence[ValidationIssue] = (), ) -> tuple[Path | None, ValidationIssue | None]: """Write the report of ``check`` (status ``"stopped"``) to the output folder. @@ -92,6 +94,9 @@ def write_check_report( The output folder; defaults to :func:`.discovery.default_output_folder`. review The axis review of the suggested roles, or None. + extra + Further issues ``check`` found besides the preflight's (an undeclared mask type, + ``R_MASK_TYPE_NOT_DECLARED``), recorded in the report with them. Returns ------- @@ -113,7 +118,8 @@ def write_check_report( reported = {issue.code for issue in pre.issues} return None, next((i for i in inside_masks if i.code not in reported), None) output.mkdir(parents=True, exist_ok=True) - report = build_report(pre, output, pre.issues, review=review, outcome=RunOutcome("check")) + issues = [*pre.issues, *extra] + report = build_report(pre, output, issues, review=review, outcome=RunOutcome("check")) try: with output_lock(output): return write_report(report, output), None diff --git a/tests/test_cli_usability.py b/tests/test_cli_usability.py index 7845e6b4..f14629cb 100644 --- a/tests/test_cli_usability.py +++ b/tests/test_cli_usability.py @@ -100,11 +100,43 @@ def test_a_minisblack_rgb_contradiction_names_the_describe_option(tmp_path, caps assert main(["describe", str(root), "--output", str(out), *COLOUR, "--publish"]) == 1 text = capsys.readouterr().out assert "R_FAST_LAYOUT_CONTRADICTION" in text or "contradict the experiment" in text - assert "--rgb-header-override FOLDER" in text - assert "declare the RGB header override instead" in text # in the suggested action + assert "--rgb-header-override FOLDER" in text # describe's own line + assert text.count("declare the RGB header override") == 1 # the action, once + assert text.count("On the command line: describe again with --rgb-header-override") == 1 assert not (out / DESCRIPTION_FILENAME).exists() +def test_an_image_the_override_cannot_lift_gets_no_override_hint(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + _scanner(root / "a" / "x.tif") + path = root / "b" / "y.tif" # four interleaved samples: never R, G and B + path.parent.mkdir(parents=True) + tifffile.imwrite( + path, + np.zeros((8, 8, 4), np.uint8), + photometric="minisblack", + planarconfig="contig", + metadata={"axes": "YXS"}, + ) + command = ["describe", str(root), "--output", str(out), *COLOUR, "--publish"] + assert main([*command, "--rgb-header-override"]) == 1 + text = capsys.readouterr().out + assert "R_RGB_OVERRIDE_NOT_THREE_SAMPLES" in text or "not three interleaved" in text + assert "declare the RGB header override" not in text and "On the command line" not in text + + +def test_the_texts_run_shares_never_name_the_describe_option(tmp_path): + from morphobricks_preprocessing.description_run_text import physical_issue + from morphobricks_preprocessing.physical_unit import ( + IMAGE_TYPE_CONTRADICTS_HEADER, + PhysicalIssue, + ) + + issue = PhysicalIssue(IMAGE_TYPE_CONTRADICTS_HEADER, None, "a.tif", "a", None, "x") + text = physical_issue(issue).message + physical_issue(issue).action + assert "--rgb-header-override" not in text + + def test_rgb_header_override_for_every_unit_is_recorded_as_the_notebook_records_it(tmp_path): root, out = _scanner_tree(tmp_path / "exp"), tmp_path / "out" command = ["describe", str(root), "--output", str(out), *COLOUR, "--publish"] @@ -141,10 +173,29 @@ def test_rgb_header_override_refuses_an_unknown_folder_and_a_channel_list(tmp_pa assert not out.exists() -def test_rgb_header_override_outside_a_new_fast_description_is_refused(tmp_path, capsys): +def test_rgb_header_override_without_channels_says_what_is_missing(tmp_path, capsys): root, out = _scanner_tree(tmp_path / "exp"), tmp_path / "out" assert main(["describe", str(root), "--output", str(out), "--rgb-header-override"]) == 1 + assert "add --channels R,G,B --image-type rgb" in capsys.readouterr().out + assert not out.exists() + + +def test_rgb_header_override_in_strict_mode_or_on_a_published_file_is_refused(tmp_path, capsys): + root, out = _scanner_tree(tmp_path / "exp"), tmp_path / "out" + command = ["describe", str(root), "--output", str(out)] + assert main([*command, "--strict", "--rgb-header-override"]) == 1 + assert "statement of a new fast-mode description" in capsys.readouterr().out + assert main([*command, *COLOUR, "--rgb-header-override", "--publish"]) == 0 + capsys.readouterr() + assert main([*command, "--rgb-header-override"]) == 1 assert "statement of a new fast-mode description" in capsys.readouterr().out + + +def test_rgb_header_override_refuses_every_acquisition_and_folders_together(tmp_path, capsys): + root, out = _scanner_tree(tmp_path / "exp"), tmp_path / "out" + command = ["describe", str(root), "--output", str(out), *COLOUR, "--publish"] + assert main([*command, "--rgb-header-override", "--rgb-header-override", "tumor"]) == 1 + assert "give one or the other" in capsys.readouterr().out assert not out.exists() @@ -179,6 +230,19 @@ def test_check_reports_an_undeclared_ome_zarr_label_mask_as_run_refuses_it(tmp_p for text in (checked, ran): assert message in text and action in text assert "--type TYPE=instances" not in checked # no representation is suggested for you + import json + + report = json.loads((out / "discovery_report.json").read_text()) + assert "R_MASK_TYPE_NOT_DECLARED" in json.dumps(report) # the check's report records it + + +def test_an_undeclared_mask_type_with_a_space_is_quoted_in_the_fix(): + from morphobricks_preprocessing.description_run_text import physical_issue + from morphobricks_preprocessing.physical_check import MASK_TYPE_NOT_DECLARED + from morphobricks_preprocessing.physical_unit import PhysicalIssue + + issue = physical_issue(PhysicalIssue(MASK_TYPE_NOT_DECLARED, None, detail="Cell outlines")) + assert "--type 'Cell outlines=REPRESENTATION'" in issue.action def test_declare_masks_without_a_masks_folder_names_no_placeholder_folder(tmp_path, capsys): @@ -219,11 +283,22 @@ def test_fast_describe_lists_open_questions_only_while_some_remain(tmp_path, cap partial = ["--channels", "DNA,ACTIN", "--image-type", "channels", "--accept-ids"] assert main(["describe", str(root), "--output", str(tmp_path / "o2"), *partial]) == 0 text = capsys.readouterr().out - assert "1 open questions (answer them with --accept-ids, --comparable" in text + assert "1 open question (answer them with --accept-ids, --comparable" in text assert "confirm that the folders of repeat rep1" in text assert "choose the ID" not in text # --accept-ids answered those +def test_an_id_with_no_proposal_stays_open_under_accept_ids(tmp_path, capsys): + root = tmp_path / "exp" + for condition in ("files", "DrugB"): # files is no ID: nothing is proposed + _ome(root / condition / "rep1" / "img.ome.tif") + command = ["describe", str(root), "--output", str(tmp_path / "out"), *CHANNELS] + assert main(command) in (0, 1) + text = capsys.readouterr().out + assert "are answered by your options" not in text + assert "1 open question (answer them" in text and "files" in text + + # --- 5. and 6. RGB as OME-Zarr: convert --store ome-zarr, then the suggestion --------------- From 1345159b2437090ad5c88410f1c89fa1d4228168 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 17:17:22 +0000 Subject: [PATCH 07/25] Keep he_tissue_mask.py under the 600-line rule v2's rescaling moves to he_tissue_rule.white_rescaled, and the lineage's run facts (the RGB header override item, the recorded pixel size) move to the new module he_tissue_run_facts (orchestration layer). No behaviour change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AEzaRH4WH1TyJRA61 --- AGENTS.md | 3 +- pyproject.toml | 1 + .../he_tissue_mask.py | 61 ++++--------------- .../he_tissue_rule.py | 17 ++++++ .../he_tissue_run_facts.py | 40 ++++++++++++ 5 files changed, 71 insertions(+), 51 deletions(-) create mode 100644 src/morphobricks_preprocessing/he_tissue_run_facts.py diff --git a/AGENTS.md b/AGENTS.md index 12931ef8..09cfface 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -381,7 +381,8 @@ src/morphobricks_preprocessing/ lineage line and own retry comparator; he_tissue_rule.py the fixed rules he_tissue_v1 and he_tissue_v2 (the default: v1 on the plane rescaled to its white, estimate_white; both provisional) as canonical records, computed from - their record + their record; he_tissue_run_facts.py the run facts of its lineage line + (the RGB header override item, the recorded pixel size) (SciPy clean-up, 8-connected, disks clipped by the border); code_identity.py the verified code identity (RECORD digest, PEP 610); lineage_schema.py the reader's dispatch by operation and the duplicate-key refusal; diff --git a/pyproject.toml b/pyproject.toml index ffde5b95..44d4b17e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -440,6 +440,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.code_identity" = "io" "morphobricks_preprocessing.he_tissue_rule" = "pure" "morphobricks_preprocessing.he_tissue_mask" = "orchestration" +"morphobricks_preprocessing.he_tissue_run_facts" = "orchestration" "morphobricks_preprocessing.he_tissue_array" = "orchestration" "morphobricks_preprocessing.run_inputs_tissue" = "orchestration" "morphobricks_preprocessing.cli_tissue_mask" = "ui" diff --git a/src/morphobricks_preprocessing/he_tissue_mask.py b/src/morphobricks_preprocessing/he_tissue_mask.py index 0e969629..15979ef9 100644 --- a/src/morphobricks_preprocessing/he_tissue_mask.py +++ b/src/morphobricks_preprocessing/he_tissue_mask.py @@ -25,11 +25,9 @@ **Colour maths: normalization's, never reimplemented.** ``E`` and ``H`` are ``stain.to_scalar(rgb, axes="CYX", preset="he_eosin")``'s ``image`` and ``exclusion``; the per-channel optical density is ``optical_density(rgb_yxc(rgb, "CYX"), check_white((255, 255, -255)))``, unpacked as ``(od, od_floored)``. Under ``he_tissue_v2`` both are computed on the -plane rescaled to its estimated white by normalization's ``rescale_to_white`` -(:func:`.he_tissue_rule.estimate_white`); the white is in the preview, not in the lineage -line, whose ``source.content_sha256`` and rule record determine it. The HED matrix is only -looked up by the preset's own name for it, to hash it into the rule record. +255)))``, unpacked as ``(od, od_floored)``; under ``he_tissue_v2``, of the plane rescaled to its +white (:func:`.he_tissue_rule.white_rescaled`). The HED matrix is only looked up by the +preset's own name for it, to hash it into the rule record. **Output and publication.** The file goes to ``///.tif`` with its line of ``mask_lineage.jsonl`` (the BM15 schema, @@ -59,11 +57,7 @@ import numpy as np import scipy from morphobricks_normalization import stain -from morphobricks_normalization.optical_density import ( - check_white, - optical_density, - rescale_to_white, -) +from morphobricks_normalization.optical_density import check_white, optical_density from morphobricks_normalization.scalar_inputs import rgb_yxc from .code_identity import code_identity @@ -73,11 +67,11 @@ PROVISIONAL, RULES, TissueComponents, - estimate_white, - estimates_white, rule_record, tissue_components, + white_rescaled, ) +from .he_tissue_run_facts import override_record, pixel_size_record from .image_names import position_id from .lineage_schema import BM15_LINE_KEYS, CODE_KEYS, EXPERIMENT_ROOT, rule_sha256 from .mask_conversion import _check_case_collision, _check_output_id, _digest_of @@ -172,8 +166,7 @@ class TissueMaskPreview: code The two code identities; ``reusable`` is True only when both are verified. white - The white the plane was rescaled to before ``E``, ``H`` and ``od`` (``he_tissue_v2``), - R, G, B; ``None`` for a rule with the fixed white 255 (``he_tissue_v1``). + The white ``E``, ``H`` and ``od`` were measured against (v2), or ``None`` (v1: 255). """ image: str @@ -481,17 +474,9 @@ def rule_on_plane( Every route calls it (the run route through :func:`_compute`, after its read, and ``he_tissue_mask_array`` on its array moved to ``(3, Y, X)``), so their masks are one computation, never a copy. The caller has checked the plane and the rule - (:func:`current_rule`). ``image`` labels the plane in the result. A rule that estimates - the white (``he_tissue_v2``) rescales the plane to it with normalization's - ``rescale_to_white`` first; ``E``, ``H`` and ``od`` are then of the rescaled plane. + (:func:`current_rule`). ``image`` labels the plane in the result. """ - white = None - measured = pixels - if estimates_white(record): - rgb = rgb_yxc(pixels, SOURCE_AXES) - white = estimate_white(rgb) - rescaled, _clipped = rescale_to_white(rgb, check_white(white)) - measured = np.ascontiguousarray(np.moveaxis(rescaled, -1, 0)) + measured, white = white_rescaled(pixels, record) scalar = stain.to_scalar(measured, axes=SOURCE_AXES, preset=PRESET) od, od_floored = _optical_density(measured) components = tissue_components(scalar.image, scalar.exclusion, od, record) @@ -534,30 +519,6 @@ def _optical_density(pixels: np.ndarray) -> tuple[np.ndarray, float]: return od, floored -def _override(run: RunInputs, found: Fov) -> dict[str, object]: - """Return the unit's declared RGB header override and this image's recorded item.""" - recorded = run.manifest.experiment_description or {} - for unit in recorded.get("units", ()): - key = (unit.get("repeat"), unit.get("condition"), unit.get("technical_repeat")) - if key == (found.repeat_group, found.condition_id, found.technical_repeat_id): - items = unit.get("rgb_header_override_images", ()) - image = next((i for i in items if i.get("image") == found.relative_path), None) - return {"declared": unit.get("rgb_header_override") is True, "image": image} - raise RunInputsError(f"The run records no unit for {found.relative_path}. Run it again.") - - -def _pixel_size(run: RunInputs, image: str) -> dict | None: - """Return the recorded X and Y sizes (information only), or None when neither has one.""" - sizes = run.pixel_sizes(image) - found = {role: sizes.get(role) for role in ("X", "Y")} - if all(size is None or size.value is None for size in found.values()): - return None - return { - role: None if size is None else {k: v for k, v in size.to_dict().items() if k != "role"} - for role, size in found.items() - } - - def _planned( run: RunInputs, found: Fov, relative: str, output_id: str, record: Mapping[str, Any] ) -> dict: @@ -577,8 +538,8 @@ def _planned( "scikit_image_version": skimage_module().__version__, "scipy_version": scipy.__version__, "image_type": found.image_type, - "rgb_header_override": _override(run, found), - "pixel_size": _pixel_size(run, found.relative_path), + "rgb_header_override": override_record(run, found), + "pixel_size": pixel_size_record(run, found.relative_path), "fractions": None, "helper": HELPER, "helper_version": __version__, diff --git a/src/morphobricks_preprocessing/he_tissue_rule.py b/src/morphobricks_preprocessing/he_tissue_rule.py index e15f194c..f0d01dcd 100644 --- a/src/morphobricks_preprocessing/he_tissue_rule.py +++ b/src/morphobricks_preprocessing/he_tissue_rule.py @@ -48,6 +48,7 @@ from dataclasses import dataclass import numpy as np +from morphobricks_normalization.optical_density import check_white, rescale_to_white from scipy import ndimage PROVISIONAL = "provisional" @@ -200,6 +201,22 @@ def estimate_white(rgb: np.ndarray) -> tuple[float, float, float]: return tuple(float(value) for value in white) +def white_rescaled( + pixels: np.ndarray, rule: Mapping[str, object] +) -> tuple[np.ndarray, tuple[float, float, float] | None]: + """Return the ``uint8`` ``(3, Y, X)`` plane a rule measures, and the white it rescaled to. + + A rule that estimates the white (v2) rescales the plane to :func:`estimate_white` with + normalization's ``rescale_to_white``; any other returns ``pixels`` itself and ``None``. + """ + if not estimates_white(rule): + return pixels, None + rgb = np.moveaxis(pixels, 0, -1) + white = estimate_white(rgb) + rescaled, _clipped = rescale_to_white(rgb, check_white(white)) + return np.ascontiguousarray(np.moveaxis(rescaled, -1, 0)), white + + def disk(radius: int) -> np.ndarray: """Return the boolean disk ``x*x + y*y <= r*r`` of side ``2 r + 1``.""" yy, xx = np.mgrid[-radius : radius + 1, -radius : radius + 1] diff --git a/src/morphobricks_preprocessing/he_tissue_run_facts.py b/src/morphobricks_preprocessing/he_tissue_run_facts.py new file mode 100644 index 00000000..dd5c0a06 --- /dev/null +++ b/src/morphobricks_preprocessing/he_tissue_run_facts.py @@ -0,0 +1,40 @@ +"""What the H&E tissue mask's lineage line records about the run (Spec ADR 0005 BM15). + +Moved from :mod:`.he_tissue_mask` (v0.10.1, its 600-line limit): the unit's declared RGB header +override with this image's recorded item (copied unchanged, never decided again; design §2), and +the image's recorded X and Y pixel sizes, for information only (sizes in the rule are pixels). +Nothing here reads a pixel. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .run_inputs_error import RunInputsError + +if TYPE_CHECKING: + from .run_inputs import Fov, RunInputs + + +def override_record(run: RunInputs, found: Fov) -> dict[str, object]: + """Return the unit's declared RGB header override and this image's recorded item.""" + recorded = run.manifest.experiment_description or {} + for unit in recorded.get("units", ()): + key = (unit.get("repeat"), unit.get("condition"), unit.get("technical_repeat")) + if key == (found.repeat_group, found.condition_id, found.technical_repeat_id): + items = unit.get("rgb_header_override_images", ()) + image = next((i for i in items if i.get("image") == found.relative_path), None) + return {"declared": unit.get("rgb_header_override") is True, "image": image} + raise RunInputsError(f"The run records no unit for {found.relative_path}. Run it again.") + + +def pixel_size_record(run: RunInputs, image: str) -> dict | None: + """Return the recorded X and Y sizes (information only), or None when neither has one.""" + sizes = run.pixel_sizes(image) + found = {role: sizes.get(role) for role in ("X", "Y")} + if all(size is None or size.value is None for size in found.values()): + return None + return { + role: None if size is None else {k: v for k, v in size.to_dict().items() if k != "role"} + for role, size in found.items() + } From 0ca1565eef655d714a175d7173e792c7c03c7dac Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 07:49:29 +0000 Subject: [PATCH 08/25] describe --id FOLDER=ID: name any folder's ID in fast mode A folder whose name cannot be an ID (control, files) was a dead end on the command line. --id FOLDER=ID (repeatable) names it, checked with the notebook's own rules (Draft.confirm_id); a refusal names the option to give again. The open-question line offers only the options that can answer what is left, never --accept-ids for an ID with no proposal. The question texts move to describe_questions.py (cli_describe stays under 600 lines). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9ASFzYU5CY2vs1ReWg --- pyproject.toml | 2 + .../cli_describe.py | 143 +++++++----------- .../describe_ids.py | 99 ++++++++++++ .../describe_questions.py | 134 ++++++++++++++++ .../fast_answers.py | 73 ++++++--- tests/test_cli_usability.py | 82 +++++++++- 6 files changed, 419 insertions(+), 114 deletions(-) create mode 100644 src/morphobricks_preprocessing/describe_ids.py create mode 100644 src/morphobricks_preprocessing/describe_questions.py diff --git a/pyproject.toml b/pyproject.toml index 44d4b17e..0579651a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -347,6 +347,8 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.fast_layout" = "pure" "morphobricks_preprocessing.fast_statement" = "pure" "morphobricks_preprocessing.fast_answers" = "pure" +"morphobricks_preprocessing.describe_ids" = "pure" +"morphobricks_preprocessing.describe_questions" = "pure" "morphobricks_preprocessing.description" = "pure" "morphobricks_preprocessing.description_write" = "pure" "morphobricks_preprocessing.fov_identity" = "pure" diff --git a/src/morphobricks_preprocessing/cli_describe.py b/src/morphobricks_preprocessing/cli_describe.py index 61f83bbd..f49ecfad 100644 --- a/src/morphobricks_preprocessing/cli_describe.py +++ b/src/morphobricks_preprocessing/cli_describe.py @@ -27,9 +27,10 @@ **Fast mode (Spec ADR 0006, owner decision FC1) is the default for a new description.** With ``--channels`` (the tagged unit's channel IDs in order), ``--image-type``, ``--accept-ids``, -``--comparable`` and ``--confirmed-on``, every answer is the user's, stated in the command -(:mod:`.fast_answers`), and ``--publish`` publishes a fast-mode file in one command after every -image's header was checked against the list (a contradiction lists every image, +``--comparable`` and ``--confirmed-on``, every answer is the user's (``--id FOLDER=ID`` names +the ID of a folder that has no proposal, such as ``control``: :mod:`.describe_ids`), stated in +the command (:mod:`.fast_answers`), and ``--publish`` publishes a fast-mode file in one command +after every image's header was checked against the list (a contradiction lists every image, ``R_FAST_LAYOUT_CONTRADICTION``, and nothing is written). ``--rgb-header-override [FOLDER]`` states that colour scanner TIFFs whose header does not say colour are R, G and B (recorded as ``rgb_header_override = true`` on those units, as the notebook records it). The open questions @@ -46,6 +47,8 @@ import argparse from pathlib import Path +from .describe_ids import apply_ids +from .describe_questions import fast_question_lines, proposal, question_blockers, question_lines from .description import Description, DescriptionError from .description_reconcile import ( CHANNELS_CHANGED, @@ -59,9 +62,8 @@ ) from .description_run_text import physical_issues from .discovery import DiscoveryResult, default_output_folder, discover_experiment -from .draft import Draft, DraftError, OpenQuestion, draft_from_discovery +from .draft import Draft, DraftError, draft_from_discovery from .draft_answers import DraftAnswers, description_from_draft, valid_day -from .draft_ids import IdKind, id_problems from .fast_answers import fast_answers, tagged_unit from .metadata import inspect_images from .name_issues import non_nfc_folders_issue @@ -71,7 +73,7 @@ from .run.description_file import PublicationRefused, publish_description from .run.description_run import load_description, without_global_channel_checks from .run.recorded import normalise_relative_path -from .validation import has_errors, plural +from .validation import has_errors FAST_HINT = ( "\nFast mode is the default for a new description (one channel list for the experiment, " @@ -93,16 +95,10 @@ "R,G,B --image-type rgb); a published description, or the strict mode, records it in the " "notebook (Channels, Image type). Nothing was written." ) -QUESTION_TEXT = { - "id_pending": "choose the ID of {subject} (accept the proposal or type another)", - "repeat_not_confirmed": ( - "confirm that the folders of {subject} were prepared and acquired under the same " - "circumstances, so they are comparable" - ), - "confirmed_on_missing": "{subject} is confirmed but has no date: confirm it again", -} -"""What the user must do for each open question of a draft, in plain words.""" - +ID_ONLY_NEW = ( + "--id names the IDs of a new fast-mode description; a published description, or the " + "strict mode, names them in the notebook. Nothing was written." +) NOT_IN_DRAFT = ( "the channels of each acquisition, the image type and the meaning of the masks are not " "part of this draft and are answered in the notebook; the command line cannot publish " @@ -189,6 +185,16 @@ def _add_fast_options(describe: argparse.ArgumentParser) -> None: describe.add_argument( "--accept-ids", action="store_true", help="fast mode: accept every proposed ID" ) + describe.add_argument( + "--id", + action="append", + default=[], + metavar="FOLDER=ID", + help="fast mode: the ID of a condition, biological-repeat or technical-repeat folder, " + "as you type it (repeatable), for example --id control=ctrl for a folder whose name " + "cannot be an ID; checked with the notebook's rules. A label used at two levels takes " + "the level: condition:FOLDER, repeat:FOLDER or technical:FOLDER", + ) describe.add_argument( "--comparable", action="store_true", @@ -238,13 +244,18 @@ def describe_command(args: argparse.Namespace) -> int: if found is not None: lines, blockers = _published(found.description, discovery, excluded, output) else: - draft = draft_from_discovery(discovery, excluded) + draft = _named(args, draft_from_discovery(discovery, excluded)) + if draft is None: + return 1 if not args.strict and args.channels is not None: lines = draft_lines(draft, root, questions=False) return describe_fast(args, draft, discovery, excluded, output, lines) lines, blockers = draft_lines(draft, root), draft_blockers(draft) if not args.strict: lines.append(FAST_HINT) + if found is not None and args.id: # never silently ignored + print(ID_ONLY_NEW) + return 1 if args.rgb_header_override: # never silently ignored new_fast = found is None and not args.strict print(OVERRIDE_NEEDS_CHANNELS if new_fast else OVERRIDE_ONLY_FAST) @@ -267,6 +278,19 @@ def describe_command(args: argparse.Namespace) -> int: return 1 +def _named(args: argparse.Namespace, draft: Draft) -> Draft | None: + """Return the draft with the IDs ``--id`` names, or None after printing every refusal.""" + if args.id and args.strict: + print(ID_ONLY_NEW) + return None + named, refusals = apply_ids(draft, args.id) + if refusals: + print("Nothing was written. These IDs cannot be used:") + print("\n".join(f" - {item}" for item in refusals)) + return None + return named + + def describe_fast( args: argparse.Namespace, draft: Draft, @@ -294,7 +318,13 @@ def describe_fast( names = () if tagged is None else tuple(tagged.raw_channel_names) lines = [ *lines, - *_fast_question_lines(draft, args), + *fast_question_lines( + draft, + accept_ids=args.accept_ids, + comparable=args.comparable, + dated=args.confirmed_on is not None and valid_day(args.confirmed_on), + named=bool(args.id), + ), "", "Fast mode (the default; --strict for the per-unit mode): one channel list for the " "experiment, the order of the tagged unit " @@ -421,61 +451,6 @@ def _publish_fast( return 0 -def _proposal(kind: IdKind, folder: str, slot_proposed: str | None) -> str: - """Say what is proposed for a folder, or why nothing is.""" - if slot_proposed is not None: - return f"proposed ID {slot_proposed!r}" - why = ", ".join(id_problems(kind, folder)) - return f"no ID can be proposed ({why or 'in use'}): you name it" - - -def _fast_question_lines(draft: Draft, args: argparse.Namespace) -> list[str]: - """Return the draft's questions the fast-mode options leave open, or say none is left. - - ``--accept-ids`` answers every ID question (a folder with no proposal is named when - publishing), ``--comparable`` with a valid ``--confirmed-on`` every repeat question. The - questions are listed only while some remain, so a command that answers them all never - says that they are answered in the notebook. - """ - dated = args.confirmed_on is not None and valid_day(args.confirmed_on) - unproposed = _unproposed(draft) - questions = draft.open_questions() - left = [q for q in questions if not _answered(q, args, dated, unproposed)] - if not questions: - return ["", "No question is open."] - if not left: - return [ - "", - f"The draft's {plural(len(questions), 'open question')} are answered by your " - "options (--accept-ids, --comparable, --confirmed-on).", - ] - out = [ - "", - f"{plural(len(left), 'open question')} (answer them with --accept-ids, --comparable " - "and --confirmed-on YYYY-MM-DD, or in the notebook):", - ] - out += [f" - {QUESTION_TEXT[q.code].format(subject=q.subject)}" for q in left] - return out - - -def _unproposed(draft: Draft) -> set[str]: - """Return the ID questions with no proposal: --accept-ids cannot answer them.""" - out = {f"condition {k}" for k, slot in draft.conditions.items() if slot.proposed is None} - out |= { - f"technical repeat {k}" - for k, slot in draft.technical_repeats.items() - if slot.proposed is None - } - return out | {f"repeat {k}" for k, rep in draft.repeats.items() if rep.id.proposed is None} - - -def _answered(q: OpenQuestion, args: argparse.Namespace, dated: bool, unproposed: set) -> bool: - """Return whether the fast-mode options answer one open question of the draft.""" - if q.code == "id_pending": - return args.accept_ids and q.subject not in unproposed - return args.comparable and dated - - def draft_lines(draft: Draft, root: Path, *, questions: bool = True) -> list[str]: """Return the plain-language report of a draft. @@ -489,18 +464,19 @@ def draft_lines(draft: Draft, root: Path, *, questions: bool = True) -> list[str "Conditions (folder: proposal)", ] out += [ - f" {folder}: {_proposal('conditions', folder, slot.proposed)}" + f" {folder}: {proposal('conditions', folder, slot.proposed, slot.confirmed)}" for folder, slot in sorted(draft.conditions.items()) ] out += ["", "Technical repeats (folder: proposal)"] out += [ - f" {folder}: {_proposal('technical_repeats', folder, slot.proposed)}" + f" {folder}: {proposal('technical_repeats', folder, slot.proposed, slot.confirmed)}" for folder, slot in sorted(draft.technical_repeats.items()) ] out += ["", "Biological repeats"] for group, repeat in sorted(draft.repeats.items()): state = f"confirmed on {repeat.confirmed_on}" if repeat.confirmed else "not confirmed" - out.append(f" {group}: {_proposal('repeats', group, repeat.id.proposed)}; {state}") + said = proposal("repeats", group, repeat.id.proposed, repeat.id.confirmed) + out.append(f" {group}: {said}; {state}") out += [ f" {m.condition} / {m.source_repeat}: {m.image_count} images" for m in repeat.members ] @@ -508,24 +484,13 @@ def draft_lines(draft: Draft, root: Path, *, questions: bool = True) -> list[str out += ["", "References (condition is compared against)"] out += [f" {c} -> {r}" for c, r in sorted(draft.references.items())] if questions: - out += _question_lines(draft) - return out - - -def _question_lines(draft: Draft) -> list[str]: - """Return what the user still has to answer, one line each.""" - questions = draft.open_questions() - if not questions: - return ["", "No question is open."] - out = ["", f"{plural(len(questions), 'open question')} (answered by you, in the notebook):"] - out += [f" - {QUESTION_TEXT[q.code].format(subject=q.subject)}" for q in questions] + out += question_lines(draft) return out def draft_blockers(draft: Draft) -> list[str]: """Return everything that stops this draft from being published, in plain words.""" - blockers = [QUESTION_TEXT[q.code].format(subject=q.subject) for q in draft.open_questions()] - return blockers or [NOT_IN_DRAFT] + return question_blockers(draft) or [NOT_IN_DRAFT] def _published( diff --git a/src/morphobricks_preprocessing/describe_ids.py b/src/morphobricks_preprocessing/describe_ids.py new file mode 100644 index 00000000..8456a1ba --- /dev/null +++ b/src/morphobricks_preprocessing/describe_ids.py @@ -0,0 +1,99 @@ +"""The IDs ``describe --id FOLDER=ID`` names on the command line (owner, 4 December 2026; pure). + +A condition, biological-repeat or technical-repeat folder whose label cannot be an ID +(``control`` and ``files`` are forbidden names, ``E_FORBIDDEN_FIELD``; experiment-v1 4.7) has +no proposal (:mod:`.draft_ids`): the user names its ID. In the notebook that is a text field; +on the command line it is ``--id control=ctrl`` (repeatable). Each ID is the user's, adopted +exactly as typed and checked with the notebook's own rules (:meth:`.draft.Draft.confirm_id`), +so the command line accepts what the notebook accepts and refuses what it refuses. + +``FOLDER`` is the folder label as the draft lists it. A label that names folders of two +levels (a condition and a technical repeat both called ``a``) needs the level: +``--id condition:a=A``, ``--id repeat:a=A`` or ``--id technical:a=A``. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +from .draft import Draft, DraftError +from .draft_ids import IdKind + +LEVELS: dict[str, IdKind] = { + "condition": "conditions", + "repeat": "repeats", + "technical": "technical_repeats", +} +"""The level prefixes of ``--id`` and the draft table each names.""" +NOUNS: dict[IdKind, str] = { + "conditions": "condition folder", + "repeats": "biological repeat", + "technical_repeats": "technical repeat folder", +} + + +def id_option(folder: str, value: str = "") -> str: + """Return the ``--id`` option that names ``folder``'s ID (```` as a placeholder).""" + return f"--id {folder}={value}" + + +def _keys(draft: Draft, kind: IdKind) -> Sequence[str]: + """Return the labels of one level of the draft.""" + table = { + "conditions": draft.conditions, + "repeats": draft.repeats, + "technical_repeats": draft.technical_repeats, + }[kind] + return tuple(table) + + +def _locate(draft: Draft, folder: str) -> list[tuple[IdKind, str]]: + """Return the (level, label) entries ``folder`` names: a bare label, or ``level:label``.""" + found = [(kind, folder) for kind in LEVELS.values() if folder in _keys(draft, kind)] + level, sep, label = folder.partition(":") + if not found and sep and level in LEVELS and label in _keys(draft, LEVELS[level]): + found = [(LEVELS[level], label)] + return found + + +def apply_ids(draft: Draft, given: Sequence[str]) -> tuple[Draft, list[str]]: + """Return the draft with every ``--id FOLDER=ID`` confirmed, and every refusal in words. + + A refusal names the option to give again; on any refusal the caller publishes nothing. + """ + refusals: list[str] = [] + seen: dict[tuple[IdKind, str], str] = {} + for item in given: + folder, sep, value = item.rpartition("=") + if not sep or not folder or not value: + refusals.append(f"--id {item}: write it as FOLDER=ID, for example --id control=ctrl") + continue + found = _locate(draft, folder) + if not found: + known = sorted({k for kind in LEVELS.values() for k in _keys(draft, kind)}) + refusals.append( + f"--id {item}: {folder!r} is not a condition, biological-repeat or " + f"technical-repeat folder of this experiment (folders: {', '.join(known)})" + ) + continue + if len(found) > 1: + prefixes = [p for p, kind in LEVELS.items() if (kind, folder) in found] + levels = " or ".join(id_option(f"{p}:{folder}", value) for p in prefixes) + refusals.append(f"--id {item}: {folder!r} names folders of two levels: give {levels}") + continue + key = found[0] + if key in seen: + refusals.append(f"--id {item}: {folder!r} is named twice; give one ID") + continue + seen[key] = value + try: + draft = draft.confirm_id(key[0], key[1], value) + except DraftError as exc: + refusals.append( + f"--id {item}: {value!r} cannot be the ID of {NOUNS[key[0]]} {key[1]} " + f"({', '.join(exc.codes) or exc}); give an allowed ID: {id_option(folder)}" + ) + return draft, refusals + + +__all__ = ["LEVELS", "apply_ids", "id_option"] diff --git a/src/morphobricks_preprocessing/describe_questions.py b/src/morphobricks_preprocessing/describe_questions.py new file mode 100644 index 00000000..71452e9c --- /dev/null +++ b/src/morphobricks_preprocessing/describe_questions.py @@ -0,0 +1,134 @@ +"""The open questions ``describe`` prints, and which option answers each one (pure). + +Moved from :mod:`.cli_describe` with ``--id`` (owner, 4 December 2026). A question is listed +with only the options that can answer it: ``--accept-ids`` accepts a proposal, so an ID that +cannot be proposed (``control``, ``files``) is answered by ``--id FOLDER=ID`` alone, and the +line never offers ``--accept-ids`` for it. +""" + +from __future__ import annotations + +from .describe_ids import id_option +from .draft import Draft, OpenQuestion +from .draft_ids import IdKind, id_problems +from .validation import plural + +QUESTION_TEXT = { + "id_pending": "choose the ID of {subject} (accept the proposal or type another)", + "repeat_not_confirmed": ( + "confirm that the folders of {subject} were prepared and acquired under the same " + "circumstances, so they are comparable" + ), + "confirmed_on_missing": "{subject} is confirmed but has no date: confirm it again", +} +"""What the user must do for each open question of a draft, in plain words.""" + + +def proposal(kind: IdKind, folder: str, proposed: str | None, named: str | None = None) -> str: + """Say what is proposed for a folder, the user's ``--id``, or why nothing is proposed.""" + if named is not None: + return f"ID {named!r} (yours, --id)" + if proposed is not None: + return f"proposed ID {proposed!r}" + why = ", ".join(id_problems(kind, folder)) + return f"no ID can be proposed ({why or 'in use'}): you name it ({id_option(folder)})" + + +def unproposed(draft: Draft) -> dict[str, tuple[IdKind, str]]: + """Return the ID questions with no proposal, by subject: --accept-ids cannot answer them.""" + out: dict[str, tuple[IdKind, str]] = { + f"condition {k}": ("conditions", k) + for k, slot in draft.conditions.items() + if slot.proposed is None + } + out |= { + f"technical repeat {k}": ("technical_repeats", k) + for k, slot in draft.technical_repeats.items() + if slot.proposed is None + } + return out | { + f"repeat {k}": ("repeats", k) for k, rep in draft.repeats.items() if rep.id.proposed is None + } + + +def _text(q: OpenQuestion, named_by: dict[str, tuple[IdKind, str]]) -> str: + """Return one open question in words; an unproposable ID names its ``--id`` option.""" + if q.code == "id_pending" and q.subject in named_by: + kind, label = named_by[q.subject] + why = ", ".join(id_problems(kind, label)) or "in use" + return ( + f"name the ID of {q.subject}: {label!r} cannot be one ({why}); give {id_option(label)}" + ) + return QUESTION_TEXT[q.code].format(subject=q.subject) + + +def fast_question_lines( + draft: Draft, *, accept_ids: bool, comparable: bool, dated: bool, named: bool +) -> list[str]: + """Return the draft's questions the fast-mode options leave open, or say none is left. + + ``--accept-ids`` answers every ID question that has a proposal, ``--comparable`` with a + valid ``--confirmed-on`` (``dated``) every repeat question; ``named`` says ``--id`` was + given. The questions are listed only while some remain, each heading naming only the + options that answer what is left. + """ + named_by = unproposed(draft) + questions = draft.open_questions() + left = [ + q + for q in questions + if not ( + (accept_ids and q.subject not in named_by) + if q.code == "id_pending" + else (comparable and dated) + ) + ] + if not questions: + return ["", "No question is open."] + if not left: + given = ["--accept-ids", "--comparable", "--confirmed-on"] + given = ["--id", *given] if named else given + return [ + "", + f"The draft's {plural(len(questions), 'open question')} are answered by your " + f"options ({', '.join(given)}).", + ] + options = [] + if any(q.code == "id_pending" and q.subject in named_by for q in left): + options.append("--id FOLDER=ID") + if any(q.code == "id_pending" and q.subject not in named_by for q in left): + options.append("--accept-ids") + if any(q.code != "id_pending" for q in left): + options.append("--comparable and --confirmed-on YYYY-MM-DD") + out = [ + "", + f"{plural(len(left), 'open question')} (answer them with {', '.join(options)}, " + "or in the notebook):", + ] + return out + [f" - {_text(q, named_by)}" for q in left] + + +def question_lines(draft: Draft) -> list[str]: + """Return what the user still has to answer, one line each (no fast-mode option given).""" + questions = draft.open_questions() + if not questions: + return ["", "No question is open."] + named_by = unproposed(draft) + out = ["", f"{plural(len(questions), 'open question')} (answered by you, in the notebook):"] + return out + [f" - {_text(q, named_by)}" for q in questions] + + +def question_blockers(draft: Draft) -> list[str]: + """Return the draft's open questions as what stops publication, in plain words.""" + named_by = unproposed(draft) + return [_text(q, named_by) for q in draft.open_questions()] + + +__all__ = [ + "QUESTION_TEXT", + "fast_question_lines", + "proposal", + "question_blockers", + "question_lines", + "unproposed", +] diff --git a/src/morphobricks_preprocessing/fast_answers.py b/src/morphobricks_preprocessing/fast_answers.py index f5681123..044f0bb9 100644 --- a/src/morphobricks_preprocessing/fast_answers.py +++ b/src/morphobricks_preprocessing/fast_answers.py @@ -9,7 +9,8 @@ in folder order (named in the output); its header names are confirmed as the channels' ``header_names`` (FC3 evidence), never matched by similarity; - ``--image-type`` is the list's image type, never inferred; -- ``--accept-ids`` accepts every proposed ID (a folder with no proposal stops publication); +- ``--accept-ids`` accepts every proposed ID; ``--id FOLDER=ID`` names one folder's ID (applied + to the draft before, :mod:`.describe_ids`), and a folder with neither stops publication; - ``--comparable`` is the N35 answer for every biological repeat; - ``--confirmed-on`` is the day of those statements, never the clock's; - ``--rgb-header-override`` (with ``--image-type rgb`` only) is the user's statement that the @@ -55,29 +56,64 @@ def tagged_unit(draft: Draft) -> UnitKey | None: def _ids(draft: Draft) -> tuple[dict, dict, dict, list[str]]: - """Return the proposed IDs as answers, and every folder that has no proposal.""" + """Return the IDs as answers (``--id``'s, else the proposal), and every folder with none.""" missing: list[str] = [] conditions = {} for folder, slot in sorted(draft.conditions.items()): - if slot.proposed is None: - missing.append( - f"condition folder {folder!r} has no proposed ID: name it in the notebook" - ) - conditions[folder] = ConditionAnswer(slot.proposed) + chosen = slot.confirmed or slot.proposed + if chosen is None: + missing.append(f"condition folder {folder!r} has no proposed ID: {_name(folder)}") + conditions[folder] = ConditionAnswer(chosen) technical = {} for folder, slot in sorted(draft.technical_repeats.items()): - if slot.proposed is None: - missing.append(f"technical repeat folder {folder!r} has no proposed ID") + chosen = slot.confirmed or slot.proposed + if chosen is None: + missing.append( + f"technical repeat folder {folder!r} has no proposed ID: {_name(folder)}" + ) else: - technical[folder] = slot.proposed + technical[folder] = chosen repeats = {} for label, repeat in sorted(draft.repeats.items()): - if repeat.id.proposed is None: - missing.append(f"repeat {label!r} has no proposed ID") - repeats[label] = RepeatAnswer(repeat.id.proposed) + chosen = repeat.id.confirmed or repeat.id.proposed + if chosen is None: + missing.append(f"repeat {label!r} has no proposed ID: {_name(label)}") + repeats[label] = RepeatAnswer(chosen) return conditions, technical, repeats, missing +def _name(folder: str) -> str: + """Say how the user names an ID that cannot be proposed.""" + return f"name it with --id {folder}= (or in the notebook)" + + +def _all_named(draft: Draft) -> bool: + """Return whether every ID of the draft is already the user's (``--id``).""" + slots = [*draft.conditions.values(), *draft.technical_repeats.values()] + slots += [repeat.id for repeat in draft.repeats.values()] + return all(slot.confirmed is not None for slot in slots) + + +def _statements( + draft: Draft, accept_ids: bool, comparable: bool, confirmed_on: str | None +) -> list[str]: + """Return the user's statements still missing: the IDs, the N35 answer and its day.""" + blockers = [] + if not accept_ids and not _all_named(draft): + blockers.append( + "accept the proposed IDs (--accept-ids), or name them (--id FOLDER=ID, or in the " + "notebook)" + ) + if not comparable: + blockers.append( + "say that every biological repeat's folders were prepared and acquired under the " + "same circumstances (--comparable)" + ) + if confirmed_on is None or not valid_day(confirmed_on): + blockers.append("give the day of your statements as YYYY-MM-DD (--confirmed-on)") + return blockers + + def fast_answers( draft: Draft, channels: Sequence[str], @@ -96,16 +132,7 @@ def fast_answers( ``rgb_override`` are the units the user declares ``rgb_header_override = true`` on (a colour list only; every key must be a unit of the draft). """ - blockers = [] - if not accept_ids: - blockers.append("accept the proposed IDs (--accept-ids), or name them in the notebook") - if not comparable: - blockers.append( - "say that every biological repeat's folders were prepared and acquired under the " - "same circumstances (--comparable)" - ) - if confirmed_on is None or not valid_day(confirmed_on): - blockers.append("give the day of your statements as YYYY-MM-DD (--confirmed-on)") + blockers = _statements(draft, accept_ids, comparable, confirmed_on) if image_type == "rgb" and tuple(channels) != RGB_LIST: blockers.append("a colour (RGB) list is exactly R,G,B (--channels R,G,B)") if rgb_override and image_type != "rgb": diff --git a/tests/test_cli_usability.py b/tests/test_cli_usability.py index f14629cb..ffbc32bc 100644 --- a/tests/test_cli_usability.py +++ b/tests/test_cli_usability.py @@ -283,7 +283,7 @@ def test_fast_describe_lists_open_questions_only_while_some_remain(tmp_path, cap partial = ["--channels", "DNA,ACTIN", "--image-type", "channels", "--accept-ids"] assert main(["describe", str(root), "--output", str(tmp_path / "o2"), *partial]) == 0 text = capsys.readouterr().out - assert "1 open question (answer them with --accept-ids, --comparable" in text + assert "1 open question (answer them with --comparable and --confirmed-on" in text assert "confirm that the folders of repeat rep1" in text assert "choose the ID" not in text # --accept-ids answered those @@ -296,7 +296,85 @@ def test_an_id_with_no_proposal_stays_open_under_accept_ids(tmp_path, capsys): assert main(command) in (0, 1) text = capsys.readouterr().out assert "are answered by your options" not in text - assert "1 open question (answer them" in text and "files" in text + assert "1 open question (answer them with --id FOLDER=ID, or in the notebook)" in text + assert "give --id files=" in text + + +# --- 4b. describe --id FOLDER=ID (owner, 4 December 2026) ---------------------------------- + + +def test_describe_id_names_a_forbidden_folder_and_publishes(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + for condition in ("control", "DrugA"): # control is a forbidden ID: no proposal + _ome(root / condition / "rep1" / "img.ome.tif") + command = ["describe", str(root), "--output", str(out), *CHANNELS, "--publish"] + assert main(command) == 1 + text = capsys.readouterr().out + assert "answer them with --id FOLDER=ID, or in the notebook" in text + assert "--accept-ids, " not in text.split("open question")[1].split("\n")[0] + assert "name it with --id control=" in text + assert not (out / DESCRIPTION_FILENAME).exists() + assert main([*command, "--id", "control=ctrl"]) == 0 + assert "Published" in capsys.readouterr().out + published = description_from_bytes((out / DESCRIPTION_FILENAME).read_bytes()) + assert published.conditions["ctrl"].source_folder == "control" + assert set(published.conditions) == {"ctrl", "DrugA"} + + +def test_describe_id_refuses_what_the_notebook_refuses_and_names_the_option(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + for condition in ("control", "DrugA"): + _ome(root / condition / "rep1" / "img.ome.tif") + base = ["describe", str(root), "--output", str(out), *CHANNELS, "--publish"] + for given, said in [ + ("control=files", "(E_FORBIDDEN_FIELD); give an allowed ID: --id control="), + ("control=druga", "E_ID_CASE_COLLISION"), + ("control=DrugA", "id_in_use_in_draft"), + ("nowhere=x", "'nowhere' is not a condition, biological-repeat or technical-repeat"), + ("control", "write it as FOLDER=ID"), + ]: + extra = ["--id", "DrugA=DrugA"] if given.endswith(("druga", "DrugA")) else [] + assert main([*base, *extra, "--id", given]) == 1, given + text = capsys.readouterr().out + assert "Nothing was written. These IDs cannot be used:" in text + assert said in text, (given, text) + assert not out.exists() + + +def test_describe_id_without_channels_shows_the_named_id(tmp_path, capsys): + root = tmp_path / "exp" + _ome(root / "control" / "rep1" / "img.ome.tif") + out = tmp_path / "out" + assert main(["describe", str(root), "--output", str(out), "--id", "control=ctrl"]) == 0 + text = capsys.readouterr().out + assert "control: ID 'ctrl' (yours, --id)" in text + assert "condition control" not in text # its question is answered + + +def test_describe_id_needs_the_level_for_a_label_of_two_levels(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + _ome(root / "a" / "rep1" / "a" / "img.ome.tif") + _ome(root / "b" / "rep1" / "a" / "img.ome.tif") + base = ["describe", str(root), "--output", str(out), *CHANNELS, "--publish"] + assert main([*base, "--id", "a=A1"]) == 1 + assert "give --id condition:a=A1 or --id technical:a=A1" in capsys.readouterr().out + assert main([*base, "--id", "condition:a=A1"]) == 0 + published = description_from_bytes((out / DESCRIPTION_FILENAME).read_bytes()) + assert published.conditions["A1"].source_folder == "a" + + +def test_describe_id_is_refused_for_a_published_or_strict_description(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + _ome(root / "CTRL" / "rep1" / "img.ome.tif") + assert ( + main(["describe", str(root), "--output", str(tmp_path / "s"), "--strict", "--id", "CTRL=c"]) + == 1 + ) + assert "--id names the IDs of a new fast-mode description" in capsys.readouterr().out + assert main(["describe", str(root), "--output", str(out), *CHANNELS, "--publish"]) == 0 + capsys.readouterr() + assert main(["describe", str(root), "--output", str(out), "--id", "CTRL=c"]) == 1 + assert "--id names the IDs of a new fast-mode description" in capsys.readouterr().out # --- 5. and 6. RGB as OME-Zarr: convert --store ome-zarr, then the suggestion --------------- From 88b754872b06992b80ecb8a368991f9c92e39535 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 07:52:11 +0000 Subject: [PATCH 09/25] tissue-mask: create and record a masks folder when the run has none A run of scanner images often has no masks folder, and tissue-mask stopped there. It now creates _masks beside the experiment (or the empty folder --masks names), records it by running preprocessing again with that masks folder (as run --masks does; unchanged images are not read), and says so in one line. A non-empty existing folder is never adopted. Messages: a refusal names the image once; the next steps give the declare-masks, run and masks commands (no source_channels, which declare-masks cannot set), and the region as a brick's settings name it (region_mask), not MaskRequest(, 'region'). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9ASFzYU5CY2vs1ReWg --- pyproject.toml | 1 + .../cli_tissue_mask.py | 54 ++++++++++- .../he_tissue_mask.py | 3 +- .../run_inputs_tissue.py | 27 ++++-- .../tissue_masks_folder.py | 95 +++++++++++++++++++ tests/test_cli_tissue_mask.py | 69 +++++++++++++- tests/test_notebook_tissue_mask.py | 4 +- 7 files changed, 235 insertions(+), 18 deletions(-) create mode 100644 src/morphobricks_preprocessing/tissue_masks_folder.py diff --git a/pyproject.toml b/pyproject.toml index 0579651a..54063549 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -446,6 +446,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.he_tissue_array" = "orchestration" "morphobricks_preprocessing.run_inputs_tissue" = "orchestration" "morphobricks_preprocessing.cli_tissue_mask" = "ui" +"morphobricks_preprocessing.tissue_masks_folder" = "orchestration" "morphobricks_preprocessing.notebook_tissue_mask" = "ui" "morphobricks_preprocessing.mask_requests" = "pure" "morphobricks_preprocessing.masks.layout" = "io" diff --git a/src/morphobricks_preprocessing/cli_tissue_mask.py b/src/morphobricks_preprocessing/cli_tissue_mask.py index 2539f678..6f5d3611 100644 --- a/src/morphobricks_preprocessing/cli_tissue_mask.py +++ b/src/morphobricks_preprocessing/cli_tissue_mask.py @@ -8,7 +8,10 @@ never changed and nothing is overwritten. A same call again is a no-op, unless a code identity is unverified: such a mask is written but never reused, so a retry is refused. The command prints what it wrote, the kept share, and the next steps (declare the mask ``binary``, run preprocessing and the -masks step again, use it as a region). It stops at the first refusal (exit status 1), naming it; the +masks step again, use it as a region: ``region_mask`` in the next brick's settings). A run with +no masks folder gets one first (``_masks`` beside the experiment, or ``--masks +FOLDER``), recorded as ``run --masks`` records it (:mod:`.tissue_masks_folder`), said in one +line. It stops at the first refusal (exit status 1), naming it; the images written before it stay written. Without scikit-image it names the extra to install and writes nothing (exit status 1). """ @@ -16,6 +19,7 @@ from __future__ import annotations import argparse +import shlex from .plane_errors import PlaneReadError from .run_inputs import RunInputs @@ -26,6 +30,7 @@ rgb_positions, tissue_next_steps, ) +from .tissue_masks_folder import MasksFolderRefused, create_masks_folder from .validation import plural @@ -64,6 +69,12 @@ def add_tissue_mask_parser(commands: argparse._SubParsersAction) -> argparse.Arg help="only this image, relative to the experiment folder (repeatable; default: every " "image of a unit declared rgb)", ) + tissue.add_argument( + "--masks", + metavar="FOLDER", + help="only when the run has no masks folder: the new, empty masks folder to create " + "and record (default: _masks beside the experiment folder)", + ) tissue.add_argument( "--rule", default=HE_TISSUE_V2, @@ -84,6 +95,22 @@ def tissue_mask_command(args: argparse.Namespace) -> int: if not images: print("The run has no image of a unit declared rgb; nothing was written.") return 1 + if args.masks and run.masks_root is not None: + print( + f"--masks creates a masks folder for a run without one; this run records " + f"{run.masks_root}, where the tissue masks go. Nothing was written." + ) + return 1 + if run.masks_root is None: + try: + run = create_masks_folder(run, args.masks).run + except MasksFolderRefused as exc: + print(f"No tissue mask written. {exc}") + return 1 + print( + f"The run had no masks folder: created {run.masks_root} and recorded it, as " + "run --masks does." + ) print(PROVISIONAL_NOTE) written = [] for image in images: @@ -91,7 +118,7 @@ def tissue_mask_command(args: argparse.Namespace) -> int: result = run.he_tissue_mask(image, output_mask_id=args.to, rule=args.rule) # Every refusal: RunInputsError, a missing extra, and a plane that cannot be read (#469). except (ValueError, ImportError, PlaneReadError, OSError) as exc: - print(f"{image}: no tissue mask written. {exc}") + print(_refusal(image, exc)) if written: print(f"{plural(len(written), 'image')} before it stay written.") return 1 @@ -103,5 +130,26 @@ def tissue_mask_command(args: argparse.Namespace) -> int: line += " (nothing kept: an empty region)" print(line if result.reusable else f"{line}; {NOT_REUSED}") print() - print(tissue_next_steps((r.mask_id for r in written), run.masks_root)) + ids = sorted({r.mask_id for r in written}) + print(tissue_next_steps(ids, run.masks_root, _commands(args.output, ids, run.masks_root))) return 0 + + +def _refusal(image: str, exc: Exception) -> str: + """Return the refusal of one image, naming the image once (a message may name it already).""" + text = str(exc).removeprefix(f"{image}: ") + if image in text: + return f"No tissue mask written. {text}" + return f"{image}: no tissue mask written. {text}" + + +def _commands(output: str, ids: list[str], masks_root: object) -> list[str]: + """Return the commands that declare the masks binary and check them (run, then masks).""" + types = " ".join(f"--type {shlex.quote(i)}=binary" for i in ids) + target = f"--output {shlex.quote(output)}" + return [ + f"morphobricks-preprocessing declare-masks {target} {types} " + f"--masks {shlex.quote(str(masks_root))}", + f"morphobricks-preprocessing run {target}", + f"morphobricks-preprocessing masks {target}", + ] diff --git a/src/morphobricks_preprocessing/he_tissue_mask.py b/src/morphobricks_preprocessing/he_tissue_mask.py index 15979ef9..d2acf192 100644 --- a/src/morphobricks_preprocessing/he_tissue_mask.py +++ b/src/morphobricks_preprocessing/he_tissue_mask.py @@ -338,7 +338,8 @@ def he_tissue_mask( if run.masks_root is None: raise ValueError( f"{found.relative_path}: the run has no masks folder; the H&E tissue mask is written " - "there only. Run preprocessing with a masks folder first" + "there only. Run preprocessing with a masks folder first (the command tissue-mask " + "creates and records one)" ) record = current_rule(rule) relative = _output_target(run, found.relative_path, output_mask_id) diff --git a/src/morphobricks_preprocessing/run_inputs_tissue.py b/src/morphobricks_preprocessing/run_inputs_tissue.py index 58da03c5..24784400 100644 --- a/src/morphobricks_preprocessing/run_inputs_tissue.py +++ b/src/morphobricks_preprocessing/run_inputs_tissue.py @@ -96,20 +96,27 @@ def rgb_positions(run: object) -> tuple[str, ...]: return tuple(fov.relative_path for fov in run.fovs() if fov.image_type == "rgb") -def tissue_next_steps(mask_ids: Iterable[str], masks_root: object) -> str: - """Return what to do with the tissue masks written: declare, run again, use as a region.""" +def tissue_next_steps( + mask_ids: Iterable[str], masks_root: object, commands: Iterable[str] = () +) -> str: + """Return what to do with the tissue masks written: declare, run again, use as a region. + + ``commands`` are the command lines that declare the masks and run again (the command line's + ``tissue-mask`` gives them); without them the steps are said in words (the notebook). + The region is named as a brick's settings name it (``region_mask``), never as Python. + """ ids = sorted(set(mask_ids)) if not ids: return "No mask was written." lines = [f"Written to the masks folder {masks_root}. Next:"] - lines += [ - f"- declare the mask {mask_id} (source type {mask_id}) as binary, with source_channels = " - '["R", "G", "B"]' - for mask_id in ids - ] - lines.append("- then run preprocessing and the masks step again to check them.") + commands = list(commands) + if commands: + lines += [f" {command}" for command in commands] + else: + lines += [f"- declare the mask {mask_id} as binary" for mask_id in ids] + lines.append("- then run preprocessing and the masks step again to check them.") lines.append( - "- use it as a region (for example fiberfeatures MaskRequest(, 'region')); in " - "memory, never pass it as cell-mode labels." + f'- use it as a region: in the next brick\'s settings, region_mask = "{ids[0]}" (for ' + "example fiberfeatures); never as cell-mode labels." ) return "\n".join(lines) diff --git a/src/morphobricks_preprocessing/tissue_masks_folder.py b/src/morphobricks_preprocessing/tissue_masks_folder.py new file mode 100644 index 00000000..0671d82d --- /dev/null +++ b/src/morphobricks_preprocessing/tissue_masks_folder.py @@ -0,0 +1,95 @@ +"""A masks folder for ``tissue-mask`` when the run has none (owner, 4 December 2026). + +The H&E tissue mask is written into the run's masks folder only (Spec ADR 0005 BM15). A run +of scanner images often has no masks: before v0.10.1 the command then stopped with "Run +preprocessing with a masks folder first". Now it creates one, an empty folder beside the +experiment (``_masks``) or the one ``--masks`` names, and records it the way +``run --masks FOLDER`` records a masks folder: by running preprocessing again on the output +folder with that masks folder and every other setting as the earlier run recorded +(:func:`.run.pipeline.run_experiment`; unchanged images are not read again). A folder that +already exists is never adopted silently: it must be empty, as a new one is. + +Nothing is created when the run is refused: a folder this module created is removed again. +""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from pathlib import Path + +from .report import format_issues +from .run import run_experiment +from .run_inputs import RunInputs +from .validation import has_errors + +MASKS_SUFFIX = "_masks" +"""The name of the default masks folder: the experiment folder's name and this suffix.""" + + +class MasksFolderRefused(ValueError): + """Raised when no masks folder can be created and recorded; nothing was left behind.""" + + +@dataclass(frozen=True) +class CreatedFolder: + """A masks folder created and recorded for the run; ``run`` is the run opened again.""" + + folder: Path + run: RunInputs + + +def default_masks_folder(experiment_root: Path) -> Path: + """Return the masks folder created by default: ``_masks`` beside it.""" + return experiment_root.parent / f"{experiment_root.name}{MASKS_SUFFIX}" + + +def create_masks_folder(run: RunInputs, folder: str | os.PathLike | None) -> CreatedFolder: + """Create an empty masks folder and record it for the run; return it and the run again. + + Parameters + ---------- + run + The opened run, which records no masks folder. + folder + Where to create it, or None for :func:`default_masks_folder`. + + Raises + ------ + MasksFolderRefused + When the folder exists and is not empty, cannot be created, or the run with it is + refused (its issues in the message). A folder created here is removed again. + """ + target = Path(folder).resolve() if folder else default_masks_folder(run.experiment_root) + created = not target.exists() + if not created and (not target.is_dir() or any(target.iterdir())): + raise MasksFolderRefused( + f"{target} exists and is not an empty folder, so it is not made the run's masks " + "folder. Give another with --masks FOLDER, or run preprocessing with " + f"--masks {target} if it is your masks folder." + ) + try: + target.mkdir(parents=True, exist_ok=True) + except OSError as exc: + raise MasksFolderRefused( + f"The masks folder {target} cannot be created ({exc.strerror or exc})." + ) from exc + result = run_experiment(output_folder=run.output_folder, masks_folder=target) + if has_errors(result.issues): + if created: + target.rmdir() + errors = [issue for issue in result.issues if issue.is_error] + raise MasksFolderRefused( + f"The run with the masks folder {target} was refused, so no masks folder was " + f"recorded:\n{format_issues(errors)}" + ) + return CreatedFolder(target, RunInputs.open(run.output_folder)) + + +__all__ = [ + "MASKS_SUFFIX", + "CreatedFolder", + "MasksFolderRefused", + "create_masks_folder", + "default_masks_folder", +] diff --git a/tests/test_cli_tissue_mask.py b/tests/test_cli_tissue_mask.py index 87fb9f7a..78edc1f1 100644 --- a/tests/test_cli_tissue_mask.py +++ b/tests/test_cli_tissue_mask.py @@ -46,9 +46,16 @@ def test_it_writes_every_rgb_image_and_names_the_next_steps(tmp_path, capsys, mo printed = capsys.readouterr().out assert "Fixed rule he_tissue_v2 (provisional)" in printed assert f"{IMAGE}: HETissue/{IMAGE} (written), kept 80.4 %" in printed - assert "declare the mask HETissue (source type HETissue) as binary" in printed - assert "run preprocessing and the masks step again" in printed - assert "never pass it as cell-mode labels" in printed + output = run.output_folder + assert ( + f"morphobricks-preprocessing declare-masks --output {output} --type HETissue=binary " + f"--masks {run.masks_root}" in printed + ) + assert f"morphobricks-preprocessing run --output {output}\n" in printed + assert f"morphobricks-preprocessing masks --output {output}\n" in printed + assert 'region_mask = "HETissue"' in printed and "never as cell-mode labels" in printed + assert "source_channels" not in printed and "MaskRequest" not in printed + assert "had no masks folder" not in printed line = json.loads((run.masks_root / "HETissue" / LINEAGE_FILENAME).read_text()) assert line["operation"] == "he_tissue_mask" and line["reusable"] is True before = tree(run.masks_root) @@ -79,6 +86,11 @@ def test_a_refusal_is_printed_and_exits_1_writing_nothing(tmp_path, capsys): printed = capsys.readouterr().out assert printed.splitlines()[-1].startswith(f"{IMAGE}: no tissue mask written. The output") assert "is declared in the description already" in printed + other = "CTRL/rep1/zz.tif" + assert main([*args, "--image", other]) == 1 + last = capsys.readouterr().out.splitlines()[-1] + assert last == f"No tissue mask written. {other} is not an image of this run." + assert last.count(other) == 1 # the image is named once (owner, 4 December 2026) assert main(["tissue-mask", "--output", str(tmp_path / "none"), "--to", "X"]) == 1 assert "The run cannot be used" in capsys.readouterr().out assert tree(run.masks_root) == before @@ -116,3 +128,54 @@ def refuse(self, *args, **kwargs): f"{IMAGE}: no tissue mask written. the plane needs 9 GiB; the limit is 2 GiB" ) assert tree(run.masks_root) == before + + +# --- No masks folder: created and recorded (owner, 4 December 2026) -------------------------- + + +def test_a_run_without_masks_folder_gets_one_recorded_as_run_masks_would( + tmp_path, capsys, monkeypatch +): + pytest.importorskip("skimage") + monkeypatch.setattr(IDENTITY_PATCH, lambda: identities()) + run = rgb_run(tmp_path, masks=False) + assert run.masks_root is None + args = ["tissue-mask", "--output", str(run.output_folder), "--to", "HETissue"] + assert main(args) == 0 + printed = capsys.readouterr().out + folder = (tmp_path / "experiment_masks").resolve() + created = [line for line in printed.splitlines() if "had no masks folder" in line] + assert created == [ + f"The run had no masks folder: created {folder} and recorded it, as run --masks does." + ] + assert (folder / "HETissue" / IMAGE).is_file() + manifest = json.loads((run.output_folder / "run_manifest.json").read_text()) + assert manifest["masks"]["folder"] == str(folder) # recorded as a run with --masks does + from morphobricks_preprocessing.run_inputs import RunInputs + + assert RunInputs.open(run.output_folder).masks_root == folder + assert main(args) == 0 # the same call again: the recorded folder, nothing created + printed = capsys.readouterr().out + assert "had no masks folder" not in printed and "(already written)" in printed + + +def test_masks_names_the_folder_to_create_and_a_busy_folder_is_refused( + tmp_path, capsys, monkeypatch +): + pytest.importorskip("skimage") + monkeypatch.setattr(IDENTITY_PATCH, lambda: identities()) + run = rgb_run(tmp_path, masks=False) + busy = tmp_path / "busy" + (busy / "other").mkdir(parents=True) + args = ["tissue-mask", "--output", str(run.output_folder), "--to", "HETissue"] + assert main([*args, "--masks", str(busy)]) == 1 + assert "exists and is not an empty folder" in capsys.readouterr().out + manifest = json.loads((run.output_folder / "run_manifest.json").read_text()) + assert not (manifest.get("masks") or {}).get("folder") + chosen = tmp_path / "chosen" + assert main([*args, "--masks", str(chosen)]) == 0 + assert f"created {chosen.resolve()}" in capsys.readouterr().out + assert (chosen / "HETissue" / IMAGE).is_file() + assert main([*args, "--masks", str(tmp_path / "third")]) == 1 # the run has one now + assert "this run records" in capsys.readouterr().out + assert not (tmp_path / "third").exists() diff --git a/tests/test_notebook_tissue_mask.py b/tests/test_notebook_tissue_mask.py index fcd965c1..f54ee53f 100644 --- a/tests/test_notebook_tissue_mask.py +++ b/tests/test_notebook_tissue_mask.py @@ -108,7 +108,9 @@ def test_the_write_happens_only_on_the_click(tmp_path, monkeypatch): card.button.click() assert f"HETissue/{IMAGE}" in tree(run.masks_root) assert "Written: 1 file(s); already written before: 0." in card.status.value - assert "declare the mask HETissue (source type HETissue) as binary" in card.status.value + assert "declare the mask HETissue as binary" in card.status.value + assert "source_channels" not in card.status.value + assert "region_mask = "HETissue"" in card.status.value assert f"HETissue/{IMAGE}: kept 80.4 %" in card.result.value card.button.click() # the same click again: nothing changes assert "Written: 0 file(s); already written before: 1." in card.status.value From a76185d0fe7f68c22f93c6a6f67868956e95097c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 07:53:22 +0000 Subject: [PATCH 10/25] A_DESCRIPTION_REQUIRED: name both routes that publish a description The fix pointed only to the notebook although describe --publish publishes from the command line. It now names the notebook's describe steps and the describe command with its fast-mode options. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9ASFzYU5CY2vs1ReWg --- docs/contract.md | 5 +++-- docs/user_guide.md | 5 +++-- .../required_description.py | 15 +++++++++------ tests/test_cli_exit_status.py | 3 +++ 4 files changed, 18 insertions(+), 10 deletions(-) diff --git a/docs/contract.md b/docs/contract.md index 298b431b..a1c48649 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -16,8 +16,9 @@ whole experiment; any change to them goes through the normalization brick. There is no backward compatibility before the first pipeline release (owner policy of 10 November 2026). **Every run needs a published experiment description** (`morphobricks.toml` in its output folder, experiment-v1). Without one every route refuses the run with the one code -`A_DESCRIPTION_REQUIRED`, before anything is read or written, naming the fix (the notebook's -describe steps and *Check and save*; the command line's `describe` shows what is still open): +`A_DESCRIPTION_REQUIRED`, before anything is read or written, naming the fix, both routes that publish one (owner, 4 December 2026): the notebook's describe +steps and *Check and save*, or the command line's `describe ... --publish` (fast mode; without +`--publish` it shows what is still open): | Route | Refusal | |---|---| diff --git a/docs/user_guide.md b/docs/user_guide.md index 6a22cecd..8d9d300d 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -895,8 +895,9 @@ for images that are not three channels of a whole-number pixel type stops the ru `check`, `run` and `masks` need the experiment description published in the output folder (`morphobricks.toml`, v0.5.1): the conditions, which biological repeats pair across conditions and that they are comparable, the channels and the masks, answered in the notebook's describe -steps and saved with *Check and save*. Without it they print `A_DESCRIPTION_REQUIRED` with what -to do, write nothing and exit with status 1. `describe` shows the draft description of the +steps and saved with *Check and save*, or published from the command line with `describe ... +--publish` (§5). Without it they print `A_DESCRIPTION_REQUIRED`, naming both routes, write +nothing and exit with status 1. `describe` shows the draft description of the folders and every question still open. The run writes `experiment_design.csv`, derived from the description (an output for later bricks; nothing reads it back). `check` and `run` write the report, `discovery_report.json` and `discovery_report.txt`, to the output folder; `run` writes diff --git a/src/morphobricks_preprocessing/required_description.py b/src/morphobricks_preprocessing/required_description.py index 7b7add8f..21642883 100644 --- a/src/morphobricks_preprocessing/required_description.py +++ b/src/morphobricks_preprocessing/required_description.py @@ -3,8 +3,8 @@ A run without a published ``morphobricks.toml`` in its output folder is refused on every route (the notebook, the command line's ``check``, ``run`` and ``masks``, :func:`.run.run_experiment`, :func:`.run.mask_step.prepare_mask_step` and :class:`.run_inputs.RunInputs`) with the one code -``A_DESCRIPTION_REQUIRED``, naming the fix: describe the experiment (the notebook's describe -steps; the command line's ``describe`` shows what is still open). Nothing is taken from folder +``A_DESCRIPTION_REQUIRED``, naming the fix: describe the experiment, in the notebook's describe +steps or with the command line's ``describe --publish`` (both named). Nothing is taken from folder names in its place and there is no undescribed run. """ @@ -23,11 +23,14 @@ """The refusal of a run without a published description (ADR 0002 AR11 ruling 1).""" FIX = ( - "Describe the experiment first: run the notebook's describe steps and save the " - "description (Check and save), which publishes morphobricks.toml in the output folder. " - "The command line's 'describe' shows what is still to be answered." + "Describe the experiment first, which publishes morphobricks.toml in the output folder: " + "either in the notebook (its describe steps, then Check and save), or on the command line " + "with 'morphobricks-preprocessing describe EXPERIMENT --output FOLDER --channels ID,ID " + "--image-type channels|rgb --accept-ids --comparable --confirmed-on YYYY-MM-DD --publish' " + "(without --publish it shows what is still to be answered)." ) -"""What the user does about it: the notebook's describe steps or the command line's ``describe``.""" +"""What the user does about it: either route publishes (owner, 4 December 2026): the notebook's +describe steps, or the command line's ``describe --publish`` (fast mode).""" def is_published(output_folder: str | os.PathLike) -> bool: diff --git a/tests/test_cli_exit_status.py b/tests/test_cli_exit_status.py index 437b5a51..3aebb587 100644 --- a/tests/test_cli_exit_status.py +++ b/tests/test_cli_exit_status.py @@ -33,6 +33,9 @@ def test_without_a_published_description_every_run_command_exits_with_1( assert main([command, str(experiment), "--output", str(output), *extra]) == 1 out = capsys.readouterr().out assert "A_DESCRIPTION_REQUIRED" in out and "describe" in out + # Both routes that publish are named (owner, 4 December 2026): notebook and command line. + assert "in the notebook" in out and "morphobricks-preprocessing describe" in out + assert "--publish" in out assert not output.exists() # nothing read or written From 01fcb75f4a664ee1b5b2f87c9f4e8ee8823c3bc1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 07:53:37 +0000 Subject: [PATCH 11/25] plan Q94: #620's CLI choices were proposed, not decided; record the owner's 4 December follow-ups Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9ASFzYU5CY2vs1ReWg --- docs/plan.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/docs/plan.md b/docs/plan.md index a7ff7db9..0e596f5f 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -1836,7 +1836,9 @@ Raised during review; to be decided before the milestones that need them: the installers are not followed (a Spec note for the owner). 94. How should the command line close the gaps a new user met before the next brick (v0.10.1, - pull request 620)? *Decided (owner, 3 December 2026):* the image-type suggestion of `check` + pull request 620)? *Proposed by the session that built pull request 620 (3 December 2026), + pending the owner's review* (the owner did not decide these choices explicitly): the + image-type suggestion of `check` and `run` follows the published description when it declares every acquisition `rgb` (no marker is written into OME-Zarr copies: OME-NGFF 0.4 has no colour field); an image type recorded by an earlier run still comes before the suggestion (`--image-type`, then the @@ -1844,3 +1846,16 @@ Raised during review; to be decided before the milestones that need them: option, without a folder for every acquisition, with a folder (repeatable, relative to the experiment) for that one; `check` reports an undeclared mask type as an error, as `run` refuses it, and exits with status 1. + *Decided (owner, 4 December 2026), folded into v0.10.1 before its release:* `describe --id + FOLDER=ID` (fast mode, repeatable) names any condition, biological-repeat or + technical-repeat folder's ID, checked with the notebook's rules (`Draft.confirm_id`), so a + folder named `control` (`E_FORBIDDEN_FIELD`) is no dead end; a refusal names the option, + and the open-question line offers only options that can answer it (never `--accept-ids` + for an ID with no proposal); a label used at two levels takes `condition:`, `repeat:` or + `technical:`. `tissue-mask` creates the run's masks folder when there is none + (`_masks` beside the experiment, or the empty folder `--masks` names), records + it by running preprocessing again with it, as `run --masks` records one, and says so in one + line; its refusals name the image once, and its next steps give the `declare-masks`, `run` + and `masks` commands and the region as `region_mask` in a brick's settings. + `A_DESCRIPTION_REQUIRED` names both routes that publish a description (the notebook, and + `describe --publish`). From 9c5780f974ffdf9e6cad46bc5a506587c6008ce2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 08:05:09 +0000 Subject: [PATCH 12/25] declare-masks --ignore TYPE: let runs skip a label image or mask type they do not use An OME-Zarr label image of another tool, or a mask type outside the analysis, was refused as undeclared with no way out but declaring or deleting it. declare-masks --ignore TYPE (repeatable) lists it in ignored_masks.toml beside morphobricks.toml (the description schema has no such field; owner choice of a TOML file in the output folder). check and run leave those types out of mask discovery; the run records the list and the file's SHA-256 in the manifest (optional key ignored_masks), so RunInputs.open neither counts them as unrecorded nor accepts a list changed since the run (RUN_FOLDER_STALE). Undeclared types not listed are still refused, and the refusal's fix now names --ignore beside --type. A declared type cannot be ignored; declaring a type takes it off the list. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9ASFzYU5CY2vs1ReWg --- pyproject.toml | 1 + .../cli_declare_masks.py | 69 +++++-- .../description_run_text.py | 5 +- .../ignored_masks.py | 190 ++++++++++++++++++ src/morphobricks_preprocessing/manifest.py | 8 + .../mask_declare.py | 65 +++++- src/morphobricks_preprocessing/masks/files.py | 6 + src/morphobricks_preprocessing/run/outputs.py | 1 + .../run/preflight.py | 35 +++- src/morphobricks_preprocessing/run_inputs.py | 3 + src/morphobricks_preprocessing/unrecorded.py | 22 +- tests/test_cli_usability.py | 60 ++++++ tests/test_ignored_masks.py | 83 ++++++++ 13 files changed, 526 insertions(+), 22 deletions(-) create mode 100644 src/morphobricks_preprocessing/ignored_masks.py create mode 100644 tests/test_ignored_masks.py diff --git a/pyproject.toml b/pyproject.toml index 54063549..5f26ec6d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -437,6 +437,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.lock_file" = "io" "morphobricks_preprocessing.mask_conversion" = "orchestration" "morphobricks_preprocessing.mask_declare" = "orchestration" +"morphobricks_preprocessing.ignored_masks" = "io" "morphobricks_preprocessing.mask_conversion_ids" = "pure" "morphobricks_preprocessing.lineage_schema" = "pure" "morphobricks_preprocessing.code_identity" = "io" diff --git a/src/morphobricks_preprocessing/cli_declare_masks.py b/src/morphobricks_preprocessing/cli_declare_masks.py index aa48352a..b4e1c7fd 100644 --- a/src/morphobricks_preprocessing/cli_declare_masks.py +++ b/src/morphobricks_preprocessing/cli_declare_masks.py @@ -10,8 +10,11 @@ commands that follow (``run``, then ``masks``): with ``--masks`` they name that folder; without it they name none, because OME-Zarr label images and ``_.tif`` masks beside the images are found without a masks folder, and say when to add one. The experiment folder is -named only when no run of the output folder records it. Exit status 1 for a refusal, with -nothing written, else 0 (also when every mask type was declared as asked already). +named only when no run of the output folder records it. ``--ignore TYPE`` (repeatable; owner, +4 December 2026) lists a mask type or OME-Zarr label image the runs do not use in +``ignored_masks.toml`` (:mod:`.ignored_masks`): ``check`` and ``run`` skip it instead of +refusing it as undeclared. Exit status 1 for a refusal, with nothing written, else 0 (also when +every mask type was declared as asked already). """ from __future__ import annotations @@ -21,7 +24,15 @@ from pathlib import Path from .description_rules import REPRESENTATIONS -from .mask_declare import MaskDeclaration, MaskDeclarationRefused, declare_masks +from .ignored_masks import IGNORED_FILENAME +from .mask_declare import ( + MaskDeclaration, + MaskDeclarationRefused, + declare_masks, + declared_types, + ignore_masks, +) +from .run.lock import OutputLockedError from .run.reuse import recorded_experiment_root NO_MASKS_FOLDER = ( @@ -56,11 +67,21 @@ def add_declare_masks_parser(commands: argparse._SubParsersAction) -> argparse.A "--type", dest="types", action="append", - required=True, + default=[], metavar="TYPE=REPRESENTATION[:ID]", help=f"a mask type (its folder name) and what it is: {', '.join(REPRESENTATIONS)}; " "optionally its ID (default: the folder name). Repeatable", ) + declare.add_argument( + "--ignore", + action="append", + default=[], + metavar="TYPE", + help="a mask type or OME-Zarr label image the runs do not use (repeatable): left out " + "of check and run instead of refused as undeclared; listed in ignored_masks.toml " + "beside morphobricks.toml and recorded by the run. Declaring a type with --type " + "takes it off the list", + ) declare.add_argument( "--masks", metavar="FOLDER", @@ -88,24 +109,48 @@ def parse_type(text: str) -> MaskDeclaration: def declare_masks_command(args: argparse.Namespace) -> int: - """Declare the mask types; print what was declared and the next commands.""" + """Declare the mask types and the ignored ones; print what changed and the next commands.""" + if not args.types and not args.ignore: + print("Give at least one --type TYPE=REPRESENTATION or --ignore TYPE. Nothing was written.") + return 1 try: declarations = [parse_type(text) for text in args.types] - done = declare_masks(args.output, declarations, masks_folder=args.masks) + done = ( + declare_masks(args.output, declarations, masks_folder=args.masks) + if declarations + else None + ) except (ValueError, MaskDeclarationRefused) as exc: - codes = f" ({', '.join(exc.codes)})" if getattr(exc, "codes", ()) else "" - print(f"Not declared{codes}: {exc}") - print("Nothing was written.") - return 1 - if done.publication is None: + return _refused(exc, "Nothing was written.") + try: + ignored, changed = ignore_masks( + args.output, args.ignore, declared=declared_types(args.output) + ) + except (ValueError, OutputLockedError, OSError) as exc: + kept = "the --ignore list was not changed" + return _refused(exc, f"{'The masks above were declared; ' if done else ''}{kept}.") + if done is not None and done.publication is None: print("Every mask type is declared as asked already; nothing was written.") - else: + elif done is not None: print(f"Declared in {done.publication.path}: {', '.join(done.added)}.") + if changed: + listed = ", ".join(ignored) if ignored else "none (the file was removed)" + print(f"Mask types the runs skip ({IGNORED_FILENAME}): {listed}.") + elif args.ignore: + print(f"Already skipped ({IGNORED_FILENAME}): {', '.join(ignored)}; nothing was written.") for line in next_commands(args.output, args.masks): print(line) return 0 +def _refused(exc: Exception, written: str) -> int: + """Print a refusal with its codes and what was (not) written; return exit status 1.""" + codes = f" ({', '.join(exc.codes)})" if getattr(exc, "codes", ()) else "" + print(f"Not declared{codes}: {exc}") + print(written[0].upper() + written[1:]) + return 1 + + def next_commands(output: str, masks: str | None) -> list[str]: """Return the lines naming the commands that follow a declaration. diff --git a/src/morphobricks_preprocessing/description_run_text.py b/src/morphobricks_preprocessing/description_run_text.py index 98876083..38458e93 100644 --- a/src/morphobricks_preprocessing/description_run_text.py +++ b/src/morphobricks_preprocessing/description_run_text.py @@ -48,7 +48,9 @@ "Declare the mask type in the description (the notebook's describe steps, or " "morphobricks-preprocessing declare-masks --output FOLDER --type " "TYPE=REPRESENTATION, where REPRESENTATION is what the mask is: instances, binary or " - "parent_labels), or remove its files." + "parent_labels); or, if the run does not use it (an OME-Zarr label image of another " + "tool, for example), skip it: declare-masks --output FOLDER --ignore TYPE; or remove " + "its files." ), } @@ -104,6 +106,7 @@ def physical_issue(issue: PhysicalIssue) -> ValidationIssue: if issue.code == MASK_TYPE_NOT_DECLARED: # the type found, never a guessed representation typed = shlex.quote(f"{issue.detail}=REPRESENTATION") action = action.replace("TYPE=REPRESENTATION", typed) + action = action.replace("--ignore TYPE", f"--ignore {shlex.quote(issue.detail)}") return error(issue.code, _what(issue), paths, action) diff --git a/src/morphobricks_preprocessing/ignored_masks.py b/src/morphobricks_preprocessing/ignored_masks.py new file mode 100644 index 00000000..3d779a5e --- /dev/null +++ b/src/morphobricks_preprocessing/ignored_masks.py @@ -0,0 +1,190 @@ +"""Mask types and OME-Zarr label images a run skips (owner, 4 December 2026). + +An OME-Zarr image may carry label images a run will not use (a segmentation of another tool, +an old annotation), and a masks folder may hold a mask type that is not part of the analysis. +Every mask type found must be declared (``R_MASK_TYPE_NOT_DECLARED``), and the experiment +description (``morphobricks.toml``, experiment-v1) has no field for "not used". So the +output folder holds a second, small file beside it, written by ``declare-masks --ignore +LABEL`` (:func:`.mask_declare.ignore_masks`, under the output folder's lock): + +.. code-block:: toml + + # Mask types and OME-Zarr label images the runs of this output folder skip. + # Written by declare-masks --ignore; declare a type to use it again. + version = 1 + ignore = ["old_cells", "tissue_v0"] + +``check`` and ``run`` read it (:func:`read_ignored`) and leave those types out of mask +discovery (:func:`.masks.find_masks` ``ignore``): no header check, no record, no +``R_MASK_TYPE_NOT_DECLARED``. The run records the list and the file's SHA-256 in the manifest +(``ignored_masks``), so :class:`.run_inputs.RunInputs` does not count those files as +unrecorded, and refuses a file changed, added or removed since the run +(``RUN_FOLDER_STALE``). Names are compared exactly, as declared types are. A type that is +declared cannot be ignored, and declaring a type takes it off the list. Undeclared types that +are not listed are still refused, as before. + +The reader is strict: other keys, another version, a name twice or a name that is not a mask +type's are :class:`IgnoredMasksError`; nothing is guessed. +""" + +from __future__ import annotations + +import os +import tomllib +from collections.abc import Iterable +from dataclasses import dataclass +from pathlib import Path + +from ._io import file_sha256 + +IGNORED_FILENAME = "ignored_masks.toml" +IGNORED_VERSION = 1 +MANIFEST_KEY = "ignored_masks" +"""The manifest's optional entry: ``{"types": [...], "file_sha256": "..."}``.""" +HEADER = ( + "# Mask types and OME-Zarr label images the runs of this output folder skip.\n" + "# Written by declare-masks --ignore; declare a type to use it again.\n" +) + + +class IgnoredMasksError(ValueError): + """Raised when ``ignored_masks.toml`` cannot be read as written, or a name is refused.""" + + +@dataclass(frozen=True) +class IgnoredMasks: + """The ignored mask types of an output folder, and the file's SHA-256 (None: no file).""" + + types: tuple[str, ...] = () + sha256: str | None = None + + def to_manifest(self) -> dict | None: + """Return the manifest's ``ignored_masks`` entry, or None when nothing is ignored.""" + if self.sha256 is None: + return None + return {"types": list(self.types), "file_sha256": self.sha256} + + +def recorded_ignored(entry: object) -> dict | None: + """Return the manifest's ``ignored_masks`` entry checked, as written and as read. + + Raises + ------ + ValueError + When it is not ``{"types": [names, sorted, each once], "file_sha256": 64 hex}``. + """ + if entry is None: + return None + sha = entry.get("file_sha256") if isinstance(entry, dict) else None + types = entry.get("types") if isinstance(entry, dict) else None + if ( + set(entry) != {"types", "file_sha256"} + or not isinstance(sha, str) + or len(sha) != 64 + or any(c not in "0123456789abcdef" for c in sha) + or not isinstance(types, list) + or not all(isinstance(t, str) and name_problem(t) is None for t in types) + or types != sorted(set(types)) + ): + raise ValueError( + f"the manifest's {MANIFEST_KEY} entry is not {{types: sorted names, file_sha256}}" + ) + return {"types": list(types), "file_sha256": sha} + + +def ignored_sha256(manifest: object) -> str | None: + """Return the SHA-256 of ``ignored_masks.toml`` a run's manifest records (None: no file).""" + entry = getattr(manifest, "ignored_masks", None) + return None if entry is None else entry["file_sha256"] + + +def ignored_types(manifest: object) -> frozenset[str]: + """Return the mask types a run's manifest records as skipped.""" + entry = getattr(manifest, "ignored_masks", None) + return frozenset(() if entry is None else entry["types"]) + + +def name_problem(name: str) -> str | None: + """Return why ``name`` cannot be an ignored mask type, or None when it can.""" + if not name or name != name.strip(): + return "a mask type's name is not empty and has no space at its start or end" + if any(c in name for c in "/\\") or any(ord(c) < 32 for c in name): + return "a mask type's name is one folder or label name: no '/', '\\' or control character" + return None + + +def ignored_text(types: Iterable[str]) -> str: + """Return the file's canonical text for ``types`` (sorted, each once).""" + names = sorted(set(types)) + for name in names: + if name_problem(name) is not None: + raise IgnoredMasksError(f"{name!r}: {name_problem(name)}") + quoted = ", ".join('"' + n.replace("\\", "\\\\").replace('"', '\\"') + '"' for n in names) + return f"{HEADER}version = {IGNORED_VERSION}\nignore = [{quoted}]\n" + + +def parse_ignored(data: bytes) -> tuple[str, ...]: + """Return the ignored types of the file's bytes, checked strictly. + + Raises + ------ + IgnoredMasksError + Not UTF-8 TOML, other keys, another version, or an ``ignore`` that is not a list of + distinct mask-type names. + """ + try: + table = tomllib.loads(data.decode("utf-8")) + except (UnicodeDecodeError, tomllib.TOMLDecodeError) as exc: + raise IgnoredMasksError(f"{IGNORED_FILENAME} is not UTF-8 TOML: {exc}") from exc + if set(table) != {"version", "ignore"}: + raise IgnoredMasksError( + f"{IGNORED_FILENAME} holds the keys version and ignore only; it holds " + f"{', '.join(sorted(table)) or 'none'}" + ) + if table["version"] != IGNORED_VERSION or isinstance(table["version"], bool): + raise IgnoredMasksError( + f"{IGNORED_FILENAME} is version {table['version']!r}; this release reads version " + f"{IGNORED_VERSION}" + ) + names = table["ignore"] + if not isinstance(names, list) or not all(isinstance(n, str) for n in names): + raise IgnoredMasksError(f"{IGNORED_FILENAME}: ignore is a list of names") + if len(set(names)) != len(names): + raise IgnoredMasksError(f"{IGNORED_FILENAME}: a name is listed twice") + for name in names: + if name_problem(name) is not None: + raise IgnoredMasksError(f"{IGNORED_FILENAME}: {name!r}: {name_problem(name)}") + return tuple(sorted(names)) + + +def read_ignored(output_folder: str | os.PathLike) -> IgnoredMasks: + """Return the output folder's ignored mask types (empty without the file). + + Raises + ------ + IgnoredMasksError + When the file cannot be read as written (:func:`parse_ignored`), or is a link. + """ + path = Path(output_folder) / IGNORED_FILENAME + if not os.path.lexists(path): + return IgnoredMasks() + if path.is_symlink() or not path.is_file(): + raise IgnoredMasksError(f"{path} is not a plain file; a link is never followed") + data = path.read_bytes() + return IgnoredMasks(parse_ignored(data), file_sha256(path)) + + +__all__ = [ + "IGNORED_FILENAME", + "IGNORED_VERSION", + "MANIFEST_KEY", + "IgnoredMasks", + "IgnoredMasksError", + "ignored_sha256", + "ignored_text", + "ignored_types", + "name_problem", + "parse_ignored", + "read_ignored", + "recorded_ignored", +] diff --git a/src/morphobricks_preprocessing/manifest.py b/src/morphobricks_preprocessing/manifest.py index a1382548..2aef2ad2 100644 --- a/src/morphobricks_preprocessing/manifest.py +++ b/src/morphobricks_preprocessing/manifest.py @@ -34,6 +34,8 @@ from .channel_identity_model import ChannelIdentitySettings, recorded_settings, settings_entry from .description_record import KEY as DESCRIPTION_KEY from .description_record import SectionDigestsError, UnitRecordError, recorded_description +from .ignored_masks import MANIFEST_KEY as IGNORED_KEY +from .ignored_masks import recorded_ignored from .image_qc_record import KEY as IMAGE_QC_KEY from .image_qc_record import recorded_image_qc from .lab_links import KEY as LAB_LINKS_KEY @@ -226,6 +228,9 @@ class RunManifest: image_qc The image QC table written with the run (:mod:`.image_qc_record`: file, SHA-256, metric version and settings); None (key left out) in manifests written before it. + ignored_masks + The mask types the run skipped and the SHA-256 of ``ignored_masks.toml`` + (:mod:`.ignored_masks`, v0.10.1); None (key left out) when the run skipped none. schema_version Version of the histogram table format, as text: ``"6"`` (``"5"`` in a version 5 manifest). @@ -256,6 +261,7 @@ class RunManifest: projection: dict | None = None lab_links: dict | None = None image_qc: dict | None = None + ignored_masks: dict | None = None schema_version: str = str(SCHEMA_VERSION) manifest_version: str = MANIFEST_VERSION @@ -337,6 +343,7 @@ def to_dict(self) -> dict: optional[PROJECTION_KEY] = self.projection optional[LAB_LINKS_KEY] = recorded_lab_links(self.lab_links) optional[IMAGE_QC_KEY] = recorded_image_qc(self.image_qc) + optional[IGNORED_KEY] = recorded_ignored(self.ignored_masks) data.update({key: value for key, value in optional.items() if value is not None}) return data @@ -393,6 +400,7 @@ def from_dict(cls, data: dict) -> RunManifest: projection=recorded_projection(data.get(PROJECTION_KEY)), lab_links=recorded_lab_links(data.get(LAB_LINKS_KEY)), image_qc=recorded_image_qc(data.get(IMAGE_QC_KEY)), + ignored_masks=recorded_ignored(data.get(IGNORED_KEY)), schema_version=str(data["schema_version"]), manifest_version=str(version), ) diff --git a/src/morphobricks_preprocessing/mask_declare.py b/src/morphobricks_preprocessing/mask_declare.py index 982a44b5..ac0df19c 100644 --- a/src/morphobricks_preprocessing/mask_declare.py +++ b/src/morphobricks_preprocessing/mask_declare.py @@ -30,12 +30,20 @@ from dataclasses import dataclass, replace from pathlib import Path +from ._io import write_text_atomic from .description import Description, DescriptionError, Mask from .description_rules import REPRESENTATIONS from .draft_ids import id_problems, propose_id +from .ignored_masks import ( + IGNORED_FILENAME, + IgnoredMasksError, + ignored_text, + name_problem, + read_ignored, +) from .run.description_file import Publication, PublicationRefused, publish_description from .run.description_run import load_description -from .run.lock import OutputLockedError +from .run.lock import OutputLockedError, output_lock from .segmentation_record import SegmentationError, check_mask_type_folder @@ -223,10 +231,65 @@ def declare_masks( return DeclaredMasks(added, publication) +def declared_types(output_folder: str | os.PathLike) -> tuple[str, ...]: + """Return the ``source_type`` of every mask the published description declares (none: ()).""" + found, problems = load_description(Path(output_folder)) + if problems or found is None: + return () + return tuple(sorted({mask.source_type for mask in found.description.masks.values()})) + + +def ignore_masks( + output_folder: str | os.PathLike, + add: Iterable[str] = (), + *, + declared: Iterable[str] = (), +) -> tuple[tuple[str, ...], bool]: + """Add types to the ignore list and take every declared type off it; return list, changed. + + ``declared`` are the ``source_type``s of the published description's masks: a type both + asked to be ignored and declared is refused; one declared and listed is removed (declaring + a type uses it again). The file is written under the output folder's lock, atomically, and + removed when the list becomes empty. Nothing is written when nothing changes. + + Raises + ------ + IgnoredMasksError + A refused name, a declared type asked to be ignored, or a file that cannot be read. + """ + add = tuple(add) + declared = set(declared) + for name in add: + if name_problem(name) is not None: + raise IgnoredMasksError(f"--ignore {name!r}: {name_problem(name)}") + both = sorted(set(add) & declared) + if both: + raise IgnoredMasksError( + f"--ignore {', '.join(both)}: declared in the description, so the run uses it; a " + "declared mask type is not ignored" + ) + folder = Path(output_folder) + if not folder.is_dir(): + raise IgnoredMasksError(f"The output folder {folder} does not exist.") + with output_lock(folder): + before = read_ignored(folder).types + after = tuple(sorted((set(before) | set(add)) - declared)) + if after == before: + return after, False + path = folder / IGNORED_FILENAME + if after: + write_text_atomic(path, ignored_text(after)) + else: + path.unlink() + return after, True + + __all__ = [ "DeclaredMasks", "MaskDeclaration", "MaskDeclarationRefused", "declare_masks", + "declared_types", + "ignore_masks", "with_declared_masks", ] diff --git a/src/morphobricks_preprocessing/masks/files.py b/src/morphobricks_preprocessing/masks/files.py index edd88303..4c9eaceb 100644 --- a/src/morphobricks_preprocessing/masks/files.py +++ b/src/morphobricks_preprocessing/masks/files.py @@ -49,6 +49,7 @@ def find_masks( output_folder: str | os.PathLike | None = None, bind: bool = False, progress: Callable[[int, int, str], None] | None = None, + ignore: Collection[str] = (), ) -> MaskInventory: """Pair every image with its masks and check them from their headers, without pixels. @@ -83,6 +84,10 @@ def find_masks( 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. + ignore + Mask types (masks-folder types and OME-Zarr label names) the run skips + (``ignored_masks.toml``, :mod:`..ignored_masks`): left out before any check or + header read, compared exactly, as declared types are. Returns ------- @@ -102,6 +107,7 @@ def find_masks( issues.extend(extra) found, unreadable = _label_masks(discovery.root, images) files.extend(found) + files = [f for f in files if f.mask_type not in ignore] issues.extend(_name_issues(files)) issues.extend(_description_name_issues(files)) files.sort(key=lambda f: (f.image, f.mask_type)) diff --git a/src/morphobricks_preprocessing/run/outputs.py b/src/morphobricks_preprocessing/run/outputs.py index bc6e9e60..45960be3 100644 --- a/src/morphobricks_preprocessing/run/outputs.py +++ b/src/morphobricks_preprocessing/run/outputs.py @@ -88,6 +88,7 @@ def write_generation( experiment_description=manifest_entry(described, masks, run.output, len(rows.entries)), lab_links=None if run.lab_links is None else run.lab_links.to_dict(), image_qc=image_qc_entry(qc_sha256), + ignored_masks=pre.ignored.to_manifest(), manifest_version=MANIFEST_VERSION, ) manifest = _kept_time(manifest, run.previous[0]) diff --git a/src/morphobricks_preprocessing/run/preflight.py b/src/morphobricks_preprocessing/run/preflight.py index 39617500..2cfa22f2 100644 --- a/src/morphobricks_preprocessing/run/preflight.py +++ b/src/morphobricks_preprocessing/run/preflight.py @@ -26,6 +26,7 @@ from ..dataset import DatasetReport, check_dataset from ..discovery import DiscoveryResult, default_output_folder, discover_experiment from ..fingerprint import Fingerprint, current_fingerprint +from ..ignored_masks import IGNORED_FILENAME, IgnoredMasks, IgnoredMasksError, read_ignored from ..mask_names import MASK_NAME_CODES, mask_name_issues from ..masks import MaskFile, MaskInventory, find_masks from ..metadata import ( @@ -88,6 +89,11 @@ class Preflight: headers_reused The images whose header was taken from a recorded check (``recorded`` of :func:`preflight`) instead of being read again, sorted; empty otherwise. + ignored + The mask types and label images the output folder's ``ignored_masks.toml`` lists + (:mod:`..ignored_masks`), left out of :attr:`masks`; empty without the file. + ignored_issues + The error ``ignored_masks_invalid`` when that file cannot be read as written. """ discovery: DiscoveryResult @@ -101,6 +107,8 @@ class Preflight: conversion: ConversionReview | None = None header_fingerprints: Mapping[str, Fingerprint | None] = field(default_factory=dict) headers_reused: tuple[str, ...] = () + ignored: IgnoredMasks = field(default_factory=IgnoredMasks) + ignored_issues: tuple[ValidationIssue, ...] = () @property def issues(self) -> tuple[ValidationIssue, ...]: @@ -112,6 +120,7 @@ def issues(self) -> tuple[ValidationIssue, ...]: *self.dataset.issues, *(self.masks.issues if self.masks is not None else ()), *(self.conversion.issues if self.conversion is not None else ()), + *self.ignored_issues, ] return tuple(sorted(merged, key=lambda issue: not issue.is_error)) @@ -251,6 +260,7 @@ def preflight( inspected, bound, reused = _inspected(root, images, bind_headers, progress, recorded or {}) metadata, calibration = _calibrated(inspected, discovery.images, output) report("masks", 0, 1, "") + ignored, ignored_issues = _ignored(output) masks = _masks( discovery, metadata, @@ -259,6 +269,7 @@ def preflight( output, bind_headers, lambda done, total, path: report("masks", done, total, path), + ignored.types, ) report("masks", 1, 1, "") # Each part of the comparison is reported, n of N (#579: the line seemed stuck). @@ -283,11 +294,28 @@ def preflight( conversion=conversion, header_fingerprints=bound, headers_reused=reused, + ignored=ignored, + ignored_issues=ignored_issues, ) report("acquisitions", total, total, "") return result +def _ignored(output: Path) -> tuple[IgnoredMasks, tuple[ValidationIssue, ...]]: + """Return the output folder's ignored mask types, or the error of a file that is invalid.""" + try: + return read_ignored(output), () + except (IgnoredMasksError, OSError) as exc: + return IgnoredMasks(), ( + error( + "ignored_masks_invalid", + f"The list of ignored mask types cannot be read: {exc}", + [IGNORED_FILENAME], + "Write it again with declare-masks --ignore, or remove the file.", + ), + ) + + ACQUISITION_PARTS = ( "the axes every header suggests", "the images per condition and repeat", @@ -406,8 +434,12 @@ def _masks( output: Path, bind: bool = False, progress: Callable[[int, int, str], None] | None = None, + ignore: tuple[str, ...] = (), ) -> MaskInventory | None: - """Pair the analysed images with their masks; None without masks folder or label image.""" + """Pair the analysed images with their masks; None without masks folder or label image. + + The types in ``ignore`` (``ignored_masks.toml``) are left out before any header is read. + """ masks = find_masks( masks_folder, discovery, @@ -416,6 +448,7 @@ def _masks( output_folder=output, bind=bind, progress=progress, + ignore=ignore, ) if masks_folder is None and not masks.files and not masks.issues: return None # no masks folder and no label images: the run has no masks diff --git a/src/morphobricks_preprocessing/run_inputs.py b/src/morphobricks_preprocessing/run_inputs.py index 70a9ed4b..8ff8a42d 100644 --- a/src/morphobricks_preprocessing/run_inputs.py +++ b/src/morphobricks_preprocessing/run_inputs.py @@ -52,6 +52,7 @@ from .design import DESIGN_FILENAME from .fingerprint import Fingerprint from .folder_rules import masks_folder_issues +from .ignored_masks import IGNORED_FILENAME, ignored_sha256 from .links import LinkRefusedError from .manifest import ( MANIFEST_FILENAME, @@ -310,6 +311,8 @@ def _read( design = published_path(output, DESIGN_FILENAME, manifest.experiment_design_sha256) check_sha(design, manifest.experiment_design_sha256) check_calibration(output / CALIBRATION_FILENAME, manifest.calibration_sha256) + # The list of skipped mask types, as the run read it (changed, added or removed: stale). + check_calibration(output / IGNORED_FILENAME, ignored_sha256(manifest)) description = check_description(output, manifest) # A_DRAFT_REFUSED, or changed check_section_digests(manifest, description) # the digests a consumer keys on (#490) check_channel_coverage(manifest, description) # recorded as the description's (#490) diff --git a/src/morphobricks_preprocessing/unrecorded.py b/src/morphobricks_preprocessing/unrecorded.py index 09a19d1c..a6f04850 100644 --- a/src/morphobricks_preprocessing/unrecorded.py +++ b/src/morphobricks_preprocessing/unrecorded.py @@ -14,7 +14,8 @@ OME-Zarr images, less the masks the run recorded and the outputs of the mask conversion helpers of a mask type the run did not record (each with its published line of ``mask_lineage.jsonl``, Spec ADR 0005 BM12: a new mask no description of this run declares, - read only after the run is made again). Label images are never skipped: without + read only after the run is made again), and the mask types the run skipped + (``ignored_masks.toml``, recorded in the manifest). Label images are never skipped: without the ``zarr`` extra, or with a ``labels`` group that cannot be read, the check raises instead of passing (owner, 2 November 2026); - links: a link that leaves the experiment or masks folder, leads back to a folder holding @@ -29,6 +30,7 @@ from pathlib import Path from .discovery import DiscoveryResult, discover_experiment +from .ignored_masks import ignored_types from .links import refuse_links from .manifest import RunManifest from .mask_lineage import conversion_outputs @@ -101,8 +103,9 @@ def unrecorded_files( refuse_links(discovery.issues) images = set(discovery.images) - recorded - set(manifest.settings.exclude) recorded_masks = {m["path"] for m in (manifest.masks or {}).get("files", ())} - masks = _folder_mask_paths(masks_root, discovery, recorded) | _label_paths( - experiment_root, recorded + ignored = ignored_types(manifest) # skipped by the run as ignored_masks.toml lists them + masks = _folder_mask_paths(masks_root, discovery, recorded, ignored) | _label_paths( + experiment_root, recorded, ignored ) types = {str(t).casefold() for t in (manifest.masks or {}).get("types", ())} masks -= conversion_outputs(masks_root, masks, types) @@ -110,17 +113,22 @@ def unrecorded_files( def _folder_mask_paths( - masks_root: Path | None, discovery: DiscoveryResult, recorded: Collection[str] + masks_root: Path | None, + discovery: DiscoveryResult, + recorded: Collection[str], + ignored: Collection[str] = (), ) -> set[str]: """Return the masks-folder files that pair with a recorded image, by the run's rules.""" if masks_root is None or not masks_root.is_dir(): return set() found, issues = _folder_masks(masks_root, discovery, recorded) refuse_links(issues) - return {mask.path for mask in found if mask.source == FOLDER} + return {m.path for m in found if m.source == FOLDER and m.mask_type not in ignored} -def _label_paths(experiment_root: Path, recorded: Collection[str]) -> set[str]: +def _label_paths( + experiment_root: Path, recorded: Collection[str], ignored: Collection[str] = () +) -> set[str]: """Return the label images of the recorded OME-Zarr images, as their mask paths. Without the ``zarr`` extra, :class:`.zarr_input.ZarrUnavailableError` is raised, and an @@ -135,5 +143,5 @@ def _label_paths(experiment_root: Path, recorded: Collection[str]) -> set[str]: names = ngff_label_names(experiment_root / image) except NgffError as exc: raise NgffError(f"the label images of {image} cannot be read: {exc}") from exc - paths.update(f"{image}/labels/{name}" for name in names) + paths.update(f"{image}/labels/{name}" for name in names if name not in ignored) return paths diff --git a/tests/test_cli_usability.py b/tests/test_cli_usability.py index ffbc32bc..36ab6972 100644 --- a/tests/test_cli_usability.py +++ b/tests/test_cli_usability.py @@ -229,6 +229,7 @@ def test_check_reports_an_undeclared_ome_zarr_label_mask_as_run_refuses_it(tmp_p action = "declare-masks --output FOLDER --type cells=REPRESENTATION" for text in (checked, ran): assert message in text and action in text + assert "declare-masks --output FOLDER --ignore cells" in text # owner, 4 Dec 2026 assert "--type TYPE=instances" not in checked # no representation is suggested for you import json @@ -243,6 +244,65 @@ def test_an_undeclared_mask_type_with_a_space_is_quoted_in_the_fix(): issue = physical_issue(PhysicalIssue(MASK_TYPE_NOT_DECLARED, None, detail="Cell outlines")) assert "--type 'Cell outlines=REPRESENTATION'" in issue.action + assert "--ignore 'Cell outlines'" in issue.action + + +def test_declare_masks_ignore_skips_a_label_image_and_the_run_records_it(tmp_path, capsys): + import json + + from morphobricks_preprocessing.run_inputs import RunInputs + + root, out = _labelled(tmp_path) + capsys.readouterr() + assert main(["declare-masks", "--output", str(out), "--ignore", "cells"]) == 0 + text = capsys.readouterr().out + assert "Mask types the runs skip (ignored_masks.toml): cells." in text + assert (out / "ignored_masks.toml").read_text() == ( + "# Mask types and OME-Zarr label images the runs of this output folder skip.\n" + "# Written by declare-masks --ignore; declare a type to use it again.\n" + 'version = 1\nignore = ["cells"]\n' + ) + assert main(["declare-masks", "--output", str(out), "--ignore", "cells"]) == 0 + assert "Already skipped" in capsys.readouterr().out # a retry writes nothing + assert main(["check", str(root), "--output", str(out)]) == 0 + assert main(["run", str(root), "--output", str(out)]) == 0 + capsys.readouterr() + manifest = json.loads((out / "run_manifest.json").read_text()) + assert manifest["ignored_masks"]["types"] == ["cells"] + run = RunInputs.open(out) # the label images are skipped, not unrecorded + assert run.manifest.masks is None or not run.manifest.masks.get("files") + # The list changed after the run: the run folder is stale until preprocessing runs again. + (out / "ignored_masks.toml").write_text('version = 1\nignore = ["cells", "other"]\n') + with pytest.raises(ValueError, match="RUN_FOLDER_STALE|ignored_masks.toml"): + RunInputs.open(out) + + +def test_declaring_an_ignored_type_takes_it_off_the_list_and_both_at_once_is_refused( + tmp_path, capsys +): + root, out = _labelled(tmp_path) + capsys.readouterr() + assert main(["declare-masks", "--output", str(out), "--ignore", "cells"]) == 0 + capsys.readouterr() + both = ["declare-masks", "--output", str(out), "--type", "cells=instances"] + assert main([*both, "--ignore", "cells"]) == 1 + assert "a declared mask type is not ignored" in capsys.readouterr().out + assert main(both) == 0 + assert "none (the file was removed)" in capsys.readouterr().out + assert not (out / "ignored_masks.toml").exists() + assert main(["run", str(root), "--output", str(out)]) == 0 # cells is used now + assert main(["declare-masks", "--output", str(out)]) == 1 + assert "Give at least one --type" in capsys.readouterr().out + + +def test_an_invalid_ignore_file_stops_check_and_run(tmp_path, capsys): + root, out = _labelled(tmp_path) + capsys.readouterr() + (out / "ignored_masks.toml").write_text('version = 2\nignore = ["cells"]\n') + assert main(["check", str(root), "--output", str(out)]) == 1 + assert "The list of ignored mask types cannot be read" in capsys.readouterr().out + assert main(["declare-masks", "--output", str(out), "--ignore", "x"]) == 1 + assert "this release reads version 1" in capsys.readouterr().out def test_declare_masks_without_a_masks_folder_names_no_placeholder_folder(tmp_path, capsys): diff --git a/tests/test_ignored_masks.py b/tests/test_ignored_masks.py new file mode 100644 index 00000000..e72f539e --- /dev/null +++ b/tests/test_ignored_masks.py @@ -0,0 +1,83 @@ +"""ignored_masks.toml: the strict reader, the canonical text and the manifest entry (v0.10.1).""" + +from __future__ import annotations + +import sys + +import pytest + +from morphobricks_preprocessing.ignored_masks import ( + IGNORED_FILENAME, + IgnoredMasks, + IgnoredMasksError, + ignored_text, + parse_ignored, + read_ignored, + recorded_ignored, +) +from morphobricks_preprocessing.mask_declare import ignore_masks + + +def test_the_text_is_canonical_and_reads_back(): + text = ignored_text(["b", "a", 'q"uote', "b"]) + assert text.endswith('version = 1\nignore = ["a", "b", "q\\"uote"]\n') + assert parse_ignored(text.encode()) == ("a", "b", 'q"uote') + + +@pytest.mark.parametrize( + ("data", "said"), + [ + (b"version = 1\n", "keys version and ignore only"), + (b'version = 1\nignore = ["a"]\nextra = 1\n', "keys version and ignore only"), + (b'version = 2\nignore = ["a"]\n', "reads version 1"), + (b'version = true\nignore = ["a"]\n', "reads version 1"), + (b'version = 1\nignore = "a"\n', "list of names"), + (b'version = 1\nignore = ["a", "a"]\n', "listed twice"), + (b'version = 1\nignore = [" a"]\n', "no space at its start or end"), + (b'version = 1\nignore = ["a/b"]\n', "no '/'"), + (b"\xff", "not UTF-8 TOML"), + (b"version = [", "not UTF-8 TOML"), + ], +) +def test_the_reader_refuses_anything_else(data, said): + with pytest.raises(IgnoredMasksError, match=said.replace("'", ".")): + parse_ignored(data) + + +@pytest.mark.skipif(sys.platform == "win32", reason="symbolic links need privileges on Windows") +def test_no_file_is_nothing_ignored_and_a_link_is_refused(tmp_path): + assert read_ignored(tmp_path) == IgnoredMasks() + target = tmp_path / "elsewhere.toml" + target.write_text('version = 1\nignore = ["a"]\n') + (tmp_path / IGNORED_FILENAME).symlink_to(target) + with pytest.raises(IgnoredMasksError, match="link"): + read_ignored(tmp_path) + + +def test_ignore_masks_adds_removes_declared_and_writes_only_on_change(tmp_path): + assert ignore_masks(tmp_path, ["b", "a"]) == (("a", "b"), True) + assert ignore_masks(tmp_path, ["a"]) == (("a", "b"), False) + assert ignore_masks(tmp_path, (), declared=["a"]) == (("b",), True) + with pytest.raises(IgnoredMasksError, match="declared"): + ignore_masks(tmp_path, ["b"], declared=["b"]) + assert ignore_masks(tmp_path, (), declared=["b"]) == ((), True) + assert not (tmp_path / IGNORED_FILENAME).exists() + with pytest.raises(IgnoredMasksError, match="does not exist"): + ignore_masks(tmp_path / "none", ["a"]) + + +def test_the_manifest_entry_is_checked_as_written_and_read(): + sha = "a" * 64 + assert IgnoredMasks().to_manifest() is None + assert recorded_ignored(None) is None + entry = IgnoredMasks(("a", "b"), sha).to_manifest() + assert recorded_ignored(entry) == {"types": ["a", "b"], "file_sha256": sha} + for bad in ( + {"types": ["b", "a"], "file_sha256": sha}, + {"types": ["a"], "file_sha256": "x"}, + {"types": ["a"]}, + {"types": ["a"], "file_sha256": sha, "more": 1}, + ["a"], + ): + with pytest.raises(ValueError, match="ignored_masks"): + recorded_ignored(bad) From 197b6db6f26c239ee3833240ccc0d4b2ae9bc171 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 08:07:55 +0000 Subject: [PATCH 13/25] docs: describe --id, tissue-mask's masks folder, declare-masks --ignore, the H&E route MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit User guide §5 (describe --id, declare-masks --ignore, tissue-mask and the whole H&E route on the command line), §6 (ignored_masks.toml), §8 (ignored_masks_invalid); contract §9 (the manifest's ignored_masks key); plan §12 question 94 (the owner's decision on where the ignore list lives); CHANGELOG Unreleased (v0.10.1); AGENTS.md repository map. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9ASFzYU5CY2vs1ReWg --- AGENTS.md | 10 ++++++ CHANGELOG.md | 47 ++++++++++++++++++++++-- docs/contract.md | 1 + docs/plan.md | 8 ++++- docs/user_guide.md | 90 +++++++++++++++++++++++++++++++++++++++------- 5 files changed, 139 insertions(+), 17 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7270bf83..67accd19 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -388,6 +388,11 @@ src/morphobricks_preprocessing/ the verified code identity (RECORD digest, PEP 610); lineage_schema.py the reader's dispatch by operation and the duplicate-key refusal; cli_tissue_mask.py the command tissue-mask + ignored_masks.py ignored_masks.toml (v0.10.1, owner 4 Dec 2026): the mask types and OME-Zarr label + images the runs skip; strict reader (read_ignored, parse_ignored), canonical text, + the manifest's optional ignored_masks entry (recorded_ignored); written by + mask_declare.ignore_masks (declare-masks --ignore, under the lock); preflight + passes the list to find_masks(ignore=); unrecorded.py leaves them out mask_declare.py declare_masks/with_declared_masks: declare mask types added after preprocessing in the published description (#587), the representation stated (no default) and the ID the folder name or given; published by publish_description (lock, base @@ -448,6 +453,11 @@ src/morphobricks_preprocessing/ moved from report.py in PP-10d discovery_report.py the run report (discovery_report.json and .txt, design v0.4 §4): status, manifest SHA-256, what was found, reused, recomputed and replaced + describe_ids.py describe --id FOLDER=ID (v0.10.1): apply_ids through Draft.confirm_id (the + notebook's rules), refusals naming the option; describe_questions.py the + draft's open questions and which options answer them (moved from cli_describe) + tissue_masks_folder.py create_masks_folder: tissue-mask on a run without a masks folder creates + _masks (or --masks) and records it by running preprocessing again cli.py, __main__ `morphobricks-preprocessing check|run|masks|calibrate|describe|convert|settings` (also `python -m morphobricks_preprocessing`); cli_run.py holds `run`'s options and output; cli_calibrate.py `calibrate`; cli_convert.py `convert`; log_target.py where `--log` may write (#99), diff --git a/CHANGELOG.md b/CHANGELOG.md index f257a8b2..8c5b8157 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,12 @@ v0.5.1: no run before v0.5.1 is read.) Patch release: the gaps a new user met before reaching the next brick in the clean-environment test of the v0.10.0 wave (3 December 2026): reuse of entry outputs in conda environments, the -command line, and the H&E tissue mask. No format change. +command line, and the H&E tissue mask; then the owner's follow-ups of 4 December 2026 +(`describe --id`, `tissue-mask` creating a masks folder, `declare-masks --ignore`, the +`A_DESCRIPTION_REQUIRED` fix). The histogram table, the description and the manifest version +are unchanged; one optional output-folder file (`ignored_masks.toml`) and one optional manifest +key (`ignored_masks`) are new. A v0.10.0 reader of a run that uses them ignores the key and so +refuses the skipped label images as unrecorded: refused, never silently wrong. ### Fixed @@ -52,8 +57,24 @@ command line, and the H&E tissue mask. No format change. records it. - **Fast `describe` prints "N open questions (answered by you, in the notebook)" only when questions remain:** with `--accept-ids`, `--comparable` and `--confirmed-on` it says the - options answer them; otherwise it lists only the questions left, naming the options (an ID - with no proposal stays open: `--accept-ids` cannot answer it). Counts use `plural`. + options answer them; otherwise it lists only the questions left, its heading naming only the + options that can answer them (owner, 4 December 2026): an ID with no proposal is answered by + `--id FOLDER=ID` alone, never offered `--accept-ids`. Counts use `plural`. +- **`tissue-mask` on a run without a masks folder** (owner, 4 December 2026) no longer stops + with "the run has no masks folder ... Run preprocessing with a masks folder first": it + creates `_masks` beside the experiment (or the new, empty folder `--masks FOLDER` + names), records it by running preprocessing again with it, as `run --masks` records one + (unchanged images are not read; `tissue_masks_folder.create_masks_folder`), and says so in one + line. A non-empty existing folder is never adopted. Its messages: a refusal names the image + once (it was repeated, "a.tif: no tissue mask written. a.tif is not an image of this run"); + the next steps print the `declare-masks --type ID=binary`, `run` and `masks` commands with + the folders, no longer `source_channels` (which `declare-masks` cannot set), and name the + region as a brick's settings do, `region_mask = ""`, not `MaskRequest(, 'region')` + (the notebook card's next steps too). +- **`A_DESCRIPTION_REQUIRED` names both routes** (owner, 4 December 2026): the notebook's + describe steps, and `describe ... --publish` with its fast-mode options; it named only the + notebook. +- **`R_MASK_TYPE_NOT_DECLARED`'s fix names `--ignore TYPE`** beside `--type TYPE=REPRESENTATION`. - **The image-type suggestion of `check` and `run` follows the published description** when it declares every acquisition `rgb` and RGB is possible (`image_type.declared_image_type`, `review_image_type(..., declared=)`). An OME-Zarr copy written by @@ -93,6 +114,26 @@ command line, and the H&E tissue mask. No format change. header override once in its action (from a flag set when the issue is built, never a search of the text), and `describe` adds a line naming the option; the shared texts that `run` also prints name only the notebook, since a published description is changed there. +- **`describe --id FOLDER=ID`** (fast mode, repeatable; owner, 4 December 2026) names the ID of + any condition, biological-repeat or technical-repeat folder, so a folder whose name cannot be + an ID (`control`, `files`: `E_FORBIDDEN_FIELD`) is no dead end on the command line. The ID is + adopted exactly as typed and checked with the notebook's rules (`Draft.confirm_id`: + forbidden names, case collisions, an ID used twice, `single`); a refusal names the option to + give again (`--id control=`) and nothing is written. A label used at two levels takes + `condition:`, `repeat:` or `technical:`. Without `--channels` it shows the draft with the IDs. + Refused for a published description or `--strict`. New modules `describe_ids` and + `describe_questions` (the question texts, moved from `cli_describe`). +- **`declare-masks --ignore TYPE`** (repeatable; owner, 4 December 2026) lets the runs skip an + OME-Zarr label image or mask type they do not use, instead of refusing it as undeclared. The + list is `ignored_masks.toml` beside `morphobricks.toml` (version 1, keys `version` and + `ignore`, read strictly; the description has no field for it), written under the output + folder's lock. `check` and `run` leave those types out of mask discovery + (`find_masks(..., ignore=)`); the run records the list and the file's SHA-256 in the manifest + (`ignored_masks`, optional), so `RunInputs.open` does not count them as unrecorded masks and + refuses a list changed, added or removed since the run (`RUN_FOLDER_STALE`). A declared type + cannot be ignored; declaring a type takes it off the list. An unreadable file is the error + `ignored_masks_invalid`. `--type` is no longer required (`--type` or `--ignore`). New module + `ignored_masks`. - **`convert --store ome-zarr`** writes every image that is read as an OME-Zarr copy (OME-NGFF 0.4, `.ome.zarr`), as `convert_experiment(..., store="ome-zarr")` and the notebook do; RGB TIFFs included. Default `ome-tiff`, as before. The user guide (§5) shows the H&E route: diff --git a/docs/contract.md b/docs/contract.md index a1c48649..bb63eca8 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -298,6 +298,7 @@ interpretation. | `narrow_histogram_ranges` | The channel planes whose range check found the central range too narrow (§4), sorted by plane and channel: `relative_path`, `plane_id`, `channel` and the fields of the normalization brick's `RangeCheck` (`histogram_range`, `central_percentiles`, `central_bins`, `robust_quantiles`, `robust_limits`, `outside_robust_count`, `robust_central_bins`, `min_central_bins`). Empty when there are none; absent in manifests written before follow-up P6. Optional key: the manifest stays version 1. | | `conversion_record_sha256` | SHA-256 of the conversion record (`.morphobricks-conversion.json`) in the experiment root when the experiment is a tree of named-axis copies (design v0.4 §5, §17); null otherwise. `RunInputs` checks it (owner decision of 2 November 2026, plan question 59): a record changed or gone since the run is refused, as for `calibration_sha256`. A changed record changes no row (the copies are checked by their fingerprints like any image). | | `calibration_sha256` | SHA-256 of the output folder's `calibration.csv` as the run read it (§9.3); null when there was none (or absent in manifests written before PP-8). `RunInputs` checks it. | +| `ignored_masks` | Optional (v0.10.1; key left out when nothing is skipped): `{"types": [sorted names], "file_sha256": "..."}`, the mask types and OME-Zarr label images the run skipped as the output folder's `ignored_masks.toml` lists them (`declare-masks --ignore`, owner decision of 4 December 2026, plan §12 question 94) and that file's SHA-256. Those types are left out of mask discovery (no header check, no record, no `R_MASK_TYPE_NOT_DECLARED`); `RunInputs.open` does not count their files as unrecorded and refuses a list changed, removed or added since the run (`RUN_FOLDER_STALE`). The manifest version is unchanged: a reader without this key refuses the skipped files as unrecorded. | | `experiment_description` | Always present (v0.5.1: every run is described, §0; experiment-v1 §4.5a, §4.6, §9.3). An object: `sha256` (of the exact bytes the run read: provenance, never a cache key), `schema_version`, `section_digests` (`conditions`, `channels`, `repeats`, `masks`), `units` (one object per declared unit: its repeat, condition and technical repeat IDs and `image_type_header_verified`, false for a format whose header states no colour interpretation and for a unit whose header was overridden; only for a unit declared `rgb` with `rgb_header_override = true` whose TIFF header does not say RGB and whose images all have three interleaved samples (Spec experiment-v1 §4.4b, amendment RH1), `image_type_header_overridden` (true) and `header_photometric` (the header's photometric interpretation, for example `minisblack`; distinct ones joined by `, `); for every unit declared `rgb`, `rgb_header_override`: the declared key (`true` or `false`, absent in the file is `false`; owner answers of 14 November 2026: declared and effective are recorded separately); for a unit that declares it `true`, `rgb_header_override_images`: a list sorted by `image` (relative path) of objects `image`, `override` (`used`: it lifted a header that does not say RGB; `unused`: it did not) and `header_photometric` (that image's own header colour interpretation, kept as evidence; null for a format that states none), an `unused` item adding `unused_reason` (`header_already_rgb`: header-verified; `no_colour_interpretation`, for example OME-Zarr: not header-verified). Homogeneity (`R_UNIT_NOT_HOMOGENEOUS`) compares the effective image type, so images of an overridden unit that differ only in colour interpretation are one layout; `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` is reported before it. These keys are additive (optional on read, checked when present): the manifest version stays 5; and, only for a unit that has such images, `images_without_header_channel_names`: a list sorted by `image` (relative path) of objects `image`, `header_names` (`none` when the header names no channel, `partial` when only some) and `channel_positions` (the zero-based C positions without a header name). Such an image passes the header checks, needs no evidence and the confirmed layout is used (§4.3); it is listed, not warned about, and the key is omitted for a unit whose images are all fully named; RGB units list nothing), `masks` (per declared mask ID: `source_type`, `representation`, `status`, `images_with_masks`, `images` and each file with its fingerprint and its own `status`) and `records` (the lines of `morphobricks.records.jsonl`, copied unchanged). A mask file is `checked` only when the mask step recorded it in `mask_representation.json` with the same fingerprint, representation and source type; otherwise `not yet checked`. Each unit record also lists its `channels` in source order; in a fast-mode description (Spec ADR 0006, `channel_layout`) every unit record adds `channels_from` (`experiment` or `unit`, as published) and a unit with `channels_from = "experiment"` adds `fast_layout_images`: one object per checked image, sorted by `path`, with `path`, `fov_key` (an object: `condition`, `biological_repeat`, `technical_repeat`, `position_id`), `header_verified` (true exactly when every channel's evidence is `header`) and `channels`, one object per index of the list: `c`, `channel`, `header_name` (as read, never normalised: `""` for a stated empty name, null when the format states none) and `evidence` (`header`, or `statement`: no name, accepted under the user's statement); additive keys, checked when present (the manifest version stays 5), and `channel_coverage` (manifest version 5, Stage 3 S3.3) classifies every biological repeat for every declared channel ID: `status` `full` (every unit of the repeat lists it), `partial` (some do; also the warning `partial_channel_coverage`) or `unavailable`, with `units_with`, `units` and the units `lacking` it (`condition/technical repeat` IDs). A run refuses units of different image types (`R_HETEROGENEOUS_LAYOUT_NOT_ENABLED`); units with different channel lists are accepted. | | `projection` | Only for a run on a tree of Z-projected copies (the key is left out otherwise, so a run without projection is byte for byte as before; issue #176, run side). An object with exactly `method` (`max`, `mean` or `sum`), `z_range` (`[start, stop]` requested for the experiment, or null for every slice), `conversion_record` (`{file, sha256}`: the record these facts come from, the same SHA-256 as `conversion_record_sha256`), `source_root`, `images` (one per analysed image, unique and sorted by path, which `read_manifest` checks: `relative_path`, `source_relative_path`, `source_content_sha256`, `source_z_size`, `z_range` (the slices used), `source_dtype`, `output_dtype`, `dtype_rule`, `rounding`, `significant_bits_dropped`), `masks_paired` (the masks paired with projected images, sorted) and `warnings` (`["masks_on_projected_images"]` exactly when `masks_paired` is not empty). A reader that knows nothing of the key ignores it, but it also refuses the conversion record the run names (version 3 or later), so projected copies are never read by it as plain images; `manifest_version` is not changed. | | `lab_links` | Only for a run given lab-tool links (v0.5.1, PP-2; Spec experiment-v1 §9.3; owner decision of 9 November 2026); the key is left out otherwise, so a run without links is byte for byte as before. An object with exactly the keys the user gave, recorded verbatim: `repository_url`, `commit` and `experiment_path` (each non-empty text with no outer whitespace, control character (Unicode `Cc`) or bidi control (U+061C, U+200E, U+200F, U+202A–U+202E, U+2066–U+2069; #416), other format characters such as ZWNJ and ZWJ kept; `commit` a full lowercase hexadecimal SHA of 40 or 64 characters) and, when given, `repeat_codes` (each lab-tool repeat code to a canonical biological repeat ID, written sorted by code). Input: `run --lab-links FILE` (a UTF-8 JSON object; any other key, a value of another type, an empty value or a key given twice in one object is refused before anything is read, `lab_links_invalid`), or `run_experiment(mode=RunMode(lab_links=LabLinks(...)))` (`read_lab_links`, `LabLinks`, `LabLinksError`). Nothing is trimmed, guessed or filled in. A `repository_url` holding a credential (a password, `user:password@`, in any form; a user name before `@` in a URL whose scheme is not `ssh`, `git+ssh` or `ssh+git`, because `https://TOKEN@host/...` carries a token there), a query string or a fragment (`?` or `#`) is refused (`lab_links_invalid`), and the refusal does not repeat the URL: a credential is never written to the manifest. An SSH remote's login name (`git@host:lab/db.git`, `ssh://git@host/...`) is kept. `repeat_codes` are used only when the user confirmed them for this run (`--confirm-repeat-codes`, `LabLinks(repeat_codes_confirmed=True)`, `read_lab_links(confirmed=True)`; never read from the file): equal strings are not evidence. They must name every biological repeat of the published description exactly once and no other ID (compared exactly: a source folder or display name is not an ID). Each refusal is a run error reported together, before any pixel is read: `lab_links_repeat_codes_not_confirmed`, `lab_links_repeat_unknown`, `lab_links_repeat_twice`, `lab_links_repeat_missing`. **Provenance only:** the links are never written to `morphobricks.toml` (`labchronicle`, `provenance` and `source_database` stay `E_FORBIDDEN_FIELD`, `i99`), and they are in no section digest, description SHA-256, row key, staging key, mask-step check, design, table or report: a run with, without or with changed links publishes the same files apart from this key, and so the manifest's own SHA-256 (which the report records, and which later bricks that pin the manifest see change). Not a recorded input (§9.2): a run not given links records none. The reader checks the entry as the input is checked; a malformed one makes the manifest malformed. | diff --git a/docs/plan.md b/docs/plan.md index 0e596f5f..c0b5ca03 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -1858,4 +1858,10 @@ Raised during review; to be decided before the milestones that need them: line; its refusals name the image once, and its next steps give the `declare-masks`, `run` and `masks` commands and the region as `region_mask` in a brick's settings. `A_DESCRIPTION_REQUIRED` names both routes that publish a description (the notebook, and - `describe --publish`). + `describe --publish`). `declare-masks --ignore TYPE` (repeatable) lets runs skip an + OME-Zarr label image or mask type they do not use; undeclared types not listed are still + refused, and the refusal's fix names `--ignore` beside `--type`. Where the list lives was + asked the same day (the description is closed by the Spec): *Decided (owner, 4 December + 2026):* a TOML file beside `morphobricks.toml`, `ignored_masks.toml`, recorded in the run + manifest (`ignored_masks`, with its SHA-256); the owner also asked for a review of how many + files the output folder holds, and a consolidation if it gets out of hand (a follow-up). diff --git a/docs/user_guide.md b/docs/user_guide.md index 8d9d300d..481c2542 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1111,8 +1111,29 @@ publishes nothing (`R_DRAFT_EXISTS`): they are finished and published in the not Images need not be three folder levels deep: images directly in condition folders (`exp1/condition_x/img.tif`) or in the experiment folder itself (one OME-Zarr mosaic, say) have the repeat and acquisition `single`, as everywhere. The draft lists the open questions only -while some remain: `--accept-ids`, `--comparable` and `--confirmed-on` answer them, and the -output says so. +while some remain, each heading naming only the options that can answer what is left +(`--id`, `--accept-ids`, `--comparable` and `--confirmed-on`), and the output says when your +options answer them all. + +**Naming an ID yourself (`--id FOLDER=ID`).** A folder whose name cannot be an ID gets no +proposal: `control` and `files` are reserved words of the description (`E_FORBIDDEN_FIELD`), +and `--accept-ids` cannot accept a proposal that does not exist. Name it with `--id` +(repeatable), for a condition, biological-repeat or technical-repeat folder: + +```bash +morphobricks-preprocessing describe /data/exp1 --channels DNA,ACTIN --image-type channels \ + --id control=ctrl --accept-ids --comparable --confirmed-on 2026-12-04 --publish +``` + +The ID is used exactly as you type it and checked with the notebook's rules: a forbidden word, +an ID already used by another folder (also in another upper/lower case) or `single` for a +folder that is not `single` is refused, the line naming the option to give again (`--id +control=`), and nothing is written. The folder keeps its name; only the description's ID +differs. A folder name used at two levels (a condition and a technical repeat both called `a`) +needs the level: `--id condition:a=A1`, `--id repeat:a=...` or `--id technical:a=...`. When +`--id` names every ID, `--accept-ids` is not needed. Without `--channels`, `describe --id` +shows the draft with your IDs. `--id` is for a new fast-mode description; a published one, or +the strict mode, names IDs in the notebook. **Colour scanner files whose header does not say colour.** Some scanners (and some public H&E datasets) store red, green and blue as three interleaved samples per pixel under the TIFF @@ -1389,7 +1410,19 @@ morphobricks-preprocessing masks --output /data/exp1_MorphoBricks_Preprocessing commands without it (`run EXPERIMENT --output FOLDER`, the experiment folder left out when a run of the output folder records it). - `check` reports a mask type the description does not declare exactly as `run` refuses it - (`R_MASK_TYPE_NOT_DECLARED`, naming the type), so you see it before the run. + (`R_MASK_TYPE_NOT_DECLARED`, naming the type), so you see it before the run. Its fix names + both ways out: `--type TYPE=REPRESENTATION` to use it, `--ignore TYPE` to skip it. +- **Skipping a mask type you do not use (`--ignore TYPE`, repeatable).** An OME-Zarr image may + carry label images of another tool, or a masks folder a mask type outside your analysis. + `declare-masks --output FOLDER --ignore TYPE` lists it in `ignored_masks.toml` beside + `morphobricks.toml` (the description itself has no place for "not used"); `check` and `run` + then leave it out, without reading or recording it, instead of refusing it. The run records + the list and the file's SHA-256 in `run_manifest.json` (`ignored_masks`), so later bricks + neither refuse those label images as unrecorded nor accept a list changed since the run (run + preprocessing again after changing it). Undeclared types that are not listed are still + refused. A declared type cannot be ignored; declaring it with `--type` takes it off the list + (the file is removed when the list becomes empty). `--type` and `--ignore` may be given + together; at least one is needed. - In Python: `morphobricks_preprocessing.mask_declare.declare_masks(output, {"Cells": "instances"})`. ### Converting a mask (`convert-mask`) @@ -1459,18 +1492,44 @@ morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preproce be reused on retry**, the installed code could not be verified (for example a development install, `pip install -e`): the mask is written, but a second run with the same ID is refused; use a new ID. -- Then declare it, run preprocessing and the masks step again, and use it **as a region**: - - ```toml - [masks.HETissue] - source_type = "HETissue" - representation = "binary" - source_channels = ["R", "G", "B"] - display_name = "H&E tissue (he_tissue_v2)" +- **A run without a masks folder** (scanner images often have no masks) gets one first: + `tissue-mask` creates `_masks` beside the experiment folder (or the new, empty + folder `--masks FOLDER` names), records it by running preprocessing again on the output folder + with that masks folder, exactly as `run --masks FOLDER` records one (unchanged images are not + read again), and says so in one line. A folder that exists and is not empty is never adopted: + give another, or run preprocessing with `--masks` yourself if it is your masks folder. +- A refusal names the image once, then what to do. +- Then declare it, run preprocessing and the masks step again; the command prints these commands + with your folders: + + ```bash + morphobricks-preprocessing declare-masks --output /data/exp1_MorphoBricks_Preprocessing \ + --type HETissue=binary --masks /data/exp1_masks + morphobricks-preprocessing run --output /data/exp1_MorphoBricks_Preprocessing + morphobricks-preprocessing masks --output /data/exp1_MorphoBricks_Preprocessing ``` - For example fiberfeatures `MaskRequest("HETissue", "region")`. It is never a set of cells: do - not pass it as cell-mode labels. + Use it **as a region**: in the next brick's settings, `region_mask = "HETissue"` (for example + fiberfeatures). It is never a set of cells: do not pass it as cell-mode labels. + +**The whole H&E route on the command line**, for scanner TIFFs with no masks (here a condition +folder named `control`, which cannot be an ID, and a header that does not say colour): + +```bash +morphobricks-preprocessing describe /data/he --channels R,G,B --image-type rgb --id control=ctrl \ + --accept-ids --comparable --confirmed-on 2026-12-04 --rgb-header-override --publish +morphobricks-preprocessing run /data/he +morphobricks-preprocessing tissue-mask --output /data/he_MorphoBricks_Preprocessing --to HETissue +morphobricks-preprocessing declare-masks --output /data/he_MorphoBricks_Preprocessing \ + --type HETissue=binary --masks /data/he_masks +morphobricks-preprocessing run --output /data/he_MorphoBricks_Preprocessing +morphobricks-preprocessing masks --output /data/he_MorphoBricks_Preprocessing +``` + +`tissue-mask` creates and records `/data/he_masks` (the run had none) and prints the last three +commands with your folders; then set `region_mask = "HETissue"` in the next brick's settings. +If the images are OME-Zarr with label images you will not use, skip them first with +`declare-masks --output ... --ignore LABEL`. In the notebook, the card **Make an H&E tissue mask (optional)** beside **Convert a mask** does the same: choose the RGB positions (or **Choose all of this unit**), **Preview** one image (the @@ -1557,6 +1616,10 @@ The default output folder is next to the experiment folder: cache: delete it and the next restore reads every header; later bricks never read it. - **`calibration.csv`** (only when you state pixel sizes): your statements (§5, Stating pixel sizes). Runs read it and never change it. +- **`ignored_masks.toml`** (only when you skip mask types, v0.10.1): the mask types and + OME-Zarr label images the runs leave out (`declare-masks --ignore`, §5). Runs read it and + never change it; the manifest records it (`ignored_masks`), and a list changed after a run + makes that run stale for later bricks until preprocessing runs again. - **`ome_zarr/`**: written only by v0.3 runs that converted TIFF images to OME-Zarr. That option was removed in v0.4.0; such a folder is left as it is, and may be deleted. @@ -1806,6 +1869,7 @@ continues. | `manifest_channel_coverage_mismatch` | Error (other bricks) | `RunInputs.open` found a `channel_coverage` in the run manifest that is not the channel coverage of the published `morphobricks.toml` the run read (`ChannelCoverageMismatchError`); the message names `experiment_description.channel_coverage` and each biological repeat that differs. The manifest was changed after the run, so the run is refused, never corrected. Run preprocessing again. | | `manifest_unit_record_malformed` | Error (other bricks) | A record of the run manifest's `experiment_description.units` is not an object with `repeat`, `condition`, `technical_repeat`, `channels` and `image_type_header_verified` of their types, or holds a field the run does not write (`ManifestUnitRecordError`, when the manifest is read). The manifest was changed after the run, or was written by a newer release that records a unit field this one does not know (refused, never ignored); the message names the unit record and the field. Nothing is filled in: run preprocessing again. A manifest written before v0.5.2 never reaches this check: its version is refused first. | | `manifest_unit_record_mismatch` | Error (other bricks) | `RunInputs.open` found a unit record in the run manifest that is not a unit of the published `morphobricks.toml` the run read: an unknown repeat, condition or technical repeat, a unit recorded twice or not at all, other channels, or a declared `rgb_header_override` that the description does not declare (`UnitRecordMismatchError`); the message names the unit record and the field. Run preprocessing again. | +| `ignored_masks_invalid` | Error | `ignored_masks.toml` in the output folder cannot be read as `declare-masks --ignore` writes it (other keys, another version, a name twice or with a `/`, a link). Write it again with `declare-masks --ignore`, or remove the file. | | `masks_folder_not_found` | Error | The masks folder does not exist. Select the folder that holds one folder per kind of mask. Later bricks opening a run (`RunInputs.open(..., masks_root=...)`) refuse a masks folder given that does not exist or is a file with the same code (`MasksFolderNotFoundError`); it is never read as a folder without masks. Give the folder that holds the masks, or leave `masks_root` out to use the one the run recorded. | | `masks_folder_unreadable` | Error | A masks folder given to a later brick (`RunInputs.open(..., masks_root=...)`) cannot be listed, for example for lack of permission, so its masks cannot be checked against the run (`MasksFolderUnreadableError`); the message names the folder and the reason. Check its permissions, or give another folder. | | `output_inside_masks` | Error | The output folder is inside the masks folder, where the run's files would be read as masks. Choose another output folder. | From da2ac87f02add2ae9048ace4a5404fe1245c2aa8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 08:58:08 +0000 Subject: [PATCH 14/25] Name the two plane memory figures apart; say why links out are refused The owner's run of the formin OME-Zarr mosaic (30720 x 36864 x 3, uint16, chunks 1 x 1024 x 1024; 4 December 2026) found two points: - run warned "would need up to 38.0 GiB" while xyc_plane_memory gave 14.8 GiB for the same plane. Both are right: the run's figure is one channel read and measured (33.8 GiB of it the histogram's working arrays), read_plane's the pixels of all three channels with no histogram. planes_read_in_blocks, the notebook's run plan and read_plane's PlaneMemoryError now say which is which. Tested on a lazily written store of the mosaic's size (zarr_tree.Unwritten). - link_outside_folder stays (owner decision of 2 November 2026, #81, plan Q64); its message now says the images behind the links are not found and why, and the fix says to move the data in. An opt-in that follows links is plan Q95, proposed, not decided. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp996hygHEfLZ4jtxi1A --- CHANGELOG.md | 24 ++++++ docs/contract.md | 7 +- docs/plan.md | 17 ++++ docs/user_guide.md | 13 +-- src/morphobricks_preprocessing/links.py | 13 ++- .../notebook_run_plan.py | 5 +- .../plane_channels.py | 10 ++- src/morphobricks_preprocessing/planes.py | 12 +-- tests/test_links.py | 42 +++++++++ tests/test_notebook_ui.py | 2 +- tests/test_plane_memory_names.py | 86 +++++++++++++++++++ tests/zarr_tree.py | 20 ++++- 12 files changed, 228 insertions(+), 23 deletions(-) create mode 100644 tests/test_plane_memory_names.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c5b8157..7b240c96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -101,6 +101,30 @@ refuses the skipped label images as unrecorded: refused, never silently wrong. used (`None` under v1). Regression fixture: a 320 x 320 crop of core 1B_D9 (`tests/data/he_core_1B_D9_crop.npz`, CC-BY-4.0, with its generator). Design: `docs/design/he-tissue-mask.md` ("`he_tissue_v2`"). +- **The two plane memory figures are named apart** (the owner's run of the formin OME-Zarr + mosaic, 30720 x 36864, 3 channels, `uint16`, chunks 1 x 1024 x 1024, 4 December 2026). `run` + warned that its planes "would need up to 38.0 GiB" while `xyc_plane_memory`, the bound + `RunInputs.read_plane` enforces and the next bricks check, gave about 14.8 GiB for the same + plane. Both figures are right and measure different things: the run's + (`PlaneLayout.memory_estimate`) is **one channel** read whole *and measured*: the chunks it + touches (2.1 GiB), the plane (2.1 GiB) and the histogram's working arrays (33.8 GiB: the + normalization brick's upper estimate of 32 bytes per pixel for an integer plane) with the + image QC sums; `xyc_plane_memory` is the pixels of **all three channels** in one + `(C, Y, X)` array with no histogram (4 planes and 3 copies of the chunks). No number + changes; the texts now say which is which: `planes_read_in_blocks` (and the notebook's run + plan) says "too large to measure whole ...: one channel and its histogram would need up to ..." + and that reading all channels without a histogram needs another amount; `read_plane`'s `PlaneMemoryError` says "the pixels + only: no histogram is computed". Tested on a lazily written OME-Zarr store of the mosaic's + size (metadata only, `tests/zarr_tree.Unwritten`). +- **`link_outside_folder` says why and what to do.** A link in the experiment (or masks) folder + to an image or OME-Zarr store kept elsewhere (`exp/ctrl/rep1/formin_mosaic.zarr -> + /data/formin_mosaic.zarr`) stays refused: the "contain" rule is the owner's decision of 2 + November 2026 (#81, plan §12 question 64; a run reads, fingerprints and records only what is + inside the selected folder). The message now says that the images behind the links are not + found and why, and the fix says to move (not copy) the data into the folder, instant on the + same drive, or to put the experiment's folders on the drive that holds the data, instead of + "Copy or move the files". Whether to offer an opt-in that follows such links is asked in plan + §12 question 95 (proposed, not decided). ### Added diff --git a/docs/contract.md b/docs/contract.md index bb63eca8..b5279ced 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -54,7 +54,7 @@ identity alone. | Uniqueness | Folder names need only be unique among siblings, ignoring case. Two folder names of one level (condition, biological repeat or technical repeat) that differ only in case are the error `case_conflict`, whether siblings or anywhere in the experiment (`ctrl/Rep1` and `treated/rep1`; decision D-e, §16; siblings only before D86). | | Names | Every label and `position_id` passes `check_identity_text` (§16): no leading or trailing whitespace, and not `""`, `NA`, `nan`, `none`, `null`, `n/a` or `` in any case, which table readers turn into a missing value. A folder or image name that fails is the error `invalid_name` (decision D-e; accepted before D86). | | Depth | At most three folder levels below the root. A folder below the technical-repeat level is an error. | -| Links | Contain (issue #81, owner 2 November 2026): a symbolic link to a file or folder (on Windows also a directory junction, which Python 3.11 does not report as a link) is followed only when its real path (`os.path.realpath`) is inside the experiment folder, itself resolved. A link that leaves it is not followed and is the error `link_outside_folder`, naming each link and its target (a broken link too); a link to a folder on its own path (the folder holding it, or one above) is `link_loop`; one file reached by two paths (a link and its target, two links, a linked folder and its target, or two hard links: the same device and inode, from the one `stat` taken per image or mask; owner, 2 November 2026) is `linked_twice`, naming both. A broken link that stays inside is kept and reported by its reader (`unreadable_tiff`, `unreadable_mask`), never skipped. Hidden and system names (§1) are skipped before any link is looked at, so a hidden link is never followed; a contained link *to* a hidden folder is followed, because that folder is itself never walked, so its files are found once, under the link's name, which the user chose. The links inside an OME-Zarr store are held to the same rule, though the store is not entered as a folder level: its folders are listed and only its links resolved, about 84 ms per 20,000 store files on each discovery (accepted by the owner, 2 November 2026). The masks folder follows the same rule (§15), with `RunInputs` (§9.1) and `convert` (§17) refusing the same links; one helper, `links.LinkGuard`, walks both folders. | +| Links | Contain (issue #81, owner 2 November 2026): a symbolic link to a file or folder (on Windows also a directory junction, which Python 3.11 does not report as a link) is followed only when its real path (`os.path.realpath`) is inside the experiment folder, itself resolved. A link that leaves it is not followed and is the error `link_outside_folder`, naming each link and its target (a broken link too), saying that what is behind it is not found and why, and telling the user to move the data in (v0.10.1; an opt-in to follow such links is plan §12 question 95, not decided); a link to a folder on its own path (the folder holding it, or one above) is `link_loop`; one file reached by two paths (a link and its target, two links, a linked folder and its target, or two hard links: the same device and inode, from the one `stat` taken per image or mask; owner, 2 November 2026) is `linked_twice`, naming both. A broken link that stays inside is kept and reported by its reader (`unreadable_tiff`, `unreadable_mask`), never skipped. Hidden and system names (§1) are skipped before any link is looked at, so a hidden link is never followed; a contained link *to* a hidden folder is followed, because that folder is itself never walked, so its files are found once, under the link's name, which the user chose. The links inside an OME-Zarr store are held to the same rule, though the store is not entered as a folder level: its folders are listed and only its links resolved, about 84 ms per 20,000 store files on each discovery (accepted by the owner, 2 November 2026). The masks folder follows the same rule (§15), with `RunInputs` (§9.1) and `convert` (§17) refusing the same links; one helper, `links.LinkGuard`, walks both folders. | | Mount points | Refused (owner, 3 November 2026), as far as they can be seen: a folder (or file) below the experiment folder or the masks folder that is a mount point by the rules below is not entered and is the error `mounted_folder`, naming it. A mount point is a path listed in Linux's `/proc/self/mountinfo` (the only way to see a bind mount of the same file system, for which `os.path.ismount` and the device number report an ordinary folder), or a folder, image or mask file on another device (`st_dev`) than the selected folder: another file system or Windows volume, or a Btrfs subvolume (a file's device comes from the one `stat` taken per image or mask; review of rc5). The selected folder itself may be on any mount. The same rule holds inside OME-Zarr stores (their files are held to the mount table only: they are not `stat`ed), and `check`, `run`, `convert` and `RunInputs` refuse the same mount points (a refused run publishes no scientific outputs and leaves the sources untouched; its discovery report is written). **Not seen:** a mount created after the walk started (the table is read once per walk); and where no mount table can be read (macOS, BSD, Windows, a Linux without `/proc`), a mounted single file or a mount of the same device (BSD `nullfs`). macOS `bindfs` (FUSE) and Windows mounted folders have another device, and a Windows mounted folder is also a mount-point reparse point, held to the link rule. **Refused although not mounted:** on an overlay file system (`overlayfs`, as in many containers) whose layers are on different file systems, mounted with `xino=off`, files (not folders) may report another `st_dev` than the selected folder and are then `mounted_folder` (copy the experiment to an ordinary folder, or use `xino=on` or `auto`). | | Unlisted store folders | A folder inside an OME-Zarr store (in the experiment or the masks folder) that cannot be listed (permissions, a disconnected drive) is the error `store_unreadable` (#392), naming each such folder: its links and mount points are not known, so the store is not taken as checked. Before, it was only logged and the store passed. Like the link errors, `RunInputs` (§9.1) and `convert` (§17) refuse it too (`links.LINK_CODES`). | | Hard links | An image or mask whose link count is above 1 (`st_nlink`, from the one `stat` taken per image or mask; it has other names, perhaps outside the folder, through which it can change) is the warning `hard_linked_file`, naming it and its count (owner, 3 November 2026). It is read and fingerprinted as any other file; the files inside an OME-Zarr store are not counted. | @@ -379,7 +379,10 @@ It gives: names X before Y (for example `ZXY`) is returned Y before X, as the run read it; nothing else is reordered. The memory limit of `read_plane` (default 1 GiB) counts only reading the plane, not the histogram arrays a run needs (audit I2), and it counts reading **every - channel** (issue #344): the `(C, Y, X)` result is allocated once and filled straight from + channel** (issue #344). It is therefore another figure than the run's + (`PlaneLayout.memory_estimate`, named by `planes_read_in_blocks`: one channel read and + measured); the texts name them apart (v0.10.1: for the 30720 x 36864 x 3 `uint16` mosaic in + 1024 x 1024 chunks, 38.0 GiB for the run, 14.8 GiB for `read_plane`): the `(C, Y, X)` result is allocated once and filled straight from the decoded pages, a page holding several channels (interleaved RGB, planar samples) is decoded once for all of them, and only one page is held at a time. Before any pixel is read, `read_plane` raises `PlaneMemoryError` when the bound of that whole read diff --git a/docs/plan.md b/docs/plan.md index c0b5ca03..affaaa31 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -1865,3 +1865,20 @@ Raised during review; to be decided before the milestones that need them: 2026):* a TOML file beside `morphobricks.toml`, `ignored_masks.toml`, recorded in the run manifest (`ignored_masks`, with its SHA-256); the owner also asked for a review of how many files the output folder holds, and a consolidation if it gets out of hand (a follow-up). +95. Should an experiment folder be allowed to link to images kept elsewhere (the owner's run of + the formin OME-Zarr mosaic, 4 December 2026: `exp/ctrl/rep1/formin_mosaic.zarr -> + /data/formin_mosaic.zarr` was refused with `link_outside_folder` and no image was found)? + *Kept for v0.10.1 (pull request from `fix/symlink-and-plane-memory`, 4 December 2026), as + question 64 decided:* the rule stays "contain"; the message now says that the images + behind the links are not found and why (a run reads, fingerprints and records only what is + inside the selected folder; a file behind a link out can change or move through its other + path unseen), and the fix says to move the data in (instant on the same drive) or to put + the experiment's folders on the drive that holds it. *Proposed, pending the owner's + decision:* an explicit opt-in, for example `run --follow-links` / `describe + --follow-links` and a notebook tick, recorded in the run manifest so that the run's + identity and fingerprints cover the link targets (their real paths, sizes, modification + times and inventory digests, with the content SHA-256 under `--verify-content`), and that + `RunInputs.open` and the bricks refuse a folder whose links lead elsewhere than recorded. + The trade-off: no move or reorganisation of large data, against a run whose inputs live + outside the folder it names (another user or a sync tool can change them; `linked_twice` + and the mount-point rule still apply). Not built until decided. diff --git a/docs/user_guide.md b/docs/user_guide.md index 481c2542..5e8341cc 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -184,9 +184,12 @@ experiment/ `.DS_Store`, `Thumbs.db`, `desktop.ini` and `__MACOSX` are ignored without a message. - Links (symbolic links, and junctions on Windows) are followed only when they stay inside the experiment folder; the same holds for the masks folder. A link to a file or folder - outside it is an error (`link_outside_folder`) naming the link and its target: nothing - outside the folder you selected is read, so copy the data in or select a folder that - holds it. A link back to a folder above it is an error (`link_loop`), and so is one file + outside it is an error (`link_outside_folder`) naming the link and its target, and the + images behind it are not found: a run reads, fingerprints and records only what is inside + the folder you selected, so a file reached through a link out could change or move without + the run seeing it. Move (do not copy) the data into the folder: on the same drive a move is + instant, however large the image. Or put the experiment's folders on the drive that holds + the data and select that folder. A link back to a folder above it is an error (`link_loop`), and so is one file reached by two paths, a link and its target or two hard links (`linked_twice`): it would count twice. - A mounted folder inside the experiment or masks folder (another disk, a network share, or @@ -1745,7 +1748,7 @@ continues. | `description_unreadable` | Error | `morphobricks.toml` or `morphobricks.records.jsonl` cannot be read. A description the reader refuses is reported with its own code (`E_*`, `R_FILE_SYMLINK`) and table path. | | `unreadable_folder` | Error | A folder could not be opened. Check permissions. | | `store_unreadable` | Error | A folder inside an OME-Zarr image could not be listed, so whether it holds links or mount points leading outside the selected folder is not known. Check the folder's permissions (and that the drive is connected), then check again. | -| `link_outside_folder` | Error | A link in the experiment or masks folder leads outside it (the message names each link and its target), and nothing outside the selected folder is read. Copy or move the files in, or select a folder that holds them, then remove the link. | +| `link_outside_folder` | Error | A link in the experiment or masks folder leads outside it (the message names each link and its target), so the images or masks behind it are not found: a run reads, fingerprints and records only what is inside the selected folder. Move (do not copy) the data in, instant on the same drive, or put the experiment's folders on the drive that holds the data and select that folder; then remove the link. | | `link_loop` | Error | A link leads back to a folder that holds it. Remove it. | | `mounted_folder` | Error | A folder (or file) in the experiment or masks folder is a mount point: another disk or share, or a bind mount of another folder, so its files come from outside the selected folder. It is named and not entered. Copy the files in, or select the mounted folder itself. Where the system's mount table cannot be read (macOS, Windows), only a mount of another device is seen. | | `hard_linked_file` | Warning | An image or mask has other names (hard links; the message gives the number), perhaps outside the folder, so it can change through a name the run does not see. It is read as usual. Replace the hard link with a copy if it may change. | @@ -1826,7 +1829,7 @@ continues. | `non_tiff_file`, `empty_folder` | Warning | Files or folders that are skipped. | | `image_named_as_mask` | Error | An image is named like a mask of another image (`f1_mask.tif` beside `f1.tif`; the endings `_mask`, `_masks`, `_cp_masks`, `_labels`, `_label`, `_seg`, `_segmentation`), and a mask is never analysed as an image. If it is a mask, move it into a masks folder outside the experiment, or exclude it; if it is an image, rename it. | | `mask_folder_in_experiment` | Warning | A folder inside the experiment is named like a masks folder (`masks`, `ctrl_masks`, `CellLabels`) and holds files named like masks of the images; they would be analysed as images. Move it out of the experiment and give it as the masks folder, or rename it if these are images. | -| `planes_read_in_blocks` | Warning | Planes too large for the memory limit are read in blocks. The results are the same; nothing to do. Raise the limit to read them whole, which is faster. | +| `planes_read_in_blocks` | Warning | Planes too large to measure whole within the memory limit are read and measured in blocks. The figure is the run's own need: one channel read and its histogram computed at once (mostly the histogram's working arrays). Reading every channel of a plane without a histogram, as `RunInputs.read_plane` and later bricks do, needs another amount (`xyc_plane_memory`), checked when they read; for a 30720 x 36864 x 3 `uint16` OME-Zarr mosaic about 38.0 GiB here and 14.8 GiB there. The results are the same; nothing to do. Raise the limit to read them whole, which is faster. | | `different_sizes` | Warning | Images have different widths or heights. Usually expected; otherwise check the camera settings. For a plain stack (no axes in its file), the sizes are compared once you confirm its axis roles, with those roles. | | `different_plane_counts` | Warning | Images have different numbers of depth slices, time points or other planes. Images with more planes weigh more in pooled statistics. Check the acquisition if this is not expected. For a plain stack, compared with its confirmed axis roles, as `different_sizes`. | | `different_pixel_sizes` | Warning | The physical pixel size or z-step (from the metadata or `calibration.csv`) differs between images by more than 0.1 % (for example different objectives). Images outside the largest group of matching sizes are listed; when sizes only change by small steps from image to image, none is listed. Check the microscope settings if this is not intended. | diff --git a/src/morphobricks_preprocessing/links.py b/src/morphobricks_preprocessing/links.py index 5a3b0cbe..a33d74cc 100644 --- a/src/morphobricks_preprocessing/links.py +++ b/src/morphobricks_preprocessing/links.py @@ -296,11 +296,16 @@ def issues(self) -> list[ValidationIssue]: error( LINK_OUTSIDE, f"{plural(len(self.outside), 'link')} in the {self.what} " - f"{agree(self.outside, 'leads', 'lead')} outside it (link -> target), " - "and nothing outside the selected folder is read: not followed.", + f"{agree(self.outside, 'leads', 'lead')} outside it (link -> target), so " + "the images or masks behind them are not found. Links are followed only " + "inside the selected folder: a run reads, fingerprints and records only " + "what is inside it, and a file behind such a link could be changed or " + "moved through its other path without the run seeing it.", self.outside, - f"Copy or move the files into the {self.what}, or select a folder that " - "holds them, then remove the links.", + f"Move (do not copy) the data into the {self.what}: on the same drive a " + "move is instant, however large the image. Or put the experiment's " + "folders on the drive that holds the data, move the images into them and " + f"select that folder as the {self.what}. Then remove the links.", ) ) if self.loops: diff --git a/src/morphobricks_preprocessing/notebook_run_plan.py b/src/morphobricks_preprocessing/notebook_run_plan.py index 2f97fcfe..2bc54abe 100644 --- a/src/morphobricks_preprocessing/notebook_run_plan.py +++ b/src/morphobricks_preprocessing/notebook_run_plan.py @@ -184,8 +184,9 @@ def _memory_plan(self, review: AxisReview) -> tuple[str, str]: line = ( f"{plural(len(plan.blocked), 'image')} " f"{'has' if len(plan.blocked) == 1 else 'have'} " - f"planes too large to read whole within the memory limit of {limit} (they need " - f"up to {largest}), so they will be read in blocks. The histograms are exactly the " + f"planes too large to measure whole within the memory limit of {limit} " + f"(reading one channel and computing its histogram at once needs up to " + f"{largest}), so they will be read in blocks. The histograms are exactly the " "same; reading takes longer. To read them whole, raise the memory limit to " f"{largest} or more in Settings above (untick Use the recommended " "settings), " diff --git a/src/morphobricks_preprocessing/plane_channels.py b/src/morphobricks_preprocessing/plane_channels.py index a7be09a4..15ed1af0 100644 --- a/src/morphobricks_preprocessing/plane_channels.py +++ b/src/morphobricks_preprocessing/plane_channels.py @@ -87,6 +87,13 @@ def xyc_plane_memory( ) -> int: """Return the working memory :func:`read_xyc_plane` checks, from the header only. + This is the memory of reading the pixels of ``channel_count`` channels into one + ``(C, Y, X)`` array, with no histogram. It is not a run's measuring memory + (:attr:`.planes.PlaneLayout.memory_estimate`, the figure of ``planes_read_in_blocks``: + one channel read and its histogram and image QC computed), so the two figures differ + for the same plane: for the 30720 x 36864 x 3 ``uint16`` mosaic in 1024 x 1024 chunks, + about 14.8 GiB here and 38.0 GiB for the run (most of it the histogram's arrays). + ``channel_count`` defaults to the image's channel count (1 without a channel axis). For TIFF the bound is of the pages holding the plane at ``z`` and ``t``, sized from their own strip or tile byte counts (pages can compress very differently). The request is checked @@ -248,7 +255,8 @@ def _refuse_over(memory: int, layout: PlaneLayout, count: int, path: str | os.Pa return channels = "its channel" if count == 1 else f"all {count} channels" raise PlaneMemoryError( - f"Reading one plane of {Path(path).name} whole, {channels}, needs about " + f"Reading one plane of {Path(path).name} whole, {channels} into one array (the " + f"pixels only: no histogram is computed), needs about " f"{format_bytes(memory)} of working memory, more than the limit of " f"{format_bytes(layout.memory_limit)}. Raise the memory limit if this computer " "has enough memory, or read the plane in windows." diff --git a/src/morphobricks_preprocessing/planes.py b/src/morphobricks_preprocessing/planes.py index dc976fce..6a0ba7b0 100644 --- a/src/morphobricks_preprocessing/planes.py +++ b/src/morphobricks_preprocessing/planes.py @@ -296,8 +296,8 @@ class PlaneLayout: Size of a page as stored in the file (compressed size, if compressed); 0 for OME-Zarr, whose compressed chunk sizes are not known in advance. memory_estimate - Estimated working memory to read one whole plane and, except for - :func:`read_plane`, compute its histogram, in bytes. + Working memory to read one whole plane of one channel and (except for :func:`read_plane`) + compute its histogram and QC, in bytes; not :func:`.plane_channels.xyc_plane_memory`. memory_limit The memory limit the layout was worked out for, in bytes. block_shape @@ -651,10 +651,10 @@ def check_planes( issues.append( warning( "planes_read_in_blocks", - f"The planes of {plural(len(blocked), 'image')} are too large to read whole " - f"within the memory limit of {format_bytes(memory_limit)} (they would need up " - f"to {format_bytes(largest)}), so they will be read in blocks. The histograms " - "are exactly the same; reading takes longer.", + f"The planes of {plural(len(blocked), 'image')} are too large to measure whole " + f"within the limit of {format_bytes(memory_limit)}: one channel and its histogram " + f"would need up to {format_bytes(largest)}, so blocks are read (exactly the same " + "histograms). Reading all channels without a histogram needs another amount.", [rel for rel, _ in blocked], "Nothing needs to be done. To read the planes whole, which is faster, raise " f"the memory limit to {format_bytes(largest)} or more if this computer has " diff --git a/tests/test_links.py b/tests/test_links.py index 2318198e..217736b8 100644 --- a/tests/test_links.py +++ b/tests/test_links.py @@ -291,3 +291,45 @@ def test_a_broken_link_in_the_masks_folder_is_named(clean): pre = preflight(clean.experiment, clean.output, masks_folder=clean.masks) issue = _issue(pre.masks.issues, "unreadable_mask") assert issue.is_error and issue.paths == ("Cells/ctrl/rep1/a.tif",) + + +def _says_why_and_what_to_do(issue): + """The refusal says why links out are not followed and what to do instead (4 Dec 2026).""" + assert "not found" in issue.message + assert "fingerprints and records only what is inside it" in issue.message + assert "Move (do not copy) the data into the experiment folder" in issue.action + assert "instant" in issue.action and "remove the links" in issue.action + + +def test_a_file_link_out_says_why_it_is_refused_and_what_to_do(tree): + root, outside = tree + (root / "ctrl/rep1/b.tif").symlink_to(outside / "far.tif") + found = discover_experiment(root) + assert "ctrl/rep1/b.tif" not in found.images + _says_why_and_what_to_do(_issue(found.issues, "link_outside_folder")) + + +def test_a_linked_ome_zarr_store_says_why_it_is_refused_and_what_to_do(tree): + """The owner's case: exp/ctrl/rep1/mosaic.zarr -> a store kept elsewhere.""" + pytest.importorskip("zarr") + from zarr_tree import write_ngff + + root, outside = tree + write_ngff(outside / "mosaic.zarr", np.zeros((3, 4, 4), np.uint16), axes="cyx") + (root / "ctrl/rep1/mosaic.zarr").symlink_to(outside / "mosaic.zarr", target_is_directory=True) + found = discover_experiment(root) + assert "ctrl/rep1/mosaic.zarr" not in found.images + issue = _issue(found.issues, "link_outside_folder") + assert issue.paths == (f"ctrl/rep1/mosaic.zarr -> {(outside / 'mosaic.zarr').resolve()}",) + _says_why_and_what_to_do(issue) + + +def test_a_mask_link_out_tells_to_move_the_mask_into_the_masks_folder(clean): + mask = clean.masks / "Cells/ctrl/rep1/a.tif" + real = clean.masks.parent / "elsewhere.tif" + mask.rename(real) + mask.symlink_to(real) + pre = preflight(clean.experiment, clean.output, masks_folder=clean.masks) + issue = _issue(pre.masks.issues, "link_outside_folder") + assert "Move (do not copy) the data into the masks folder" in issue.action + assert "select that folder as the masks folder" in issue.action diff --git a/tests/test_notebook_ui.py b/tests/test_notebook_ui.py index 08b78c18..7e9fd921 100644 --- a/tests/test_notebook_ui.py +++ b/tests/test_notebook_ui.py @@ -752,7 +752,7 @@ def fail(*args, **kwargs): nb.confirm_button.click() nb.image_type_checked.button.click() plan = nb.plan.value - assert "1 image has planes too large to read whole" in plan + assert "1 image has planes too large to measure whole" in plan assert "will be read in blocks" in plan and "exactly the same" in plan assert "ctrl/rep1/big.tif" in plan and "small.tif" not in plan assert "cannot be read within the memory limit" not in plan diff --git a/tests/test_plane_memory_names.py b/tests/test_plane_memory_names.py new file mode 100644 index 00000000..f3dc2506 --- /dev/null +++ b/tests/test_plane_memory_names.py @@ -0,0 +1,86 @@ +"""The two plane memory figures, named apart (owner's mosaic run of 4 December 2026). + +For one plane of the formin mosaic (OME-Zarr, 30720 x 36864, 3 channels, uint16, chunks +1 x 1024 x 1024) the run warned that its planes "would need up to 38.0 GiB" while +``xyc_plane_memory`` (the bound ``RunInputs.read_plane`` enforces) gave about 14.8 GiB. Both +are right, and different: the run's figure is one channel read *and measured* (most of it +the histogram's working arrays), the other the pixels of all three channels with no +histogram. The texts now say which is which. The store is written lazily (metadata only). +""" + +from __future__ import annotations + +import numpy as np +import pytest +from morphobricks_normalization.histogram import estimate_histogram_memory + +from morphobricks_preprocessing.axes import AxisMapping +from morphobricks_preprocessing.image_qc import qc_memory +from morphobricks_preprocessing.plane_channels import ( + OPEN_BYTES, + ZARR_COPIES, + read_xyc_plane, + xyc_plane_memory, +) +from morphobricks_preprocessing.planes import ( + PlaneMemoryError, + check_planes, + format_bytes, + plane_layout, +) + +pytest.importorskip("zarr") +from zarr_tree import Unwritten, write_ngff # noqa: E402 + +Y, X, C = 30720, 36864, 3 +CHUNK = 1024 +REL = "ctrl/rep1/formin_mosaic.zarr" +MAPPING = AxisMapping("CYX", ("C", "Y", "X")) +PLANE = Y * X * 2 # one channel, uint16 +CHUNKS = (Y // CHUNK) * (X // CHUNK) * CHUNK * CHUNK * 2 # every chunk one plane touches + + +@pytest.fixture +def mosaic(tmp_path): + root = tmp_path / "exp" + write_ngff(root / REL, Unwritten((C, Y, X), "uint16"), axes="cyx", chunks=(1, CHUNK, CHUNK)) + store_bytes = sum(f.stat().st_size for f in (root / REL).rglob("*") if f.is_file()) + assert store_bytes < 64 * 1024 # metadata only: no chunk is written + return root + + +def test_the_run_figure_is_one_channel_read_and_measured(mosaic): + layout = plane_layout(mosaic / REL, MAPPING) + histogram = estimate_histogram_memory(Y * X, np.dtype("uint16"), range_check=True) + finished = C * 8 * 65536 + assert layout.memory_estimate == ( + CHUNKS + PLANE + histogram + qc_memory(Y, X, False) + finished + ) + assert histogram > 0.8 * layout.memory_estimate # mostly the histogram's arrays + assert format_bytes(layout.memory_estimate) == "38.0 GiB" + + +def test_the_read_plane_figure_is_every_channel_without_a_histogram(mosaic): + memory = xyc_plane_memory(mosaic / REL, MAPPING) + assert memory == (C + 1) * PLANE + ZARR_COPIES * CHUNKS + OPEN_BYTES + assert format_bytes(memory) == "14.8 GiB" + assert format_bytes(xyc_plane_memory(mosaic / REL, MAPPING, 1)) == "10.5 GiB" + + +def test_the_run_warning_names_its_figure_as_one_channel_measured(mosaic): + issues = check_planes(mosaic, {REL: MAPPING}) + (issue,) = issues + assert issue.code == "planes_read_in_blocks" and issue.paths == (REL,) + assert "38.0 GiB" in issue.message and "one channel" in issue.message + assert "one channel and its histogram" in issue.message + assert "all channels without a histogram needs another amount" in issue.message + assert "would need up to 38.0 GiB" in issue.message + assert "raise the memory limit to 38.0 GiB" in issue.action + + +def test_the_read_plane_refusal_names_its_figure_as_pixels_only(mosaic): + with pytest.raises(PlaneMemoryError) as caught: + read_xyc_plane(mosaic / REL, MAPPING) + text = str(caught.value) + assert "all 3 channels" in text and "14.8 GiB" in text + assert "the pixels only: no histogram is computed" in text diff --git a/tests/zarr_tree.py b/tests/zarr_tree.py index cb5a9c39..70485a87 100644 --- a/tests/zarr_tree.py +++ b/tests/zarr_tree.py @@ -15,6 +15,20 @@ def zarr_major() -> int: return int(zarr.__version__.split(".")[0]) +class Unwritten: + """An image's shape and type only: :func:`write_ngff` writes its metadata, no chunk. + + Reading it gives zarr's fill value (0); the store holds no pixel, so an image of any + size (the 30720 x 36864 x 3 mosaic of the owner's 4 December 2026 run) costs a few + kilobytes on disk. + """ + + def __init__(self, shape, dtype): + self.shape = tuple(shape) + self.dtype = np.dtype(dtype) + self.ndim = len(self.shape) + + def write_ngff( # noqa: PLR0913 path, data, @@ -44,7 +58,8 @@ def write_ngff( # noqa: PLR0913 pytest.skip("OME-NGFF 0.5 needs zarr 3") path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) - data = np.asarray(data) + if not isinstance(data, Unwritten): + data = np.asarray(data) group = _group(zarr, path, 3 if version == "0.5" else 2) chunks = chunks or (*(1,) * (data.ndim - 2), *data.shape[-2:]) _array(group, "0", data, chunks) @@ -139,5 +154,6 @@ def _array(group, name, data, chunks): array = group.create_array(name, shape=data.shape, chunks=chunks, dtype=data.dtype) else: array = group.create_dataset(name, shape=data.shape, chunks=chunks, dtype=data.dtype) - array[...] = data + if not isinstance(data, Unwritten): + array[...] = data return array From 62e97fe7c9c99e22f45ffd74673104f02078dd8f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 12:07:07 +0200 Subject: [PATCH 15/25] Write OME-Zarr copies in 1024 x 1024 chunks; name stores too coarse for windows convert --store ome-zarr (and the notebook's copy) wrote each plane as one chunk, so a windowed reader decoded the whole plane for every window and refused the first patch of a large slide after check had passed. - ome_zarr_copy: chunks 1 x ... x min(Y,1024) x min(X,1024), written block by block in place (edge chunks full size, zero-filled); no pyramid. - windows: smallest_window_memory, chunk_note (fix advice on refusals). - window_reader: WindowReader refuses at open an OME-Zarr whose chunks leave no window within the limit with its cache. - window_chunks (new): check_window_chunks -> warning chunks_too_large_for_windows, from check and run. - tests/test_ome_zarr_chunks.py; CHANGELOG, contract, user guide, AGENTS. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 8 +- CHANGELOG.md | 29 +++ docs/contract.md | 10 +- docs/user_guide.md | 6 + pyproject.toml | 1 + src/morphobricks_preprocessing/cli.py | 18 +- .../ome_zarr_copy.py | 118 ++++++++++-- src/morphobricks_preprocessing/run/steps.py | 3 + .../window_chunks.py | 108 +++++++++++ .../window_reader.py | 33 +++- src/morphobricks_preprocessing/windows.py | 49 ++++- tests/test_ome_zarr_chunks.py | 170 ++++++++++++++++++ 12 files changed, 526 insertions(+), 27 deletions(-) create mode 100644 src/morphobricks_preprocessing/window_chunks.py create mode 100644 tests/test_ome_zarr_chunks.py diff --git a/AGENTS.md b/AGENTS.md index 67accd19..607d1dd1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -298,7 +298,10 @@ src/morphobricks_preprocessing/ WindowLayoutError (shared by both); window_reader.py WindowReader (#304): many windows of one image through a bounded, thread-safe block_cache.BlockCache of decoded pieces (opt-in), - RunInputs.window_reader -> RunWindowReader by channel IDs; + RunInputs.window_reader -> RunWindowReader by channel IDs; it refuses at + open an OME-Zarr whose chunks leave no window within the limit (v0.10.1); + window_chunks.py check_window_chunks: check/run warn about such stores + (chunks_too_large_for_windows, e.g. one chunk per plane); window_map.py map_plan / map_windows / iter_windows: a function over windows in a bounded thread pool, results in window order, memory planned and checked against a budget before any read (lazy-windows §5); @@ -599,7 +602,8 @@ src/morphobricks_preprocessing/ changed right there, the proposal the Axes step starts from notebook_zarr_copy.py the first screen's "Also save a copy as OME-Zarr" and the Axes step's card that writes it once the roles are confirmed; ome_zarr_copy.py - the writers (OME-NGFF 0.4, written directly) and the copy's name + the writers (OME-NGFF 0.4, written directly, chunks of at most + 1 x 1024 x 1024 since v0.10.1) and the copy's name notebook_projection.py the Axes step's card for Z-stacks: choose the projection, write the projected copies into the output folder (convert_experiment), open them as the experiment; the greyed 3-D option diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b240c96..818440f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,35 @@ refuses the skipped label images as unrecorded: refused, never silently wrong. ### Fixed +- **OME-Zarr copies are written in spatial chunks, so a later brick can read them in windows.** + `convert --store ome-zarr`, the notebook's OME-Zarr copy and `convert_experiment(..., + store="ome-zarr")` wrote each plane as one chunk (the whole Y and X). A windowed route + (fiberfeatures' `run.execution_route = "patch_window"`, through `RunInputs.window_reader`) + decodes a chunk whole for any window, so it refused the first patch of a large converted slide + (`WindowMemoryError`) after `check` had passed. Copies are now written in chunks of one plane by + at most 1024 x 1024 pixels (`1 x ... x min(Y, 1024) x min(X, 1024)`, bioformats2raw's default; + `ome_zarr_copy.CHUNK_SIDE`, `chunk_shape`), still uncompressed Zarr version 2 (OME-NGFF 0.4), + one level (no pyramid: the bricks read level 0 only). Each plane is written as it is read, + block by block within the memory limit, each block's part of each chunk written in place + (edge chunks at full size, zeros outside the image, as Zarr 2 stores them); a plane read in + blocks is never held whole. **Byte identity:** the pixels, the `.zattrs` and the conversion + record's other fields are unchanged, but a copy of an image larger than 1024 pixels along Y + or X is new bytes: its `0/.zarray` `chunks` and its chunk files (`0///`, + instead of one `0//0/0` per plane), so its `copy_sha256` differs. Copies of planes of at + most 1024 x 1024 pixels are byte for byte as before. A conversion into a folder that already + holds a copy written before keeps that copy (its plan and content are unchanged): convert + into a new folder to get the chunked copies. +- **`check` and `run` warn about an OME-Zarr image no window reader can serve** + (`chunks_too_large_for_windows`, new module `window_chunks`): from the header, the least a + window reader needs for a window of one pixel, through a cache of one chunk + (`window_chunks.window_chunk_need`, `windows.smallest_window_memory`), against the memory + limit; the warning names the images and says to convert the originals again into a new folder + (for a copy written before v0.10.1) or to save the image with chunks of at most 1024 x 1024 + pixels. `check` uses the default limit (1 GiB); `run` its `--memory-limit`. The same store is + refused when `WindowReader` / `RunInputs.window_reader` is opened on it with a cache that + leaves no room for one window (`WindowMemoryError`, naming the chunks and the fix), instead of + on its first window; a window refused for its memory names the chunks too. + `tests/test_ome_zarr_chunks.py`. - **An entry output is reusable in a conda environment** (Spec ADR 0007 RE10). Conda installs `setuptools` as an `.egg-info` with no `RECORD`, and `brick_identity` followed every requirement of the brick, every extra included, down to it: every record written there was diff --git a/docs/contract.md b/docs/contract.md index b5279ced..c7cf69f6 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -435,7 +435,13 @@ It gives: decodes, hits, evictions and bytes held. The cache holds at most `cache_bytes` (a whole number above 0, below `memory_limit`; a piece larger is used once and not kept), counts in each window's memory estimate (a window whose own working memory and `cache_bytes` together are - over `memory_limit` is `WindowMemoryError`), and is safe to share between threads (a piece + over `memory_limit` is `WindowMemoryError`; an OME-Zarr image whose chunks are so large that + even a window of one pixel is over `memory_limit` with this cache is refused when the reader + is opened, `WindowMemoryError` naming the chunks and what to do, v0.10.1: a chunk is decoded + whole for any window; `check` and `run` warn about such an image first, + `chunks_too_large_for_windows`, from `window_chunks.check_window_chunks`, which counts a + cache of one chunk; `window_chunks.window_chunk_need(path, mapping)` gives that figure for a + consumer's own check), and is safe to share between threads (a piece asked by several at once is decoded once, and every thread that waited gets that decode, also when the piece is not kept; a kept piece is immutable, its bytes in a read-only buffer; the cache is per process, never shared). Pieces are kept under the image's path, the @@ -1525,7 +1531,7 @@ exclude=, missing_as_singleton=, memory_limit=, progress=)` (`conversion`), the | Repeat | A copy already in the tree is reused when its source (fingerprint and axes), roles, copy axes, pixel sizes, unknown sizes (roles and reasons), channel names, significant bits, the copy's fingerprint and the copy's SHA-256 (read whole) are as recorded; a new image is added; when every copy is reused the record is kept as it was (same SHA-256). Anything else (a source changed, other roles, a copy changed, an image no longer in the experiment, another experiment's copy tree, a file at a new image's place that the record does not list) is `copy_differs`: nothing is overwritten. A conversion record that cannot be read, or of another version than 4, is `conversion_record_unreadable`. | | Conversion record | `.morphobricks-conversion.json` in the copy tree's root (a dot-file, so discovery skips it), record version 4: `source_root`, `mapping`, `projection` (null, or `{method, z_range}`: the method and slice range of a tree of Z-projected copies, see "Projected copies" below), `missing_as_singleton`, `written_at`, `versions`, and per image `relative_path`, `action` (`converted` or `copied`), `reason` (the axis code, `excluded`, or null), `source` and `copy` fingerprints (`size`, `mtime_ns`), `copy_sha256` (the copy's SHA-256, computed in one pass after it is written; an OME-Zarr copy's is the SHA-256 of its files' relative paths and SHA-256s in path order, its `labels` group left out as for fingerprints: `content_hash`), `source_axes`, `roles`, `copy_axes`, `pixel_sizes` (by role, as §9), `unknown_sizes` (role: why), `channel_names` (as the copy holds them; `[]` for none), `significant_bits` (or null), `projection` (null, or the projected copy's provenance, below) and, only for an image converted or projected into an OME-Zarr copy, `source_relative_path` (below). Sources keep the fingerprint rule (design v0.4 §1); the copies' SHA-256 is the owner's decision of 2 November 2026 (plan §12 question 59 (16)). Version 2 (PP-11c) added `copy_sha256`, `channel_names` and `significant_bits`; version 3 (issue #176) added the record-level `projection` and the entry's `projection`, and the action `projected`; version 4 (owner decision of 12 November 2026, before v0.5.2) added the entry's `source_relative_path` of an OME-Zarr copy, which a version 3 reader would ignore, looking for the source at the copy's path and warning `conversion_source_changed`. Only version 4 is read (SWEEP-PP: no backward compatibility, Spec ADR 0002 AR10): a record of any other version, 1 to 3 included, is refused everywhere it is read (`convert`, the run's `review_conversion`, `RunInputs`), never converted, with a message to convert the originals again into a new folder. `read_conversion_record(folder)` reads it with its SHA-256. | | Projected copies (issue #176, record version 3 and later) | A tree made with a Z projection holds, for every image, a 2-D copy of its Z-stack made with the record-level `projection` `{method, z_range}` (`max`, `mean` or `sum`; there is no default method; `z_range` is `[start, stop]`, zero-based, stop excluded, the same for every image, or null for every slice). An entry has the action `projected` and a `projection` object with exactly: `source_relative_path`, `source_content_sha256` (the source's content as read while writing), `source_z_axis` (`{letter, index}` of the header's Z axis, or null for an image without one, which is one slice), `source_z_size`, `z_range` (the slices actually used), `method`, `source_dtype`, `output_dtype`, `dtype_rule`, `rounding` (`none`, `float64, one division` or `float64 addition, z ascending`), `nan_policy` (`propagate`), `dropped_sizes` (`{"Z": {value, unit, source}}`, or `{"Z": null}` when the source gave no Z size: the Z size is never written to the copy) and `significant_bits_dropped` (a reason, or null: kept for `max`, dropped for `sum` and `mean`). Excluded images stay plain copies (`copied`, reason `excluded`). The output type depends only on the input type, the method and the slice count (never on the data): `max` keeps the type; `sum` of `uint8`/`uint16` is `uint32`, of `int8`/`int16` is `int32`, of `uint32`/`int32` is `float64` holding the exact integer, of floats is `float64`; `mean` is `float64`; 64-bit integers are refused (`cannot_convert_pixel_type`). A sum or mean whose worst case (the type's extreme times the slices) could not be held exactly is refused (`projection_cannot_be_exact`), never wrapped or clipped. A NaN makes its pixel NaN, infinities are kept. The reader refuses an entry whose output type or rounding is not the table's for its method, a projected entry in a record without a projection (and the reverse), and a method or range that is not the record's. The reuse key holds the projection (everything of it except the content SHA-256, which the write computes), so another method or range into the same tree is `copy_differs`. Masks are never projected: `convert_experiment(..., projection=Projection(...), masks_folder=)` scans the masks folder from the headers only and refuses, before writing anything, masks of the images to project that have depth slices (`projection_masks_3d`) or more than Y and X with axes that are not named (`projection_masks_axes_unknown`); 2-D masks are left alone. The other refusals, all before anything is written: `nothing_to_project` (no image has a Z role), `projection_z_range_outside`, `projection_cannot_be_exact`, `cannot_convert_pixel_type`, `projection_over_memory_limit` (one input plane, the running plane and, when it is another type, the output plane must fit `memory_limit`) and `projection_zarr_not_supported` (OME-Zarr images are not projected yet). The copy's OME-XML holds an `Image/Description` with the method, slices, source, source SHA-256 and types, and a UUID derived from it, so one projection of one source is the same bytes; the source's content SHA-256 is taken before and after the projection and the source fingerprint before and after, and a source that changed is refused. A sum that overflows to infinity (`projection_overflow`) or adds an infinity to its opposite (`projection_undefined`) stops the conversion and is never written. Excluded images are copied byte for byte. | -| OME-Zarr copies (v0.5.2, record version 4) | `convert_experiment(..., store="ome-zarr")` (the notebook's **Also save a copy as OME-Zarr**; default `"ome-tiff"`) writes every image that is read as an OME-Zarr image instead of an OME-TIFF: also the images whose headers name their axes as confirmed, which are otherwise copied byte for byte. Excluded images and OME-Zarr images are copied byte for byte as before. With `projection` the projected copies are OME-Zarr. A copy is named after its image with `.ome.zarr` in place of the TIFF extension, in the same folder, so its position ID is the same; two images that would get one copy name are refused (`copy_names_collide`). In the record the entry's `relative_path` is the copy's path and `source_relative_path` (a key written only for such an entry: required there and refused on any other entry, so a source is never looked for at a copy's path; other entries are written as before) is the source's path relative to `source_root`; `significant_bits` is null (OME-NGFF 0.4 has no field for it). The store is OME-NGFF 0.4 (Zarr version 2), written directly: one array `0`, uncompressed, little-endian, one chunk per plane (the whole Y and X), metadata as sorted JSON, so one copy of one source is the same bytes. Each plane is the plane read under the confirmed roles, bit for bit; the axes are the roles (`t`, `c`, `z`, `y`, `x`) with the units of the copy's sizes, the level-0 `scale` holds the sizes and 1 for an unknown one, which is named under the multiscale's `metadata.unknown_scale` and so read as unknown; channel names are under `omero.channels[].label`, each channel with the `color` (`FFFFFF`) and `window` (the pixel type's whole range as `min`, `max`, `start`, `end`) that OME-NGFF 0.4 requires, display only and never read from the pixels; a projected copy's description is under `morphobricks.description`. Reading the copies needs the `zarr` extra, as for any OME-Zarr image. Plan, lock, `.partial` writes, reuse, the copy's SHA-256 and the checks of the run on the copies are those of the other copies. | +| OME-Zarr copies (v0.5.2, record version 4) | `convert_experiment(..., store="ome-zarr")` (the notebook's **Also save a copy as OME-Zarr**; default `"ome-tiff"`) writes every image that is read as an OME-Zarr image instead of an OME-TIFF: also the images whose headers name their axes as confirmed, which are otherwise copied byte for byte. Excluded images and OME-Zarr images are copied byte for byte as before. With `projection` the projected copies are OME-Zarr. A copy is named after its image with `.ome.zarr` in place of the TIFF extension, in the same folder, so its position ID is the same; two images that would get one copy name are refused (`copy_names_collide`). In the record the entry's `relative_path` is the copy's path and `source_relative_path` (a key written only for such an entry: required there and refused on any other entry, so a source is never looked for at a copy's path; other entries are written as before) is the source's path relative to `source_root`; `significant_bits` is null (OME-NGFF 0.4 has no field for it). The store is OME-NGFF 0.4 (Zarr version 2), written directly: one array `0`, uncompressed, little-endian, in chunks of one plane by at most 1024 x 1024 pixels along Y and X (`1 x ... x min(Y, 1024) x min(X, 1024)`; v0.10.1, one chunk per plane before: see `chunks_too_large_for_windows`), written block by block as the planes are read, each edge chunk at full size with zeros (the `fill_value`) outside the image, one level only (no pyramid), metadata as sorted JSON, so one copy of one source is the same bytes. Each plane is the plane read under the confirmed roles, bit for bit; the axes are the roles (`t`, `c`, `z`, `y`, `x`) with the units of the copy's sizes, the level-0 `scale` holds the sizes and 1 for an unknown one, which is named under the multiscale's `metadata.unknown_scale` and so read as unknown; channel names are under `omero.channels[].label`, each channel with the `color` (`FFFFFF`) and `window` (the pixel type's whole range as `min`, `max`, `start`, `end`) that OME-NGFF 0.4 requires, display only and never read from the pixels; a projected copy's description is under `morphobricks.description`. Reading the copies needs the `zarr` extra, as for any OME-Zarr image. Plan, lock, `.partial` writes, reuse, the copy's SHA-256 and the checks of the run on the copies are those of the other copies. | | The run on the copies | The user runs preprocessing on the copy tree with the same output folder (`--output`): the recorded experiment root becomes the copy tree and the report says so (`experiment_root_changed`, and `conversion` with the record, its SHA-256 and `source_root`; the text says "named-axis copies of ..."); every row is recomputed (the row key includes the read path, §9); the design, image type and calibration are kept (same relative paths). The manifest records `conversion_record_sha256`, and for projected copies the `projection` summary (§9); the report says "max projections of slices 1:4 (2 images) of " (and `conversion.projection` in `discovery_report.json`). Masks are paired as usual (the image has no Z now, so 2-D masks fit; a mask with depth slices stays `mask_planes_mismatch` and stops the run), and the run warns `masks_on_projected_images`, naming the method, for masks paired with projections, in the report and the manifest's `projection.warnings`. The run and `check` warn when a source changed or went missing after the conversion (`conversion_source_changed`) and refuse a copy that changed (its fingerprint or its SHA-256: each copy is read whole, so `check` and `run` on a copy tree cost one more read of the copies), went missing or was added since (`copy_changed_after_conversion`: an error since PP-12, owner decision of 2 November 2026; the run stops after the header checks, before any pixel is read, writing only its report, since `RunInputs` would refuse the run; the message says to convert the originals again into a new folder); an unreadable record stops the run (`conversion_record_unreadable`). `check` and `run` also read the OME `Image/Description` header (first page's description tag only, no pixels) of every analysed TIFF the record does not list as `projected`: a description that begins "MorphoBricks Z projection:" in a tree with no record, or whose record does not list the image as projected, is refused as `projection_record_missing` (owner decision of 8 November 2026; plain images are unaffected). `RunInputs` reads the copies like any images, and refuses a run whose conversion record changed or went missing since (`conversion_record_sha256`), is of version 1, or whose recorded images' copies no longer have the recorded fingerprint and SHA-256 (§9.1). | | Notebook (PP-11b) | Step 2's **Make named-axis copies (optional)** card, under the axis check, shown only when it reports images with `axes_yx_swapped`, `axes_contradict_header`, `axes_x_before_y` or `axes_not_named` for the roles being edited (design v0.4 §5: offered only for files with errors), and not with `folder_step(show_output=False)`. The roles are the user's: those confirmed in step 2, or the roles shown once the preview is checked and the card's own question is answered; any change of a role or of the missing-axes answer takes it back. A required folder for the copies (Browse…, or pasted) checked with the command's rule (`copy_folder_issues`); `preview_conversion` (`conversion_plan`, headers only, writes nothing) gives what will be converted and copied byte for byte (the command's `plan_conversion`), the space needed and the free space; then `convert_experiment` with a progress bar, under the copy tree's lock. Refusals use the existing cards (the lock card with **Remove the lock of a stopped run**, the rule of `--remove-stale-lock`). After the copies: the record's path, and **Check the copies in step 1**, which sets the experiment folder to the copy tree, keeps the output folder and checks again; the card says that the missing-axes answer must be given again and lists the copies whose relabelled sizes are unknown (`ConversionResult.unknown_sizes`), to state under **Pixel sizes**. | diff --git a/docs/user_guide.md b/docs/user_guide.md index 5e8341cc..46c971e3 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1256,6 +1256,11 @@ no field for colour, so the copies cannot say RGB themselves: describe them with `--image-type rgb --channels R,G,B`, and `check` and `run` then suggest the image type `rgb` from the published description (no `--image-type rgb` needed). Reading OME-Zarr copies needs the `zarr` extra; writing them does not. `--project` writes OME-Zarr projections the same way. +The copies are stored in chunks of one plane by at most 1024 x 1024 pixels (since v0.10.1; +before, one chunk per plane), so a later brick can read a large slide in windows; `check` +warns about an OME-Zarr image whose chunks are too large for that +(`chunks_too_large_for_windows`). Copies written before v0.10.1 are not rewritten by a new +conversion into the same folder: convert into a new folder. ```bash morphobricks-preprocessing convert /data/he --to /data/he_zarr --axes YXC --store ome-zarr @@ -1830,6 +1835,7 @@ continues. | `image_named_as_mask` | Error | An image is named like a mask of another image (`f1_mask.tif` beside `f1.tif`; the endings `_mask`, `_masks`, `_cp_masks`, `_labels`, `_label`, `_seg`, `_segmentation`), and a mask is never analysed as an image. If it is a mask, move it into a masks folder outside the experiment, or exclude it; if it is an image, rename it. | | `mask_folder_in_experiment` | Warning | A folder inside the experiment is named like a masks folder (`masks`, `ctrl_masks`, `CellLabels`) and holds files named like masks of the images; they would be analysed as images. Move it out of the experiment and give it as the masks folder, or rename it if these are images. | | `planes_read_in_blocks` | Warning | Planes too large to measure whole within the memory limit are read and measured in blocks. The figure is the run's own need: one channel read and its histogram computed at once (mostly the histogram's working arrays). Reading every channel of a plane without a histogram, as `RunInputs.read_plane` and later bricks do, needs another amount (`xyc_plane_memory`), checked when they read; for a 30720 x 36864 x 3 `uint16` OME-Zarr mosaic about 38.0 GiB here and 14.8 GiB there. The results are the same; nothing to do. Raise the limit to read them whole, which is faster. | +| `chunks_too_large_for_windows` | Warning | `check` and `run`: an OME-Zarr image is stored in chunks so large that a later brick reading it in windows (a patch-window route, through `RunInputs.window_reader`) cannot read even one window within the memory limit: a chunk is decoded whole for any window it holds, so a store in one chunk per plane is decoded whole for every window. Preprocessing itself reads it (in blocks). The same image is refused when a window reader is opened on it, with the same advice. If it is an OME-Zarr copy written by `convert --store ome-zarr` or the notebook before v0.10.1 (one chunk per plane), convert the original images again into a new folder (copies are now written in chunks of 1024 x 1024 pixels); otherwise save it again with chunks of at most 1024 x 1024 pixels along Y and X. | | `different_sizes` | Warning | Images have different widths or heights. Usually expected; otherwise check the camera settings. For a plain stack (no axes in its file), the sizes are compared once you confirm its axis roles, with those roles. | | `different_plane_counts` | Warning | Images have different numbers of depth slices, time points or other planes. Images with more planes weigh more in pooled statistics. Check the acquisition if this is not expected. For a plain stack, compared with its confirmed axis roles, as `different_sizes`. | | `different_pixel_sizes` | Warning | The physical pixel size or z-step (from the metadata or `calibration.csv`) differs between images by more than 0.1 % (for example different objectives). Images outside the largest group of matching sizes are listed; when sizes only change by small steps from image to image, none is listed. Check the microscope settings if this is not intended. | diff --git a/pyproject.toml b/pyproject.toml index 5f26ec6d..c8057452 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -477,6 +477,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.codec_bounds" = "io" "morphobricks_preprocessing.window_memory" = "pure" "morphobricks_preprocessing.window_reader" = "io" +"morphobricks_preprocessing.window_chunks" = "io" "morphobricks_preprocessing.block_cache" = "pure" "morphobricks_preprocessing.window_map" = "orchestration" "morphobricks_preprocessing.report" = "pure" diff --git a/src/morphobricks_preprocessing/cli.py b/src/morphobricks_preprocessing/cli.py index 4db3a546..6ff42a8e 100644 --- a/src/morphobricks_preprocessing/cli.py +++ b/src/morphobricks_preprocessing/cli.py @@ -41,6 +41,7 @@ from collections.abc import Sequence from pathlib import Path +from .axes import AxisReview from .cli_calibrate import add_calibrate_parser, calibrate_command, calibration_summary from .cli_convert import add_convert_parser, convert_command from .cli_convert_mask import add_convert_mask_parser, convert_mask_command @@ -85,6 +86,7 @@ from .run.description_run import load_description from .run.preflight import Preflight from .validation import ValidationIssue +from .window_chunks import check_window_chunks __all__ = ["build_parser", "main", "parse_size"] @@ -265,6 +267,18 @@ def _remove_stale_lock(args: argparse.Namespace) -> bool: return True +def _window_chunks(pre: Preflight, review: AxisReview) -> list[ValidationIssue]: + """Print and return the warning naming OME-Zarr chunks too large for windows (v0.10.1). + + Named by ``check``, before a later brick's windowed reads refuse them. + """ + chunks = check_window_chunks(pre.discovery.root, review) + if chunks: + print() + print(format_issues(chunks)) + return chunks + + def _check(args: argparse.Namespace) -> int: """Print what the preflight found and the suggested roles, and write the report.""" refusal = description_refusal(args) @@ -296,6 +310,7 @@ def _check(args: argparse.Namespace) -> int: print() print(format_issues(undeclared)) axis_errors = () + chunks: list[ValidationIssue] = [] if review is not None: # The suggested roles are the header's own, so they never contradict it; 'run' # checks the roles given with --axes. @@ -308,6 +323,7 @@ def _check(args: argparse.Namespace) -> int: if review.axis_check: print() print(format_issues(review.axis_check)) + chunks = _window_chunks(pre, review) print() # Suggested only where an image lacks some of the axes and is read with one plane. lacking = any(found.singleton_roles for found in review.file_mappings.values()) @@ -321,7 +337,7 @@ def _check(args: argparse.Namespace) -> int: f"Suggested image type: {type_review.suggested}, because {type_review.reason}. " "'run' uses it unless you give --image-type." ) - path, refusal = write_check_report(pre, args.output, review, extra=undeclared) + path, refusal = write_check_report(pre, args.output, review, extra=[*undeclared, *chunks]) print() print(format_issues([refusal]) if refusal else f"Report written to {path}" if path else "") blocked = not pre.ok or axis_errors or undeclared or refusal is not None diff --git a/src/morphobricks_preprocessing/ome_zarr_copy.py b/src/morphobricks_preprocessing/ome_zarr_copy.py index 0c5e2a6a..3b1447b3 100644 --- a/src/morphobricks_preprocessing/ome_zarr_copy.py +++ b/src/morphobricks_preprocessing/ome_zarr_copy.py @@ -8,8 +8,15 @@ The store is written directly (no ``zarr`` package is needed to write it; reading it needs the ``zarr`` extra, as for any OME-Zarr image): a Zarr version 2 group with one array ``0``, -uncompressed, one chunk per plane (the whole Y and X), little-endian, so every plane has a -fixed file and the same copy is the same bytes. Each plane is the plane read under the +uncompressed, little-endian, in chunks of one plane by at most :data:`CHUNK_SIDE` rows and +columns (``1 x ... x 1024 x 1024``, :func:`chunk_shape`), so every chunk has a fixed file and +the same copy is the same bytes. Spatial chunks let a later brick read a window of a large +image by decoding only the chunks under it (:mod:`.window_reader`): a whole plane in one chunk +had to be decoded whole for every window, which no memory limit could serve on a slide +(v0.10.1). Each plane is written as it is read, block by block (:meth:`.planes.Plane.blocks`, +within the memory limit), each block's part of each chunk written in place: a plane is never +held whole unless it is read whole. One level only (no pyramid): the brick reads level 0 alone +(:data:`.windows.LEVEL`). Each plane is the plane read under the confirmed roles, bit for bit; a projected copy's planes are computed as in :func:`.ome_tiff_copy.write_projected_copy`. The metadata follow the copy's layout (:class:`.copy_axes.CopyLayout`): the axes by role with their units, the level-0 ``scale`` from @@ -31,6 +38,7 @@ import os from dataclasses import replace from pathlib import Path +from typing import BinaryIO import numpy as np @@ -53,6 +61,12 @@ NGFF_VERSION = "0.4" _AXIS_TYPES = {"T": "time", "C": "channel", "Z": "space", "Y": "space", "X": "space"} BITS_NOT_WRITTEN = "OME-NGFF 0.4 has no field for significant bits" +CHUNK_SIDE = 1024 +"""The largest chunk along Y and along X of an OME-Zarr copy (one plane along every other axis). + +1024 x 1024 is bioformats2raw's default and common practice for OME-NGFF 0.4 images: 1 MiB +(``uint8``) to 8 MiB (``float64``) per chunk, so a window reader decodes a few MiB per chunk it +touches, while a slide of 100,000 x 100,000 pixels has about 10,000 chunk files per plane.""" OMERO_COLOUR = "FFFFFF" """The ``color`` of every ``omero`` channel (required by OME-NGFF 0.4; display only).""" @@ -141,6 +155,12 @@ def _json(path: Path, data: dict) -> None: path.write_bytes(text.encode("utf-8")) +def chunk_shape(shape: tuple[int, ...]) -> tuple[int, ...]: + """Return the chunks of a copy of ``shape``: 1 along each leading axis, at most 1024 in Y, X.""" + *leading, rows, cols = shape + return (*([1] * len(leading)), min(rows, CHUNK_SIDE), min(cols, CHUNK_SIDE)) + + def _lay_out(target: Path, layout: CopyLayout, dtype: np.dtype, description: str | None) -> Path: """Write the store's metadata and return the folder of the array's chunks.""" target.mkdir(parents=True) @@ -148,14 +168,13 @@ def _lay_out(target: Path, layout: CopyLayout, dtype: np.dtype, description: str array.mkdir() _json(target / ".zgroup", {"zarr_format": 2}) _json(target / ".zattrs", _metadata(layout, dtype, description)) - rows, cols = layout.plane_shape stored = dtype.newbyteorder("<") if dtype.itemsize > 1 else dtype _json( array / ".zarray", { "zarr_format": 2, "shape": list(layout.shape), - "chunks": [*([1] * (len(layout.shape) - 2)), rows, cols], + "chunks": list(chunk_shape(layout.shape)), "dtype": stored.str, "compressor": None, "filters": None, @@ -167,11 +186,68 @@ def _lay_out(target: Path, layout: CopyLayout, dtype: np.dtype, description: str return array -def _chunk_path(array: Path, position: tuple[int, ...]) -> Path: - """Return the file of the plane at ``position`` (its leading indices), making its folder.""" - path = array.joinpath(*(str(i) for i in position), "0", "0") - path.parent.mkdir(parents=True, exist_ok=True) - return path +class _PlaneChunks: + """The chunk files of one plane, written in place block by block (never the whole plane). + + Each chunk file is created at its full size (an edge chunk too, as Zarr version 2 stores + it, its outside zero, the ``fill_value``) the first time a block reaches it; each block's + part of it is written at its place. Files of the chunk rows a block no longer reaches are + closed, so a plane read in bands holds about two rows of chunk files open at once. + """ + + def __init__( + self, array: Path, position: tuple[int, ...], chunks: tuple[int, int], dtype: np.dtype + ) -> None: + self.folder = array.joinpath(*(str(i) for i in position)) + self.chunks, self.itemsize = chunks, dtype.itemsize + self.open: dict[tuple[int, int], BinaryIO] = {} + self.made: set[tuple[int, int]] = set() + + def _file(self, key: tuple[int, int]) -> BinaryIO: + """Return the open file of the chunk at ``key`` (its grid row and column).""" + stream = self.open.get(key) + if stream is not None: + return stream + path = self.folder / str(key[0]) / str(key[1]) + if key in self.made: + stream = open(path, "r+b") + else: + path.parent.mkdir(parents=True, exist_ok=True) + stream = open(path, "w+b") + stream.truncate(self.chunks[0] * self.chunks[1] * self.itemsize) + self.made.add(key) + self.open[key] = stream + return stream + + def _drop(self, below: int) -> None: + """Close the files of the chunk rows above grid row ``below``.""" + for key in [key for key in self.open if key[0] < below]: + self.open.pop(key).close() + + def write(self, y: int, x: int, pixels: np.ndarray) -> None: + """Write the stored values ``pixels`` (little-endian) at row ``y`` and column ``x``.""" + ch, cw = self.chunks + height, width = pixels.shape + self._drop(y // ch) + for gy in range(y // ch, -(-(y + height) // ch)): + a, b = max(y, gy * ch), min(y + height, (gy + 1) * ch) + for gx in range(x // cw, -(-(x + width) // cw)): + c, d = max(x, gx * cw), min(x + width, (gx + 1) * cw) + part = pixels[a - y : b - y, c - x : d - x] + stream = self._file((gy, gx)) + start = ((a - gy * ch) * cw + (c - gx * cw)) * self.itemsize + if d - c == cw: # whole chunk rows: one contiguous run of the file + stream.seek(start) + stream.write(memoryview(np.ascontiguousarray(part)).cast("B")) + continue + for r in range(b - a): + stream.seek(start + r * cw * self.itemsize) + stream.write(memoryview(np.ascontiguousarray(part[r])).cast("B")) + + def close(self) -> None: + """Close every chunk file still open.""" + while self.open: + self.open.popitem()[1].close() def _little(pixels: np.ndarray, dtype: np.dtype) -> np.ndarray: @@ -219,18 +295,16 @@ def write_named_zarr( """ dtype = np.dtype(dtype) array = _lay_out(Path(target), layout, dtype, layout.description) - rows, cols = layout.plane_shape + chunks = chunk_shape(layout.shape)[-2:] roles = [role.lower() for role in layout.axes[:-2]] - row_nbytes = cols * dtype.itemsize for plane in iter_planes(source, mapping, memory_limit=memory_limit): position = tuple(int(plane.coordinates[role]) for role in roles) - with open(_chunk_path(array, position), "wb") as stream: - stream.truncate(rows * row_nbytes) + files = _PlaneChunks(array, position, chunks, dtype) + try: for block in plane.blocks(): - pixels = _little(block.pixels, dtype) - for r in range(pixels.shape[0]): - stream.seek((block.y + r) * row_nbytes + block.x * dtype.itemsize) - stream.write(memoryview(pixels[r]).cast("B")) + files.write(block.y, block.x, _little(block.pixels, dtype)) + finally: + files.close() def write_projected_zarr( @@ -256,6 +330,7 @@ def write_projected_zarr( start, stop = details.z_range out = np.dtype(details.output_dtype) array = _lay_out(Path(target), layout, out, projection_description(details)) + chunks = chunk_shape(layout.shape)[-2:] roles = [role.lower() for role in layout.axes[:-2]] has_z = mapping.index_of("Z") is not None for position in np.ndindex(*layout.shape[:-2]): @@ -275,12 +350,16 @@ def write_projected_zarr( if plane.pixels is None: raise CopyWriteError(f"a plane of {source} does not fit the memory limit") running.add(plane.pixels) - pixels = _little(running.result(), out) - _chunk_path(array, tuple(int(i) for i in position)).write_bytes(pixels.tobytes()) + files = _PlaneChunks(array, tuple(int(i) for i in position), chunks, out) + try: + files.write(0, 0, _little(running.result(), out)) + finally: + files.close() __all__ = [ "BITS_NOT_WRITTEN", + "CHUNK_SIDE", "NGFF_VERSION", "OMERO_COLOUR", "OME_TIFF", @@ -288,6 +367,7 @@ def write_projected_zarr( "STORES", "ZARR_COPY_SUFFIX", "as_zarr_copy", + "chunk_shape", "write_named_zarr", "write_projected_zarr", "zarr_copy_name", diff --git a/src/morphobricks_preprocessing/run/steps.py b/src/morphobricks_preprocessing/run/steps.py index e5667a47..0978a5d3 100644 --- a/src/morphobricks_preprocessing/run/steps.py +++ b/src/morphobricks_preprocessing/run/steps.py @@ -28,6 +28,7 @@ from ..planes import check_planes from ..source_content import with_content from ..validation import ValidationIssue, error, has_errors, plural +from ..window_chunks import check_window_chunks from .entries import Comparison, compare_with_previous, file_entries from .modes import FULL from .phases import CONTENTS @@ -142,6 +143,8 @@ def header_checks( histogram_settings=inputs.histogram_settings, ) ) + # Chunks too large for a later brick's windows are named before the run (v0.10.1). + issues.extend(check_window_chunks(root, review, memory_limit=memory_limit)) return Checked(review, type_review, design, issues, bins) diff --git a/src/morphobricks_preprocessing/window_chunks.py b/src/morphobricks_preprocessing/window_chunks.py new file mode 100644 index 00000000..0d77c309 --- /dev/null +++ b/src/morphobricks_preprocessing/window_chunks.py @@ -0,0 +1,108 @@ +"""Name, before a run, the OME-Zarr images whose chunks are too large for windowed reads (v0.10.1). + +A later brick reads a large image in windows through ``RunInputs.window_reader`` +(:mod:`.window_reader`), which decodes every OME-Zarr chunk a window touches whole and keeps +the chunks it decoded in a cache. A store in one chunk per plane (as ``convert --store +ome-zarr`` wrote before v0.10.1) is read whole for every window: preprocessing itself reads it +fine (its planes in blocks of rows), so nothing failed before the later brick's first window. + +:func:`check_window_chunks` works out from the headers the least a window reader needs for any +window of each OME-Zarr image (:func:`.windows.smallest_window_memory`: a window of one pixel, +read through a cache that holds one chunk, the least that keeps a chunk for the next window) +and warns, ``chunks_too_large_for_windows``, when it is over the memory limit. The reader +refuses the same store when it is opened with a cache that leaves no room for it +(:class:`.window_reader.WindowReader`), with the same advice (:data:`.windows.CHUNK_FIX`). +TIFF images are not checked here: their strips and tiles have their own refusals +(``plane_over_memory_limit``, issue #356). +""" + +from __future__ import annotations + +import logging +import os +from collections.abc import Mapping +from pathlib import Path + +from .axes import AxisMapping, AxisReview +from .plane_errors import PlaneReadError +from .planes import DEFAULT_MEMORY_LIMIT, format_bytes +from .validation import ValidationIssue, plural, warning +from .windows import CHUNK_FIX, _source, smallest_window_memory +from .zarr_input import is_zarr_store + +logger = logging.getLogger(__name__) + +CODE = "chunks_too_large_for_windows" + + +def window_chunk_need( + path: str | os.PathLike, mapping: AxisMapping, memory_limit: int = DEFAULT_MEMORY_LIMIT +) -> int | None: + """Return the least working memory of a window read of an OME-Zarr image, from its header. + + A window of one pixel through a window reader whose cache holds one chunk; None for a + TIFF image. + + Raises + ------ + PlaneReadError + If the image cannot be read under ``mapping``. + """ + if not is_zarr_store(path): + return None + with _source(path, mapping, memory_limit) as source: + return smallest_window_memory(source, source.layout.blocking.piece_nbytes) + + +def check_window_chunks( + experiment_root: str | os.PathLike, + review: AxisReview | Mapping[str, AxisMapping], + *, + memory_limit: int = DEFAULT_MEMORY_LIMIT, +) -> list[ValidationIssue]: + """Warn about OME-Zarr images that no window reader can read within ``memory_limit``. + + Parameters + ---------- + experiment_root + The experiment folder. + review + The axis review, or its per-file mappings keyed by relative path. + memory_limit + The working-memory limit of one read, in bytes. + + Returns + ------- + list of ValidationIssue + One warning, ``chunks_too_large_for_windows``, naming the images, or nothing. An image + that cannot be read under its mapping is left to :func:`.planes.check_planes`. + """ + mappings = review.file_mappings if isinstance(review, AxisReview) else review + root = Path(experiment_root) + found: list[tuple[str, int]] = [] + for rel in sorted(mappings): + try: + need = window_chunk_need(root / rel, mappings[rel], memory_limit) + except PlaneReadError: + logger.debug("Cannot plan windows of %s", rel, exc_info=True) + continue + if need is not None and need > memory_limit: + found.append((rel, need)) + if not found: + return [] + largest = max(need for _, need in found) + return [ + warning( + CODE, + f"{plural(len(found), 'OME-Zarr image')} cannot be read in windows within the memory " + f"limit of {format_bytes(memory_limit)}: the chunks are so large that even a window " + f"of one pixel needs up to {format_bytes(largest)} (a chunk is decoded whole). " + "Preprocessing reads them, but a later brick that reads windows (a patch-window " + "route) will refuse them.", + [rel for rel, _ in found], + CHUNK_FIX, + ) + ] + + +__all__ = ["CODE", "check_window_chunks", "window_chunk_need"] diff --git a/src/morphobricks_preprocessing/window_reader.py b/src/morphobricks_preprocessing/window_reader.py index 84328323..cc782646 100644 --- a/src/morphobricks_preprocessing/window_reader.py +++ b/src/morphobricks_preprocessing/window_reader.py @@ -57,8 +57,10 @@ _Source, _source, check_level, + chunk_note, plane_position, ) +from .zarr_input import is_zarr_store @dataclass(frozen=True) @@ -162,7 +164,10 @@ class WindowReader: ValueError If ``cache_bytes`` is not a whole number above 0. WindowMemoryError - If ``cache_bytes`` leaves no room under ``memory_limit``. + If ``cache_bytes`` leaves no room under ``memory_limit``, or for an OME-Zarr image + whose chunks are too large for even a window of one pixel to be read within + ``memory_limit`` with this cache (:func:`.windows.chunk_note`: a store written in one + chunk per plane; the message names the chunks and what to do). WindowSourceChangedError If the image is missing, or its fingerprint is not ``fingerprint``. """ @@ -188,6 +193,8 @@ def __init__( self.fingerprint = self._now() if fingerprint is None else fingerprint self._check() self._identity = os.path.realpath(self.path) + if is_zarr_store(self.path): + self._check_chunks() def window_plan( self, @@ -300,6 +307,25 @@ def __exit__(self, *exc_info: object) -> None: """Close the reader (:meth:`close`).""" self.close() + def _check_chunks(self) -> None: + """Refuse an OME-Zarr image no window of which fits the limit with this cache. + + From the header: a chunk is decoded whole for any window, so a store in chunks too + large (one chunk per plane of a slide) is refused when the reader is opened, naming its + chunks and what to do, rather than on its first window. + """ + with _source(self.path, self.mapping, self.memory_limit) as source: + note = chunk_note( + source, self.path, self.memory_limit, cache_bytes=self.cache.max_bytes + ) + if note: + self.close() + raise WindowMemoryError( + f"No window of {self.path.name} can be read within the memory limit of " + f"{format_bytes(self.memory_limit)} with a window cache of " + f"{format_bytes(self.cache.max_bytes)}." + note + ) + def _check_open(self) -> None: """Refuse a window asked after :meth:`close`.""" if self._closed: @@ -325,7 +351,10 @@ def _plan( plan = _plan(source, bounds, channels, self.memory_limit, position) plan = _with_cache(plan, self.cache.max_bytes) if plan.memory_estimate > self.memory_limit: - raise WindowMemoryError(_memory_text(plan, self.path) + _CACHE_NOTE) + note = chunk_note( + source, self.path, self.memory_limit, cache_bytes=self.cache.max_bytes + ) + raise WindowMemoryError(_memory_text(plan, self.path) + _CACHE_NOTE + note) return plan def _cached(self, key: Hashable, decode: Callable[[], np.ndarray | None]) -> np.ndarray | None: diff --git a/src/morphobricks_preprocessing/windows.py b/src/morphobricks_preprocessing/windows.py index 2909473f..de01af4d 100644 --- a/src/morphobricks_preprocessing/windows.py +++ b/src/morphobricks_preprocessing/windows.py @@ -316,7 +316,9 @@ def _read_source( position = _position(source.layout, mapping, {"Z": z, "T": t}) plan = _plan(source, bounds, channels, memory_limit, position) if plan.memory_estimate > memory_limit: - raise WindowMemoryError(_memory_text(plan, path)) + raise WindowMemoryError( + _memory_text(plan, path) + chunk_note(source, path, memory_limit, cache_bytes=0) + ) rows_are_y = source.layout.blocking.rows_are_y y0, y1, x0, x1 = plan.bounds box = (y0, y1, x0, x1) if rows_are_y else (x0, x1, y0, y1) @@ -521,3 +523,48 @@ def _memory_text(plan: WindowPlan, path: str | os.PathLike) -> str: f"{format_bytes(plan.memory_limit)}. Ask for a smaller window or fewer channels, or " "raise the memory limit if this computer has enough memory." ) + + +CHUNK_FIX = ( + "If it is an OME-Zarr copy written by 'convert --store ome-zarr' or the notebook before " + "v0.10.1 (one chunk per plane), convert the original images again into a new folder: " + "copies are now written in chunks of 1024 x 1024 pixels. Otherwise save the image again " + "with chunks of at most 1024 x 1024 pixels along Y and X (one plane along the other axes)." +) +"""What to do about an OME-Zarr image whose chunks are too large for windowed reads.""" + + +def smallest_window_memory(source: _Source, cache_bytes: int = 0) -> int: + """Return the working memory of the smallest window read of an open image, from its header. + + A window of one pixel of one channel, read without a cache (``cache_bytes`` 0) or through a + reader whose cache holds ``cache_bytes`` (counted in the figure, as a reader's plan counts + it). An OME-Zarr chunk is decoded whole however small the window, so for a store in one + chunk per plane this is several times the plane: no window of it can be read in less. + """ + plan = _plan(replace(source, cached=cache_bytes > 0), (0, 1, 0, 1), (0,), 0) + return plan.memory_estimate + cache_bytes + + +def chunk_note( + source: _Source, path: str | os.PathLike, memory_limit: int, *, cache_bytes: int +) -> str: + """Return the sentences naming chunks too large for any window within the limit, or "". + + Only for OME-Zarr images (TIFF pieces are bounded by their own refusals, issue #356): + when even a window of one pixel (:func:`smallest_window_memory`, with ``cache_bytes``) is + over ``memory_limit``, no smaller window helps, and the chunks are what to change. + """ + blocking = source.layout.blocking + if blocking.kind != "zarr": + return "" + need = smallest_window_memory(source, cache_bytes) + if need <= memory_limit: + return "" + rows, cols = blocking.unit + return ( + f" {Path(path).name} is stored in chunks of {rows} x {cols} pixels " + f"({format_bytes(blocking.piece_nbytes)} each), and a chunk is decoded whole for any " + f"window it holds: even a window of one pixel needs about {format_bytes(need)}. " + + CHUNK_FIX + ) diff --git a/tests/test_ome_zarr_chunks.py b/tests/test_ome_zarr_chunks.py new file mode 100644 index 00000000..c0d2d080 --- /dev/null +++ b/tests/test_ome_zarr_chunks.py @@ -0,0 +1,170 @@ +"""OME-Zarr copies in spatial chunks, readable in windows (v0.10.1). + +``convert --store ome-zarr`` wrote each plane as one chunk, so a later brick's windowed route +(``RunInputs.window_reader``) decoded the whole plane for every window and refused the first +patch of a slide (``WindowMemoryError``) after ``check`` had passed. Copies are now written in +chunks of one plane by at most 1024 x 1024 pixels, block by block; ``check`` warns about a +store whose chunks no window reader can serve (``chunks_too_large_for_windows``), and the +reader refuses it when opened, with the same advice. The TIFF slides are written lazily, tile +by tile, and the large single-chunk stores hold metadata only. +""" + +from __future__ import annotations + +import json +import tracemalloc + +import numpy as np +import pytest +import tifffile + +pytest.importorskip("zarr") + +from morphobricks_preprocessing.axes import AxisMapping, prefill_mapping # noqa: E402 +from morphobricks_preprocessing.cli import main # noqa: E402 +from morphobricks_preprocessing.conversion import convert_experiment # noqa: E402 +from morphobricks_preprocessing.ome_zarr_copy import CHUNK_SIDE, chunk_shape # noqa: E402 +from morphobricks_preprocessing.window_chunks import ( # noqa: E402 + CODE, + check_window_chunks, + window_chunk_need, +) +from morphobricks_preprocessing.window_reader import WindowReader, cache_plan # noqa: E402 +from morphobricks_preprocessing.windows import WindowMemoryError, read_window # noqa: E402 +from zarr_tree import Unwritten, write_ngff # noqa: E402 + +C, Y, X, TILE = 2, 3000, 2600, 256 +PLANE = Y * X * 2 # one channel, uint16 +REL = "ctrl/rep1/slide.tif" +COPY = "ctrl/rep1/slide.ome.zarr" +MAPPING = AxisMapping("CYX", ("C", "Y", "X")) +MIB = 2**20 + + +def pixels(c, y0, y1, x0, x1): + """Return the slide's values in a box: a pattern, so every pixel's place is checked.""" + y, x = np.ogrid[y0:y1, x0:x1] + return ((c * 7919 + y * 31 + x * 17) % 65521).astype(np.uint16) + + +def write_slide(path): + """Write the slide tile by tile (never whole in memory), as a scanner's tiled TIFF.""" + + def tiles(): + for c in range(C): + for y in range(0, Y, TILE): + for x in range(0, X, TILE): + tile = np.zeros((TILE, TILE), np.uint16) # edge tiles are padded + part = pixels(c, y, min(y + TILE, Y), x, min(x + TILE, X)) + tile[: part.shape[0], : part.shape[1]] = part + yield tile + + path.parent.mkdir(parents=True, exist_ok=True) + tifffile.imwrite( + path, + tiles(), + shape=(C, Y, X), + dtype=np.uint16, + tile=(TILE, TILE), + photometric="minisblack", + metadata={"axes": "CYX"}, + ) + + +@pytest.fixture(scope="module") +def converted(tmp_path_factory): + tmp = tmp_path_factory.mktemp("slide") + root, dest = tmp / "exp", tmp / "copies" + write_slide(root / REL) + tracemalloc.start() + try: + result = convert_experiment( + root, prefill_mapping("CYX"), dest, store="ome-zarr", memory_limit=8 * MIB + ) + peak = tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + assert result.written and list(result.converted) == [COPY] + assert [i.code for i in result.issues] == ["planes_read_in_blocks"] + return dest, peak + + +def test_the_copy_is_written_in_1024_px_chunks_one_plane_deep(converted): + dest, _ = converted + store = dest / COPY + array = json.loads((store / "0/.zarray").read_text(encoding="utf-8")) + assert array["shape"] == [C, Y, X] + assert array["chunks"] == [1, CHUNK_SIDE, CHUNK_SIDE] == list(chunk_shape((C, Y, X))) + # 3 x 3 chunk files per channel, each full size (an edge chunk too, as Zarr 2 stores it) + found = (store / "0").rglob("[0-9]") + files = sorted(p.relative_to(store / "0").as_posix() for p in found if p.is_file()) + assert files == [f"{c}/{r}/{k}" for c in range(C) for r in range(3) for k in range(3)] + assert {(store / "0" / f).stat().st_size for f in files} == {CHUNK_SIDE * CHUNK_SIDE * 2} + + +def test_the_copy_holds_every_pixel_and_was_never_held_whole(converted): + import zarr + + dest, peak = converted + data = zarr.open(str(dest / COPY / "0"), mode="r") + for c in range(C): + assert np.array_equal(data[c], pixels(c, 0, Y, 0, X)) + assert peak < PLANE / 2 # written block by block: never one plane, let alone the image + + +def test_a_small_plane_is_one_chunk_no_larger_than_itself(): + assert chunk_shape((3, 4, 16, 20)) == (1, 1, 16, 20) + assert chunk_shape((5000, 700)) == (1024, 700) + + +def test_a_window_of_the_copy_is_read_within_the_memory_limit(converted): + dest, _ = converted + path, limit = dest / COPY, 64 * MIB + assert window_chunk_need(path, MAPPING, limit) < limit + assert check_window_chunks(dest, {COPY: MAPPING}, memory_limit=limit) == [] + plan = cache_plan(path, MAPPING, window=(512, 512), margin=(32, 32), channels=[0, 1]) + with WindowReader(path, MAPPING, cache_bytes=plan.cache_bytes, memory_limit=limit) as reader: + bounds = (900, 1700, 1000, 1800) # across four chunks + window = reader.read_window(bounds=bounds, channels=[1, 0]) + assert reader.window_plan(bounds=bounds, channels=[1, 0]).memory_estimate <= limit + expected = np.stack([pixels(c, 900, 1700, 1000, 1800) for c in (1, 0)]) + assert np.array_equal(window, expected) + + +def test_the_same_image_in_one_chunk_per_plane_is_named_and_refused(tmp_path): + # The copy as v0.10.1 wrote it before the fix: the same pixels, one chunk per plane. + data = np.stack([pixels(c, 0, Y, 0, X) for c in range(C)]) + root, rel, limit = tmp_path / "exp", "ctrl/rep1/slide.ome.zarr", 32 * MIB + path = write_ngff(root / rel, data, axes="cyx") + assert window_chunk_need(path, MAPPING, limit) > 4 * PLANE + (issue,) = check_window_chunks(root, {rel: MAPPING}, memory_limit=limit) + assert issue.code == CODE and not issue.is_error and issue.paths == (rel,) + assert "even a window of one pixel" in issue.message + assert "convert the original images again into a new folder" in issue.action + assert "1024 x 1024" in issue.action + with pytest.raises(WindowMemoryError) as opened: + WindowReader(path, MAPPING, cache_bytes=MIB, memory_limit=limit) + text = str(opened.value) + assert f"chunks of {Y} x {X} pixels" in text and "convert the original images" in text + with pytest.raises(WindowMemoryError) as read: # without a reader, the same advice + read_window(path, MAPPING, bounds=(0, 1, 0, 1), channels=[0], memory_limit=limit) + assert f"chunks of {Y} x {X} pixels" in str(read.value) + + +def test_check_warns_about_a_slide_stored_in_one_chunk_per_plane(tmp_path, capsys): + # A 12000 x 12000 slide (metadata only): preprocessing reads it in blocks, so the run's + # check passes, but a 275 MiB chunk is decoded whole for every window: no reader serves it. + root, out = tmp_path / "exp", tmp_path / "out" + for condition in ("a", "b"): + write_ngff(root / condition / "slide.zarr", Unwritten((2, 12000, 12000), "uint16"), "cyx") + describe = ["describe", str(root), "--output", str(out), "--channels", "DNA,ACTIN"] + describe += ["--image-type", "channels", "--accept-ids", "--comparable"] + assert main([*describe, "--confirmed-on", "2026-12-04", "--publish"]) == 0 + capsys.readouterr() + assert main(["check", str(root), "--output", str(out)]) == 0 # a warning, not an error + text = capsys.readouterr().out + assert "2 OME-Zarr images cannot be read in windows within the memory limit of 1.0 GiB" in text + assert " - a/slide.zarr\n - b/slide.zarr" in text + assert "convert the original images again" in text + report = json.loads((out / "discovery_report.json").read_text(encoding="utf-8")) + assert CODE in json.dumps(report) From 55470cbaed4f5e611498bf90a5487d3ffe662ec7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:15:19 +0000 Subject: [PATCH 16/25] CLI wording: help, success, next-step and refusal messages; guide and README Every subcommand gets a description and examples; success lines say what was saved and print the next commands with the user's options (quoted); refusals say what, why and what to do. Codes, severities and paths are unchanged. README and user guide follow the complete workflow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp99saj5j4QZfMeAZQUm --- CHANGELOG.md | 15 + README.md | 128 +++-- docs/user_guide.md | 484 ++++++++++++------ pyproject.toml | 2 + src/morphobricks_preprocessing/cli.py | 134 ++++- .../cli_calibrate.py | 33 +- src/morphobricks_preprocessing/cli_convert.py | 164 ++++-- .../cli_declare_masks.py | 84 ++- .../cli_describe.py | 157 ++---- .../cli_describe_options.py | 127 +++++ src/morphobricks_preprocessing/cli_masks.py | 35 +- src/morphobricks_preprocessing/cli_run.py | 193 ++----- .../cli_run_options.py | 149 ++++++ .../cli_tissue_mask.py | 62 ++- .../conversion_issues.py | 53 +- .../describe_ids.py | 89 +++- .../describe_questions.py | 18 +- .../description_run_text.py | 127 ++++- .../fast_answers.py | 27 +- .../he_tissue_mask.py | 30 +- .../ignored_masks.py | 25 +- .../mask_declare.py | 18 +- src/morphobricks_preprocessing/mask_text.py | 30 +- .../physical_check.py | 4 +- .../projection_issues.py | 22 +- src/morphobricks_preprocessing/report.py | 5 +- .../required_description.py | 35 +- .../run/preflight.py | 12 +- .../run_inputs_text.py | 30 +- .../run_inputs_tissue.py | 30 +- .../tissue_masks_folder.py | 9 +- tests/test_axis_check.py | 2 +- tests/test_brick_checks.py | 12 + tests/test_calibration.py | 2 +- tests/test_cli.py | 15 +- tests/test_cli_describe.py | 14 +- tests/test_cli_tissue_mask.py | 15 +- tests/test_cli_usability.py | 65 ++- tests/test_convert_work_folder.py | 2 +- tests/test_declare_masks.py | 2 +- tests/test_he_tissue_mask.py | 6 +- tests/test_ignored_masks.py | 4 +- tests/test_mask_step.py | 2 +- tests/test_mask_ties.py | 7 +- tests/test_notebook_mask_step.py | 5 +- tests/test_notebook_tag_by_repeat_drafts.py | 5 +- tests/test_notebook_tissue_mask.py | 2 +- tests/test_report.py | 2 +- tests/test_run_description.py | 4 +- tests/test_stopped_run_text.py | 4 +- 50 files changed, 1741 insertions(+), 760 deletions(-) create mode 100644 src/morphobricks_preprocessing/cli_describe_options.py create mode 100644 src/morphobricks_preprocessing/cli_run_options.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 818440f0..ee6f4ce6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,21 @@ are unchanged; one optional output-folder file (`ignored_masks.toml`) and one op key (`ignored_masks`) are new. A v0.10.0 reader of a run that uses them ignores the key and so refuses the skipped label images as unrecorded: refused, never silently wrong. +### Changed + +- **Command-line wording (independent review of v0.10.1, owner answers of 4 December 2026).** + Every subcommand has a description and examples in `--help`; option help is rewritten in plain + language. Success lines say what was saved and where, then print the next commands with the + user's own options, shell-quoted (`describe --publish`, `check`, `run`, `convert`, + `calibrate`, `declare-masks`, `tissue-mask`, `masks`). Refusals say what was refused, why and + what to do, with commands on their own lines (`A_DESCRIPTION_REQUIRED`, ID reasons in + `describe --id`, undeclared mask types with each representation's meaning, an unreadable + `ignored_masks.toml`, projection, conversion and tissue-mask refusals); the `zarr` install line + names the installed release. Issue codes, severities and paths are unchanged. README and user + guide follow (complete workflow, both masks-folder layouts, `plane_histograms.parquet`). + `cli_run_options` and `cli_describe_options` hold option definitions moved out of `cli_run` + and `cli_describe` (line limit); `parse_size` and `add_describe_parser` are re-exported. + ### Fixed - **OME-Zarr copies are written in spatial chunks, so a later brick can read them in windows.** diff --git a/README.md b/README.md index dcb2d0bd..40240334 100644 --- a/README.md +++ b/README.md @@ -2,14 +2,20 @@ [![CI](https://github.com/CellMigrationLab/morphobricks-preprocessing/actions/workflows/ci.yml/badge.svg)](https://github.com/CellMigrationLab/morphobricks-preprocessing/actions/workflows/ci.yml) -The preprocessing brick of MorphoBricks. It reads an experiment folder of -microscopy TIFFs, computes one intensity histogram per channel of every plane, and writes -them, with each plane's experimental labels, to `plane_histograms.csv`: one row per plane -(an image at one time point), each channel in its own columns. MorphoBricks v1 analyses 2-D -planes: a Z-stack (more than one depth slice) is refused (`z_stack_not_supported`); make -recorded 2-D projected copies first with `convert --project max|mean|sum`, and use the copies. Later bricks -(for example patch extraction) use that table to calculate normalization -parameters for any group of images without rereading the pixels. +MorphoBricks preprocessing is the first step before analysing a microscopy experiment. It +records experimental conditions, repeats, channels, pixel sizes and masks, checks the images, +and prepares the files used by downstream MorphoBricks analysis tools. + +Its main output is `plane_histograms.parquet`: the intensity histograms of every image plane, +with its experimental labels and channel IDs. The table contains one row per plane and stores +each channel's histogram as lists of bin indices and counts. Later MorphoBricks tools read this +file to calculate normalisation parameters without rereading the image pixels. From v0.10.0, +this file replaces `plane_histograms.csv`. To update an older preprocessing run, run +preprocessing again. + +MorphoBricks v1 analyses 2-D planes: a Z-stack (more than one depth slice) is refused +(`z_stack_not_supported`); make recorded 2-D projected copies first with +`convert --project max|mean|sum`, and use the copies. The brick never modifies source images and never applies a normalization itself. The histograms, the table format, pooling and the normalization methods come from the @@ -50,16 +56,16 @@ Pre-alpha; the current release is v0.10.0 (what is planned next is in - A step-by-step notebook ([notebooks/MorphoBricks_Preprocessing.ipynb](notebooks/MorphoBricks_Preprocessing.ipynb)) and a command line (`morphobricks-preprocessing check` / `run` / `masks` / `calibrate` / `describe` / `convert`) -- **Every run is described** (v0.5.1): the output folder must hold a published experiment - description, `morphobricks.toml`, written by the notebook's describe steps (*Check and - save*). A run without one is refused with `A_DESCRIPTION_REQUIRED` on every route. +- **Every run is described:** publish the experiment description using `describe --publish` + or the notebook. Every preprocessing run requires a published description + (`morphobricks.toml`); a run without one is refused with `A_DESCRIPTION_REQUIRED`. Every feature, message code and output file is described in the [user guide](docs/user_guide.md). From the normalization brick (`morphobricks_normalization`, a required dependency, pinned -to its release v0.8.0): per-plane histograms with the robust range and the range check -(`histogram`, `ranges`), the histogram table (`csv_io`, schema version 5: channels by canonical -ID, so acquisitions may have different channels), pooled group statistics +to its release v0.10.0): per-plane histograms with the robust range and the range check +(`histogram`, `ranges`), the histogram table (`parquet_io`, `plane_histograms.parquet` schema +version 6: channels by canonical ID, so acquisitions may have different channels), pooled group statistics (`pooling`) and normalization parameters (`normalization`); import them from `morphobricks_normalization` (the deprecated paths through `morphobricks_preprocessing` were removed in v0.4.0). @@ -81,8 +87,17 @@ contract version 3 and an objects use with `RunInputs.read_objects`. See the ## Installation +You need Python 3.11 or newer, Git and an internet connection. We recommend installing into a +new Python virtual environment. JupyterLab is not required for command-line use. + ```bash -pip install "git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.0" +python -m pip install "morphobricks-preprocessing @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" +``` + +For OME-Zarr images or the H&E tissue mask, install the extras too: + +```bash +python -m pip install "morphobricks-preprocessing[zarr,he-mask] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" ``` For development, from a clone: @@ -92,7 +107,7 @@ pip install -e ".[dev]" ``` The optional `notebook` extra installs the widget dependencies for the notebook -(`pip install "morphobricks-preprocessing[notebook] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.0"`). +(`python -m pip install "morphobricks-preprocessing[notebook] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1"`). The notebook's first code cell (**1. Install**) can set this up automatically: it uses a nearby checkout or an installed package only when it is the pinned `RELEASE_REF` commit (never by version alone), and installs missing requirements into the active kernel. A standalone @@ -143,12 +158,7 @@ LabConstrictor's JupyterLab/LabConstrictor before their release candidate is tagged; see [docs/colab-release-check.md](docs/colab-release-check.md). -From a terminal: - -```bash -morphobricks-preprocessing check /data/exp1 -morphobricks-preprocessing run /data/exp1 --axes ZCYX --image-type fluorescence -``` +From a terminal, see [Command line](#command-line) below. ## Running an experiment @@ -185,30 +195,57 @@ the [user guide](docs/user_guide.md) §9, "Settings". ## Command line +A complete workflow. This example assumes that every image contains collagen and fibronectin +in that order, that the image axes are named correctly, and that your biological repeats were +prepared and acquired comparably. Replace the channel names and date with your own. Review the +proposed IDs before accepting them. If these assumptions do not fit your experiment, use the +relevant instructions in the [user guide](docs/user_guide.md) §5. + +```bash +morphobricks-preprocessing describe my_experiment # preview: proposed IDs, open questions +morphobricks-preprocessing describe my_experiment --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +morphobricks-preprocessing check my_experiment +morphobricks-preprocessing run my_experiment +``` + +Your experiment is now described, checked and processed. The default output folder is +`my_experiment_MorphoBricks_Preprocessing`. Give this folder to the MorphoBricks tool that will +analyse your images. + +Fast publication from the command line creates a new description for an experiment with a +shared channel layout. Use the notebook to edit an existing description, change repeat pairing +or describe acquisitions with different channel lists or orders. Give `--comparable` only if +the samples of each biological repeat were prepared and acquired comparably; never give it +just to get past the question. + +Other commands: + ```bash -morphobricks-preprocessing describe /data/exp1 # the draft description, what is open -morphobricks-preprocessing check /data/exp1 # report, suggested --axes -morphobricks-preprocessing run /data/exp1 --axes ZCYX -morphobricks-preprocessing run --output /data/exp1_MorphoBricks_Preprocessing # later runs -morphobricks-preprocessing masks --output /data/exp1_MorphoBricks_Preprocessing # mask step -morphobricks-preprocessing calibrate --output /data/exp1_MorphoBricks_Preprocessing -morphobricks-preprocessing convert /data/exp1 --to /data/exp1_named_axes --axes ZXY # axis errors -morphobricks-preprocessing convert-mask --output /data/exp1_MorphoBricks_Preprocessing --mask TumorRegion --to-instances TumorObjects # new mask files -morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preprocessing --to HETissue # H&E tissue region (he-mask extra; provisional rule) +morphobricks-preprocessing run --output my_experiment_MorphoBricks_Preprocessing # later runs +morphobricks-preprocessing declare-masks --output my_experiment_MorphoBricks_Preprocessing \ + --masks my_masks --type Cells=instances # declare masks +morphobricks-preprocessing masks --output my_experiment_MorphoBricks_Preprocessing # check masks +morphobricks-preprocessing calibrate my_experiment --size . XY 0.65 um # pixel sizes +morphobricks-preprocessing convert my_experiment --to my_experiment_max --axes ZCYX --project max # 2-D projections +morphobricks-preprocessing convert-mask --output my_experiment_MorphoBricks_Preprocessing --mask TumorRegion --to-instances TumorObjects # new mask files +morphobricks-preprocessing tissue-mask --output my_experiment_MorphoBricks_Preprocessing --to HETissue # H&E tissue region (he-mask extra; provisional rule) ``` `check`, `run` and `masks` need the experiment description published in the output folder -(the notebook's describe steps); without it they stop with `A_DESCRIPTION_REQUIRED` and write -nothing. `describe` shows the draft and what is still to be answered. `check` writes the -report. `run` and `masks` reuse every input the run in the -output folder recorded. A run that stops writes its report and says so. Every output file -gets the permissions a file you save yourself would (your umask). `convert` saves the -images whose metadata name their axes wrongly or not at all as named-axis OME-TIFF copies -with your roles in a new folder (each plane bit for bit the plane read with those roles; -every other image copied as it is; a conversion record written last), then you run -preprocessing on that folder with the same output folder. The notebook offers the same -conversion in step 2, under the axis check, when it finds such images. Details in the -[user guide](docs/user_guide.md) §5. +(`describe --publish` or the notebook's describe steps); without it they stop with +`A_DESCRIPTION_REQUIRED` and write nothing. `check` inspects the folders, image headers and +supplied masks, and suggests axis roles; it does not measure image pixels or perform every +validation of the published description. `run` validates the description and confirmed axis +roles before processing. `run` and `masks` reuse every input the run in +the output folder recorded. External TIFF masks are stored in a separate masks folder, given +with `--masks`; OME-Zarr label images are discovered automatically. If your analysis uses +masks, run `masks` after preprocessing. After `calibrate`, run preprocessing again. Every +output file gets the permissions a file you save yourself would (your umask). `convert` writes +copies of the images in a new folder (named-axis OME-TIFF, OME-Zarr with `--store ome-zarr`, +or 2-D projections with `--project`); the copies are a new experiment folder, described and +published before `check` and `run`. Use the actual stored axis order of your images: RGB TIFFs store their colour samples +last (`YXC`). Details in the [user guide](docs/user_guide.md) §5. ## Example @@ -232,13 +269,14 @@ record = PlaneRecord( technical_repeat="tech_rep1", histograms=[compute_plane_histogram(plane)], # one per channel position_id="img_01", # required: the XY position within its technical repeat + channels=("DNA",), # the channel ID of each histogram, in order ) -write_plane_histograms([record], "plane_histograms.csv") +write_plane_histograms([record], "plane_histograms.parquet", channel_ids=["DNA"]) # In a later brick: pool one channel of any group and derive normalization parameters -records = read_plane_histograms("plane_histograms.csv") +records = read_plane_histograms("plane_histograms.parquet") for key, members in group_records(records, "condition").items(): - pooled = PooledHistogram(members, channel=0) + pooled = PooledHistogram(members, channel="DNA") params = percentile_range(pooled, low=1, high=99.8) normalized = params.apply(plane, clip=(0, 1)) ``` diff --git a/docs/user_guide.md b/docs/user_guide.md index 46c971e3..0165e4ac 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -3,16 +3,21 @@ The preprocessing brick reads an experiment folder of microscopy images (TIFF or OME-Zarr) and computes one intensity histogram for every 2D plane. The histograms, with each plane's labels, are -saved in `plane_histograms.csv`. Later MorphoBricks bricks (for example patch extraction) -use this table to normalise images per condition, repeat or image without reading the -pixels again. +saved in `plane_histograms.parquet`. Later MorphoBricks tools (for example patch extraction) +use this table to calculate normalisation parameters per condition, repeat or image without +reading the pixels again. + +New to the command line? Start with the [quick start](#quick-start-from-a-terminal) after +the installation section. The brick **never changes your images** and never normalises them itself. It writes only to its own output folder, which is never inside the experiment folder. ## 1. Installation -You need Python 3.11 or newer and JupyterLab (or Google Colab). Download +For the notebook, you need Python 3.11 or newer and JupyterLab (or Google Colab). For the +command line only, see [Installing for the command line](#installing-for-the-command-line) +below. Download [`notebooks/MorphoBricks_Preprocessing.ipynb`](../notebooks/MorphoBricks_Preprocessing.ipynb), open it and run its three code cells in order: @@ -64,12 +69,12 @@ To install everything manually instead, run these commands in the environment us your notebook kernel: ```bash -pip install "morphobricks-preprocessing[notebook] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git" -pip install jupyterlab +python -m pip install "morphobricks-preprocessing[notebook] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" +python -m pip install jupyterlab ``` To read OME-Zarr images, install the `zarr` extra too: -`pip install "morphobricks-preprocessing[notebook,zarr] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git"`. +`python -m pip install "morphobricks-preprocessing[notebook,zarr] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1"`. Start JupyterLab with `jupyter lab` and open the notebook. **Browse…** opens your computer's folder dialog; where no dialog can open (Google Colab, a remote server), it says so and you @@ -128,6 +133,48 @@ Google Drive is wiped when it disconnects (after some idle time, or after severa run. Untick it (CLI `--no-verify-content`) to compare size and time only; the manifest then records `verify_content: false`. An output folder keeps the choice of its earlier run. +### Installing for the command line + +You need Python 3.11 or newer, Git and an internet connection. We recommend installing into a +new Python virtual environment. JupyterLab is not required for command-line use. + +```bash +python -m pip install "morphobricks-preprocessing @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" +``` + +To read OME-Zarr images, or to make the optional H&E tissue mask (`tissue-mask`, §5), install +the extras too: + +```bash +python -m pip install "morphobricks-preprocessing[zarr,he-mask] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" +``` + +The package is installed from GitHub; it is not on a package index. + +## Quick start from a terminal + +This is the shortest route for an experiment whose images all have the same channels in the +same order. §5 explains each step and what to do when your experiment differs. + +```bash +morphobricks-preprocessing describe my_experiment +morphobricks-preprocessing describe my_experiment --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +morphobricks-preprocessing check my_experiment +morphobricks-preprocessing run my_experiment +``` + +1. The first `describe` shows the proposed IDs and the open questions. It writes nothing. +2. The second `describe` publishes the experiment description. Every preprocessing run needs + it. Give `--comparable` only if the samples of each biological repeat were prepared and + acquired comparably. +3. `check` inspects the folders, image headers and masks, and writes a report. +4. `run` computes the histograms and writes the output folder, + `my_experiment_MorphoBricks_Preprocessing`. + +If your analysis uses masks, declare them and run the `masks` command after preprocessing +(§5, "Declaring existing masks or adding new masks"). + ## 2. Organising the experiment folder The folder you select is the **experiment folder**. Below it, up to three levels of folders @@ -221,10 +268,34 @@ masks/ control/bio_rep1/tech_rep1/img_02.tif ``` -- Or keep the masks in the same folders as the experiment, each named after its image - followed by `_` and its kind (`img_01_cells.tif`, `img_01_nuclei.tif`), as many - segmentation tools write them; the kind is the part after the image name. Both ways may be - mixed in one masks folder. +- OME-Zarr label images are discovered automatically. External TIFF masks must be stored in a + separate masks folder. Give that folder with `--masks`, unless an earlier preprocessing run + already recorded it. +- Inside the masks folder, a mask type can be named in one of two ways. Both ways may be mixed + in one masks folder. + + **(a) One subfolder per mask type**, each mask named exactly as its image: + + ``` + my_experiment/ctrl/image_01.tif + my_masks/Cells/ctrl/image_01.tif + ``` + + Declare it with `--type Cells=instances` (§5, `declare-masks`). + + **(b) The mask type as the file-name ending**, after the image name and `_`, in the + experiment's folders. Cellpose names its masks this way: + + ``` + my_experiment/ctrl/image_01.tif + my_masks/ctrl/image_01_cp_masks.tif + ``` + + The mask type is `cp_masks`. Declare it with `--type cp_masks=instances:Cells`: the ending, + then the mask ID you want to use. + + Do not combine the two. A file `my_masks/Cells/ctrl/image_01_cp_masks.tif` matches no + image: the run warns and leaves it out. - A mask is a TIFF label image with the width and height of its image: background 0, each object its own whole number (or a true/false mask). The extension may differ from the image's (`img_01.tiff` for `img_01.ome.tif`). @@ -243,13 +314,16 @@ masks/ starts another's (`a.tif` and `a_b.tif`), a mask named `a_b_cells.tif` could belong to either and is refused: rename the masks or the images. - The label images stored inside an OME-Zarr image (its `labels` group) are used as masks - too, named after the label image. + too, named after the label image, except for mask types listed in `ignored_masks.toml` + (§5, `declare-masks --ignore`). - An image without a mask of one kind is reported; its objects of that kind cannot be measured. -Masks do not change `plane_histograms.csv`. They are checked and recorded for the bricks -that measure objects; the optional `masks` command (§5), or **Describe the masks** in the -notebook's step 3 (§4), also tells how they relate. +Masks do not change `plane_histograms.parquet`. They are checked and recorded for the bricks +that measure objects. If your analysis uses masks, run the `masks` command (§5), or +**Describe the masks** in the notebook's step 3 (§4), after preprocessing. It checks the mask +pixels against their declared representation and reports relationships between mask types. +Skip this step only if the downstream analysis does not use masks. ### Making masks with Cellpose (optional) @@ -454,10 +528,23 @@ run the experiment in the app of cell 3. Then: images must have their dimensions in the same order; the number of slices, time points and the size may differ. OME-Zarr images may store them in another order: they are matched by role, so z = 2, c = 1 means the same slice and channel in every image. -- **Channels:** all images of an experiment must have the same number of channels (an - image without a channel dimension has one). Split images with other channels into a - separate experiment, or exclude them. -- **RGB images:** the three colour samples are treated as channels (C). +- **Channels:** images within one acquisition folder must have a consistent channel layout + (an image without a channel dimension has one channel). Different acquisitions may have + different channel lists or orders when each is described separately in the notebook. The + simple command-line publication workflow requires one shared channel list and order for the + experiment. Later analysis tools may require the selected channel to be present in every + image being analysed. +- **RGB images:** RGB images must have exactly three colour channels containing red, green and + blue in that order, with an integer pixel type. Declare them using `--image-type rgb + --channels R,G,B`. TIFF files whose headers do not identify their interleaved colour samples + as RGB may need `--rgb-header-override`. OME-Zarr colour images must be declared RGB + explicitly. The three colour samples are treated as channels (C). The optional + `tissue-mask` command has narrower requirements: 8-bit RGB, one depth plane and one time + point. +- **Image type names:** the experiment description records separate-channel images as + `channels` and colour images as `rgb`. The `run` command's `--image-type` option uses the + older name `fluorescence` for separate-channel images. In the normal described workflow, use + the published description as the authoritative record of what your channels represent. - **Pyramidal images:** only the full-resolution level is read. - **Not supported yet:** files with several positions or scenes (several image series), and position or tile axes. Export each position as its own file. @@ -850,61 +937,98 @@ On Google Colab, cell 3 asks Colab not to put its output in a frame that scrolls ## 5. Command line -The same checks and computations are available from a terminal: +**Before you start.** Every preprocessing run needs a published experiment description +(`morphobricks.toml` in the output folder). `check`, `run` and `masks` refuse an experiment +without one: they print `A_DESCRIPTION_REQUIRED`, write nothing and exit with status 1. Publish +the description first, with `describe ... --publish` (below) or in the notebook's describe +steps. -```bash -morphobricks-preprocessing check /data/exp1 -``` - -prints what will be analysed, the label tree, the number of images per condition and -biological repeat (with `!` marking unbalanced ones), the problems found and the -suggested axis roles, for example `--axes ZCYX`. Then: +**A complete workflow.** This example assumes that every image contains collagen and +fibronectin in that order, that the image axes are named correctly, and that your biological +repeats were prepared and acquired comparably. Replace the channel names and date with your +own. Review the proposed IDs before accepting them. If these assumptions do not fit your +experiment, use the relevant instructions below. ```bash -morphobricks-preprocessing run /data/exp1 --axes ZCYX +# 1. Preview the draft description: proposed IDs and open questions (writes nothing) +morphobricks-preprocessing describe my_experiment +# 2. Publish the description +morphobricks-preprocessing describe my_experiment --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +# 3. Check the folders, image headers and masks +morphobricks-preprocessing check my_experiment +# 4. Compute the histograms +morphobricks-preprocessing run my_experiment ``` -`--axes` gives one role per dimension of the images, in their order: `X`, `Y`, `Z`, `C`, -`T`, or `-` for a length-1 dimension without a role. It is needed only when some images are +Your experiment is now described, checked and processed. The default output folder is +`my_experiment_MorphoBricks_Preprocessing`. Give this folder to the MorphoBricks tool that will +analyse your images. + +- Fast publication from the command line creates a new description for an experiment with a + shared channel layout. Use the notebook to edit an existing description, change repeat + pairing or describe acquisitions with different channel lists or orders. +- Give `--comparable` only if the samples of each biological repeat were prepared and acquired + comparably. Never give it just to get past the question. +- If `describe` refuses to publish because some image headers do not name their axes or state + their channel count, name the axes with the notebook or with `convert` (below). +- If your analysis uses masks, declare them, run preprocessing with them and run the `masks` + command ("Declaring existing masks or adding new masks", below). +- To state pixel sizes the images do not record, use `calibrate` (below), then run + preprocessing again. + +**What `check` does.** `check` inspects the folders, image headers and supplied masks, and +suggests axis roles. It does not measure image pixels or perform every validation of the +published description. `run` validates the description and confirmed axis roles before +processing. `check` prints what will be analysed, the label tree, the number of images per +condition and biological repeat (with `!` marking unbalanced ones), the problems found and the +suggested axis roles. + +To check the same images and external masks as your intended run, give `check` the same +`--exclude`, `--masks` and `--mask-axes` options. Unlike `run`, `check` does not automatically +reuse all these recorded choices. + +**Axis roles (`--axes`).** `--axes` gives one role per dimension of the images, in their +stored order: `X`, `Y`, `Z`, `C`, `T`, or `-` for a length-1 dimension without a role. For +example, `--axes CYX` is for images stored as channels, then rows, then columns. A Z axis is +allowed only with one slice: multi-slice Z-stacks are refused in this release (make 2-D +projections with `convert --project`, below). `--axes` is needed only when some images are plain stacks, whose metadata do not name their axes: when every image names all its axes, -`run` uses those roles without `--axes` (it prints **Axis roles (as every image names -them)**; design v0.4 §3), and they are still checked as below. A later `run` in the same output folder needs neither the roles nor -the experiment folder again, unless plain stacks were added or changed: +`run` uses those roles without `--axes` (design v0.4 §3), and they are still checked as below. +A later `run` in the same output folder needs neither the roles nor the experiment folder +again, unless plain stacks were added or changed: ```bash -morphobricks-preprocessing run --output /data/exp1_MorphoBricks_Preprocessing +morphobricks-preprocessing run --output my_experiment_MorphoBricks_Preprocessing ``` -uses the experiment folder and everything else the earlier run recorded there. Without an -experiment folder and without an output folder of a v0.4.0 run, `run` stops with -`experiment_not_recorded`, naming what is missing. Giving an experiment folder other than +uses the experiment folder and everything else the earlier run recorded there. If no +experiment folder has been recorded, give the experiment folder explicitly (otherwise `run` +stops with `experiment_not_recorded`). Giving an experiment folder other than the recorded one (for example after moving it) is reported as a change: every row is read again from the new place, and images that do not name their axes (plain stacks) must be confirmed again with `--axes`. Both commands check the axes (§4, step 2): `check` with the suggested roles, which are the headers' own, so only the `axes_not_named` warning of plain stacks can appear there; `run` -with the roles given in `--axes`. They print **Axes checked: every image names its axes in -its metadata, and the roles agree with them** when all is well (and name the plain stacks -whose roles are recorded as confirmed), or the errors naming the images, the likely cause -and the two fixes, and `run` stops (exit status 1). - -`--image-type fluorescence` or `--image-type rgb` gives the image type (§4, step 3). -Without it, `run` uses the type suggested from the image headers and prints it, with why it -was suggested and how to choose the other one; `check` prints the suggestion too. `rgb` -for images that are not three channels of a whole-number pixel type stops the run -(`rgb_not_possible`). - -`check`, `run` and `masks` need the experiment description published in the output folder -(`morphobricks.toml`, v0.5.1): the conditions, which biological repeats pair across conditions -and that they are comparable, the channels and the masks, answered in the notebook's describe -steps and saved with *Check and save*, or published from the command line with `describe ... ---publish` (§5). Without it they print `A_DESCRIPTION_REQUIRED`, naming both routes, write -nothing and exit with status 1. `describe` shows the draft description of the -folders and every question still open. The run writes `experiment_design.csv`, derived from the -description (an output for later bricks; nothing reads it back). `check` and `run` write the -report, `discovery_report.json` and `discovery_report.txt`, to the output folder; `run` writes -it on every run, also one that stops (`status` `stopped` or `written`, with the SHA-256 of the +with the roles given in `--axes`. When all is well they say that every image names its axes +and the roles agree (and name the plain stacks whose roles are recorded as confirmed); +otherwise they print the errors naming the images, the likely cause and the two fixes, and +`run` stops (exit status 1). + +**Image type.** The experiment description records separate-channel images as `channels` and +colour images as `rgb`. The `run` command's `--image-type` option uses the older name +`fluorescence` for separate-channel images. In the normal described workflow, use the +published description as the authoritative record of what your channels represent. Without +`--image-type`, `run` uses the earlier run's type, else the type suggested from the published +description and the image headers, and prints it; `check` prints the suggestion too. `rgb` for images that are not three +channels of a whole-number pixel type stops the run (`rgb_not_possible`). + +**Reports.** `describe` shows the draft description of the folders and every question still +open. The run writes `experiment_design.csv`, derived from the description (an output for +later tools; nothing reads it back). `check` and `run` write the report, +`discovery_report.json` and `discovery_report.txt`, to the output folder; `run` writes it on +every run, also one that stops (`status` `stopped` or `written`, with the SHA-256 of the manifest it describes). A run that stops says so, says that no table or manifest was written, and names what it did write: the report. Only a run refused before it starts (another run holds the lock, or no description is published) writes nothing. @@ -928,20 +1052,39 @@ the same bytes in every file except that time (and the manifest SHA-256 the repo | `--memory-limit SIZE` | Working-memory limit per plane, e.g. `2GiB` or `1.5GiB`: a whole number of bytes above 0 (`1.5` or `0.5B` are refused before anything is read) | | `--workers N\|auto` | How many images are read at once, each in its own thread (default 1: one after another). `auto`: at most the number of CPUs, and with `--max-ram` as many as the largest image's estimated working memory fits. The results are exactly the same with any value; it is not recorded and changes nothing on the next run | | `--max-ram SIZE` | With `--workers auto`: the memory the run may use, e.g. `8GiB` (256 MiB of it kept for the run itself). An image that alone needs more stops the run before any pixel is read (`image_over_max_ram`) | -| `--missing-as-singleton`, `--no-missing-as-singleton` | Confirm that images lacking some dimensions have one plane along them (`check` and `run`; default: the earlier run's answer, else no). `check` then reports what `run` will: an experiment of 2D images and Z-stacks passes `check` once confirmed, and the suggested option says `--axes ZCYX --missing-as-singleton` | +| `--missing-as-singleton`, `--no-missing-as-singleton` | Confirm that images lacking some dimensions have one plane along them (`check` and `run`; default: the earlier run's answer, else no). Confirm that a dimension absent from an image has size 1. This can reconcile missing length-1 dimensions, but does not permit multi-slice Z-stacks. Project Z-stacks to 2-D before preprocessing (`convert --project`) | | `--image-type fluorescence\|rgb` | The image type (default: the earlier run's, else the suggested one, printed) | | `--mode restart\|full` | `restart` (default) reuses the rows of unchanged images; `full` recomputes every row and check. Both keep your confirmations and replace the results only when the run succeeds | | `--verify-content`, `--no-verify-content` | Reuse rows (earlier or staged) only when each image's content SHA-256 is the one recorded with them, not only its size and modification time; every image is read once more. Default: the earlier run's choice, else on; `--no-verify-content` opts out and the manifest records it. Turning it on or off recomputes every row. With `masks`: also compare each mask's content SHA-256 before and after it is read (same default) | -| `--lab-links FILE` | A JSON file of lab-tool links (for example LabChronicle), recorded in `run_manifest.json` only (`lab_links`): exactly the keys `repository_url`, `commit` (the full 40- or 64-character lowercase SHA) and `experiment_path`, as non-empty text, and optionally `repeat_codes`, which maps each lab-tool repeat code to a biological repeat ID of the description (for example `{"R001": "rep1"}`). Any other key, a value of another type, an empty value, spaces around a value, or a key given twice is refused before anything is read (`lab_links_invalid`). A `repository_url` holding a credential (a password, `user:password@`, in any form; a user name before `@` in a URL whose scheme is not `ssh`, `git+ssh` or `ssh+git`, because `https://TOKEN@host/...` carries a token there), a query string or a fragment (`?` or `#`) is refused (`lab_links_invalid`), and the refusal does not repeat the URL: a credential is never written to the manifest. An SSH remote's login name (`git@host:lab/db.git`, `ssh://git@host/...`) is kept. The links change no result: no row, digest, cache or other file. They are not taken over by the next run: give the file to each run it belongs to. Not offered by the notebook | +| `--lab-links FILE` | Record optional lab-tool provenance from a JSON file. See "The lab-links file" below the table for its format. Does not change the image measurements. | | `--confirm-repeat-codes` | Confirm the `repeat_codes` of `--lab-links` for this run. The run prints each pair; without this option a file with repeat codes is refused (`lab_links_repeat_codes_not_confirmed`), also when a code is spelled like the ID: the lab tool's codes and the description's IDs are separate names | | `--no-masks` | Drop the masks folder an earlier run recorded, with the mask axes stated for its masks (those of OME-Zarr label images are kept) | | `--no-exclude` | Clear the exclusions an earlier run recorded, so every image is analysed again (not together with `--exclude`) | | `--remove-stale-lock` | Remove the lock left by a run that was stopped or whose computer restarted (`check`, `run`, `masks` and `calibrate`); give it only when no other run uses the output folder, on any computer (only Linux and macOS can tell whether a process on this computer still runs) | | `--outlier-limit N`, `--saturation-limit FRACTION`, `--min-images N` | Limits of the intensity checks printed after the run (default 3, 0.01 and 5) | -| `--log FILE` | Write technical details to a file (`run`, `masks`, `convert`). It is checked before anything is written and opened only once the other options are checked: a file inside the experiment or masks folder (given or recorded by the earlier run), inside the folder of the copies (`convert`), or named as one of the run's files in the output folder (`plane_histograms.csv`, `run_manifest.json`, the reports, `experiment_design.csv`, `calibration.csv`, `mask_relationships.json`, the lock) is refused and nothing is written; so is a file that is a hard link (it has another name). Any other name in the output folder is fine, for example `run.log` | +| `--log FILE` | Write technical details to a file (`run`, `masks`, `convert`). It is checked before anything is written and opened only once the other options are checked: a file inside the experiment or masks folder (given or recorded by the earlier run), inside the folder of the copies (`convert`), or named as one of the run's files in the output folder (`plane_histograms.parquet`, `run_manifest.json`, the reports, `experiment_design.csv`, `calibration.csv`, `mask_relationships.json`, the lock) is refused and nothing is written; so is a file that is a hard link (it has another name). Any other name in the output folder is fine, for example `run.log` | | `--masks FOLDER` | The masks folder (§2). `check` lists the mask types found and checks every mask from its header; `run` stops on a mask error and records the masks in `run_manifest.json`. A masks folder other than the one an earlier run recorded does not reuse the mask axes stated for that folder's masks (`--mask-axes`): state them again for the new folder (those of OME-Zarr label images are kept) | | `--mask-axes TYPE=ROLES` | The axes of a mask type, one role (Y, X, Z or T) per axis as stored, stated once per type: `Cells=TYX` for plain stacks of time points whose files do not name their axes; a 2D mask needs none, and `Cells=YX` (the removed shared 2D mask) is the error `shared_mask_not_supported` (repeatable; `check`, `run`, `masks`). Masks are never reordered. | +**The lab-links file.** `--lab-links` takes a JSON file of lab-tool links (for example +LabChronicle). It is recorded in `run_manifest.json` only (`lab_links`), and is not offered by +the notebook. + +- It holds exactly the keys `repository_url`, `commit` (the full 40- or 64-character lowercase + SHA) and `experiment_path`, as non-empty text. It may also hold `repeat_codes`, which maps + each lab-tool repeat code to a biological repeat ID of the description (for example + `{"R001": "rep1"}`). +- Any other key, a value of another type, an empty value, spaces around a value, or a key given + twice is refused before anything is read (`lab_links_invalid`). +- A `repository_url` holding a credential (a password, `user:password@`, in any form; a user + name before `@` in a URL whose scheme is not `ssh`, `git+ssh` or `ssh+git`, because + `https://TOKEN@host/...` carries a token there), a query string or a fragment (`?` or `#`) is + refused (`lab_links_invalid`). The refusal does not repeat the URL: a credential is never + written to the manifest. An SSH remote's login name (`git@host:lab/db.git`, + `ssh://git@host/...`) is kept. +- The links change no result: no row, digest, cache or other file. They are not taken over by + the next run: give the file to each run it belongs to. + After writing, `run` prints the intensity checks of the table, grouped by kind, each with the channel, the image or biological repeat and the values compared, and what to do once per kind; it draws no plots (the notebook does). Then it prints the channel check: each @@ -968,16 +1111,16 @@ stored as 8-bit do not. The same experiment in 16 bits and as 0-1 floats gives t findings only while the channel's high percentile is above about 333 counts; below that, the whole-number files have a floor that floats do not. -**Exit status.** Every command (`check`, `run`, `masks`, `calibrate`, `describe` and -`convert`) exits with status 1 when it prints an error, and with 0 otherwise: warnings, -intensity warnings included, never change it. So `check` exits with 1 on every error it -reports, `A_DESCRIPTION_REQUIRED` included. Options that cannot be read exit with 2. Scripts can therefore stop on any -non-zero status. +**Exit status.** Commands use exit status 0 for successful completion and 1 for a refused +operation. Invalid command-line arguments normally return 2. Read the command's final status +message before proceeding. Warnings, intensity warnings included, never change the status. -The optional `masks` command reads the masks and tells how they relate: +If your analysis uses masks, run the `masks` command after preprocessing. It checks the mask +pixels against their declared representation and reports relationships between mask types. +Skip this step only if the downstream analysis does not use masks. ```bash -morphobricks-preprocessing masks /data/exp1 --masks /data/exp1_masks +morphobricks-preprocessing masks my_experiment --masks my_masks ``` It reads every image's masks, one image at a time, and prints for each kind of mask @@ -1167,6 +1310,17 @@ metadata give none, or the wrong one, state them in `calibration.csv` in the out folder. Nothing is ever guessed: an image with neither is *uncalibrated*, and the report says so. +The most common case, 0.65 µm pixels in X and Y for the whole experiment, then a run that +records them: + +```bash +morphobricks-preprocessing calibrate my_experiment --size . XY 0.65 um +morphobricks-preprocessing run my_experiment +``` + +Run preprocessing again after every change made with `calibrate`: the sizes are recorded only +by the next run. More examples: + ```bash # 0.65 um pixels for the whole experiment; a 2 um z-step for one condition morphobricks-preprocessing calibrate /data/exp1 --size . XY 0.65 um --size treated Z 2 um @@ -1227,14 +1381,37 @@ exit status; it is not printed when the experiment is given or recorded. When the metadata of some images name their axes wrongly (the errors `axes_yx_swapped`, `axes_contradict_header`, `axes_x_before_y`) or do not name them at all (the warning `axes_not_named`), and you are sure of the roles, save the images again as named-axis -copies with your roles, then run preprocessing on the copies: +copies with your roles, then run preprocessing on the copies. `convert` has three common uses: ```bash -morphobricks-preprocessing convert /data/exp1 --to /data/exp1_named_axes --axes ZXY --output /data/exp1_MorphoBricks_Preprocessing -morphobricks-preprocessing check /data/exp1_named_axes --output /data/exp1_MorphoBricks_Preprocessing -morphobricks-preprocessing run /data/exp1_named_axes --output /data/exp1_MorphoBricks_Preprocessing --axes ZYX +# Correct axis metadata: write copies whose metadata name your roles +morphobricks-preprocessing convert my_experiment --to my_experiment_named --axes CYX +# Save a large fluorescence mosaic as OME-Zarr, so later tools can read it in windows +morphobricks-preprocessing convert my_slides --to my_slides_zarr --axes CYX --store ome-zarr +# Make maximum projections of Z-stacks (2-D copies) +morphobricks-preprocessing convert my_experiment --to my_experiment_max --axes ZCYX --project max ``` +These axis orders are examples. Use the actual stored order of your images. RGB TIFFs store +their colour samples last, so use `YXC` rather than `CYX`; `convert` does not check the order +against the file, so look at a copy. + +**The copies are a new experiment folder.** Describe and publish the copies before `check` and +`run`, for example for the projections: + +```bash +morphobricks-preprocessing describe my_experiment_max +morphobricks-preprocessing describe my_experiment_max --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +morphobricks-preprocessing check my_experiment_max +morphobricks-preprocessing run my_experiment_max +``` + +The same applies to `my_experiment_named` and `my_slides_zarr`. Projected copies always need +their own description and output folder. Named-axis and OME-Zarr copies are the one +exception: if the originals already have a published description in an output folder, give +that folder to `check` and `run` on the copies with `--output` instead (see below). + `--axes` gives your roles for the original images, exactly as for `run`; they are never taken from the metadata. `convert` writes a new folder (`--to`, outside the experiment) with the experiment's folders and file names: the images with axis problems as OME-TIFF @@ -1337,7 +1514,8 @@ make a projected copy first: default method; `--z-range 2:10` uses only those slices of every image, zero-based with the end excluded, `4:5` is the single slice 4, and every image must have them), or in Python `convert_experiment(EXP, mapping, FOLDER, projection=Projection("max", (2, 10)))`. -Every image of the experiment is written as a 2-D OME-TIFF of the same folders and names: +Every image of the experiment is written as a 2-D OME-TIFF (or a 2-D OME-Zarr image with +`--store ome-zarr`) of the same folders and names: its axes are your roles without Z (`ZCYX` becomes `CYX`), each (t, c) is projected on its own, and the Z size is not written to the copy (it is recorded in the conversion record as dropped). Your originals are only read. The pixel type is decided by the input type and the @@ -1349,8 +1527,8 @@ to infinity is refused (`projection_overflow`). The copy's OME-XML says how it w the conversion record (version 4) holds the method, the slices used, the source's SHA-256, the types, the rounding and the dropped Z size for every image. Masks are never projected: masks with depth slices stop the projection (`projection_masks_3d`); 2-D masks stay where -they are. OME-Zarr images are not projected yet (`projection_zarr_not_supported`; exclude -them). One folder holds one method and one slice range (`copy_differs` otherwise). The command prints the next commands with a +they are. OME-Zarr source images are not projected in this release (`projection_zarr_not_supported`; +export TIFF copies of them first, or process the TIFF images separately). One folder holds one method and one slice range (`copy_differs` otherwise). The command prints the next commands with a new output folder (by default the copy folder's name with `_MorphoBricks_Preprocessing`): the projected copies are a different source, so the description starts again there (the design and the stated pixel sizes are entered again). A run on the copies records the projection in its manifest (`projection`: the method, the slices used, the source SHA-256 of every image) and the report says "max projections of slices 1:4". Masks next to projected images are used as they are, with the warning `masks_on_projected_images`: check that they were made on, or for, the projection. A run on projected copies reads the conversion record strictly: a record that is missing or does not match the run is refused, never read as a plain image. The notebook card follows. @@ -1388,49 +1566,56 @@ copies (optional)** card appears under it, calling the same functions as the com The card is not shown when another brick embeds step 1 without the output folder (`folder_step(show_output=False)`). -### Declaring masks added after preprocessing (`declare-masks`) +### Declaring existing masks or adding new masks (`declare-masks`) -Masks you make after preprocessing (a segmentation of the output, for example) must be declared -in the published description before `run --masks` accepts them; otherwise the run refuses them -(`R_MASK_TYPE_NOT_DECLARED`). The notebook declares them on its *Masks* question or in its -Register step. On the command line, say what each mask type is: +Declare each mask type before running preprocessing with those masks. You can do this +immediately after publishing the experiment description, or add masks to an existing +preprocessing run later. An undeclared mask type is refused (`R_MASK_TYPE_NOT_DECLARED`). The +notebook declares masks on its *Masks* question or in its Register step. On the command line, +say what each mask type is: ```bash -morphobricks-preprocessing declare-masks --output /data/exp1_MorphoBricks_Preprocessing \ - --masks /data/exp1_masks --type Cells=instances --type Nuclei=instances -morphobricks-preprocessing run --output /data/exp1_MorphoBricks_Preprocessing --masks /data/exp1_masks -morphobricks-preprocessing masks --output /data/exp1_MorphoBricks_Preprocessing --masks /data/exp1_masks +morphobricks-preprocessing describe my_experiment --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +morphobricks-preprocessing declare-masks --output my_experiment_MorphoBricks_Preprocessing \ + --masks my_masks --type Cells=instances +morphobricks-preprocessing run my_experiment --masks my_masks +morphobricks-preprocessing masks --output my_experiment_MorphoBricks_Preprocessing ``` -- `TYPE` is the mask type's folder name. `REPRESENTATION` is `instances` (each object has its +The last command checks the mask pixels and reports their properties and relationships. Run it +before using the masks in another MorphoBricks tool. + +- `TYPE` is the mask type: its folder name, or the file-name ending of masks such as + `image_01_cp_masks.tif` (§2, "Masks"). `REPRESENTATION` is `instances` (each object has its own number: Cellpose output), `binary` (foreground / background) or `parent_labels` (each non-zero value one group). There is no default; nothing is guessed from the files. -- The mask ID is the folder name. When that is not a valid mask ID (`nuclei-mask`), give one: - `--type nuclei-mask=binary:nuclei`. -- The description is published as the notebook publishes it: under the output folder's lock and - against the version it was read from. Running the command again with the same answers changes - nothing. A mask type already declared otherwise is refused: change it in the notebook's - describe steps. +- The mask ID is the mask type unless you give another after a colon. Give one when the type is + not a valid mask ID (`--type nuclei-mask=binary:nuclei`), or to give a file-name ending a + clearer name (`--type cp_masks=instances:Cells`). +- The command updates the saved experiment description safely. Repeating an identical + declaration makes no change. A mask type already declared otherwise is refused: change it in + the notebook's describe steps. - `--masks` also checks each mask type against the masks folder (no folder there that differs only in upper/lower case). -- Masks that are not in a masks folder of their own, OME-Zarr label images (`.zarr/labels/`) - or `_.tif` beside the images, need no `--masks`: the command then prints the next - commands without it (`run EXPERIMENT --output FOLDER`, the experiment folder left out when a - run of the output folder records it). +- OME-Zarr label images (`.zarr/labels/`) need no `--masks`: the command then + prints the next commands without it (`run EXPERIMENT --output FOLDER`, the experiment folder + left out when a run of the output folder records it). - `check` reports a mask type the description does not declare exactly as `run` refuses it (`R_MASK_TYPE_NOT_DECLARED`, naming the type), so you see it before the run. Its fix names - both ways out: `--type TYPE=REPRESENTATION` to use it, `--ignore TYPE` to skip it. -- **Skipping a mask type you do not use (`--ignore TYPE`, repeatable).** An OME-Zarr image may - carry label images of another tool, or a masks folder a mask type outside your analysis. - `declare-masks --output FOLDER --ignore TYPE` lists it in `ignored_masks.toml` beside - `morphobricks.toml` (the description itself has no place for "not used"); `check` and `run` - then leave it out, without reading or recording it, instead of refusing it. The run records - the list and the file's SHA-256 in `run_manifest.json` (`ignored_masks`), so later bricks - neither refuse those label images as unrecorded nor accept a list changed since the run (run - preprocessing again after changing it). Undeclared types that are not listed are still - refused. A declared type cannot be ignored; declaring it with `--type` takes it off the list - (the file is removed when the list becomes empty). `--type` and `--ignore` may be given - together; at least one is needed. + both ways out: `--type TYPE=instances` (or `binary`, `parent_labels`, each with what it + means; none is guessed) to use it, `--ignore TYPE` to skip it. +- **Skipping a mask type you do not use (`--ignore TYPE`, repeatable).** Ignored mask types are + recorded in `ignored_masks.toml`. Preprocessing skips them. Declare a previously ignored type + with `--type` to use it again. Run preprocessing after changing the list. For example: + + ```bash + morphobricks-preprocessing declare-masks --output my_experiment_MorphoBricks_Preprocessing \ + --type Cells=instances --ignore OtherLabels + ``` + +- Do not declare and ignore the same mask type. If the ignore operation fails after new + declarations have been saved, those declarations remain saved. - In Python: `morphobricks_preprocessing.mask_declare.declare_masks(output, {"Cells": "instances"})`. ### Converting a mask (`convert-mask`) @@ -1470,17 +1655,20 @@ masks** does the same. ### An H&E tissue mask (optional) -For H&E images (a unit declared `image_type = "rgb"`), `tissue-mask` writes a **new** region mask -that leaves out nuclei, red blood cells and empty space, so that a brick such as fiberfeatures -measures the tissue between them. It needs the `he-mask` extra: +For H&E images (a unit declared `image_type = "rgb"`), `tissue-mask` writes a binary region +mask designed to exclude nuclei, red blood cells and empty background, so that a tool such as +fiberfeatures measures the tissue between them. The images must be 8-bit RGB, with three colour +channels, one depth plane and one time point. It needs the `he-mask` extra (see +[Installing for the command line](#installing-for-the-command-line)): ```bash -pip install "morphobricks-preprocessing[he-mask]" -morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preprocessing --to HETissue +morphobricks-preprocessing tissue-mask --output my_experiment_MorphoBricks_Preprocessing --to HETissue ``` -- It is a **fixed rule**, `he_tissue_v2` by default, and it is **provisional**: its numbers are - not frozen until an acceptance report is accepted. `he_tissue_v2` first measures each image's +Inspect the masks (the notebook's preview, or the printed "kept" share) before declaring them. + +- It is a **fixed rule**, `he_tissue_v2` by default. The rule is provisional and may change in a + later version. The rule version is recorded with each mask. `he_tissue_v2` first measures each image's white from its brightest pixels (the glass), so scans whose glass is grey rather than white work; `--rule he_tissue_v1` keeps the white fixed at 255 (it keeps nothing on such scans). An image with no glass or empty space at all takes its brightest tissue as white: check the @@ -1496,15 +1684,18 @@ morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preproce to `mask_lineage.jsonl`, which records the image, the complete rule and its digest, the exact installed code that computed it and the library versions. An image where nothing is kept gives an all-zero mask: a valid, empty region. -- Running the same command again changes nothing. If the printed line says **this mask will not - be reused on retry**, the installed code could not be verified (for example a development - install, `pip install -e`): the mask is written, but a second run with the same ID is refused; - use a new ID. +- Before declaring the generated mask, an identical retry can reuse existing files when their + contents and the software identity can be verified. Once the mask ID is declared, + `tissue-mask` refuses to write under that ID. To generate another version, choose a new ID + with `--to`. If the command says the mask will not be reused on retry, the installed code + could not be verified (for example a development install, `pip install -e`): the mask is + written, but a second run with the same ID is refused; use a new ID. - **A run without a masks folder** (scanner images often have no masks) gets one first: `tissue-mask` creates `_masks` beside the experiment folder (or the new, empty folder `--masks FOLDER` names), records it by running preprocessing again on the output folder - with that masks folder, exactly as `run --masks FOLDER` records one (unchanged images are not - read again), and says so in one line. A folder that exists and is not empty is never adopted: + with that masks folder, exactly as `run --masks FOLDER` records one, and says so in one line. + Histograms of verified unchanged images are reused; content verification may still reread + the source files. A folder that exists and is not empty is never adopted: give another, or run preprocessing with `--masks` yourself if it is your masks folder. - A refusal names the image once, then what to do. - Then declare it, run preprocessing and the masks step again; the command prints these commands @@ -1566,21 +1757,15 @@ it has no lineage file and cannot be declared as a mask of a run: for a MorphoBr The default output folder is next to the experiment folder: `/data/exp1` → `/data/exp1_MorphoBricks_Preprocessing`. -- **`plane_histograms.csv`:** one row per plane (every channel of an image at one depth - slice and time point) with the position (`position_id`, the file name without its - extension), the file name, the zero-based plane coordinates `z` and `t` (0 when the - image has no such dimension), the three labels, the pixel type and the number of - channels; then, for each channel, its exact minimum and maximum, pixel counts and - histogram, in columns ending in the channel number (`Intensity_MinIntensity_C0`, - `Histogram_Count_C1_00042`, …). The table is very wide (one column per bin and channel), - so spreadsheet programs may not open it completely; read it in Python with - `read_plane_histograms()`. The columns are defined in the [normalization brick's - contract](https://github.com/CellMigrationLab/morphobricks-normalization/blob/main/docs/contract.md) - §6.2 (schema version 5: the columns are named by channel ID, for example - `Histogram_Count_DNA_00042`; a `channels` column lists the stains of each plane, and a stain - the image does not have is blank; each channel also has its underflow and overflow, zero - unless the robust range is used). A table written by an earlier version is recomputed on the next - run; later bricks ask you to run this brick again on it. +- **`plane_histograms.parquet`:** the intensity histograms of every image plane, with its + experimental labels and channel IDs. The table contains one row per plane and stores each + channel's histogram as lists of bin indices and counts. Later MorphoBricks tools read this + file to calculate normalisation parameters without rereading the image pixels. Read it in + Python with `read_plane_histograms()` (from `morphobricks_normalization`). The format + (schema version 6) is defined in the [normalization brick's + contract](https://github.com/CellMigrationLab/morphobricks-normalization/blob/main/docs/contract.md). + From v0.10.0, this file replaces `plane_histograms.csv`. To update an older preprocessing + run, run preprocessing again. - **`image_qc.csv`:** one row per plane and channel with image QC metrics measured while the histograms are computed (no extra read): the share of the plane above its Otsu threshold (`foreground_fraction`; `otsu_separation` is about 0.64 for noise and for any dense field @@ -1718,9 +1903,14 @@ Run the notebook or `run` again after adding, changing or removing images: types, and only the manifest records the new type. **After upgrading from an earlier version (v0.5.1 or before):** its run manifest is not read -(only version 5 is, since v0.5.2), so the first run recomputes every row and reuses no recorded +(only versions 5 and 6 are), so the first run recomputes every row and reuses no recorded input: give the axis roles, masks and exclusions again. Later bricks refuse such older runs until they are run again. +**After upgrading from v0.5.2 to v0.9.x:** those runs wrote `plane_histograms.csv`. From v0.10.0, +`plane_histograms.parquet` replaces it, and later tools refuse the old table. To update an +older preprocessing run, run preprocessing again: every row is recomputed and the CSV file is +removed. + Run the brick again after adding images or masks before using a later brick: later bricks read the images and masks this brick's run recorded, and refuse an experiment holding images or masks the run did not record (they name them). @@ -1743,7 +1933,7 @@ continues. | `R_MASK_CONTRADICTS_REPRESENTATION` | Error | The masks step found a file of a mask declared `binary` that is stored as floats, or holds, over all its planes together, a negative value or two or more different positive values (the message names the file and the values found, or its pixel type). A binary mask holds 0 and at most one positive value (an all-zero or all-foreground file is accepted), stored as integers or true/false. Declare the mask as `instances` in the description if every value is an object, or as `parent_labels` (grouped labels) if every value is one group, such as the mitochondria of one cell; or fix the file (save a float mask as integers). The file stays `not yet checked`, so an analysis that names the mask refuses it (`A_MASK_UNCHECKED`) without reading it. | | `R_UNIT_NOT_FOUND`, `R_UNIT_NOT_DECLARED`, `R_UNIT_NOT_HOMOGENEOUS`, `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER`, `R_MASK_TYPE_NOT_DECLARED` | Error | The published description and the folder or the image headers disagree (the message says where). Correct the description, publish it again and run again. | | `R_IMAGE_TYPE_CONTRADICTS_HEADER` for colour scanner files, `R_RGB_OVERRIDE_NOT_THREE_SAMPLES`, `E_RGB_OVERRIDE_WITHOUT_RGB` | Error | Some scanners store colour (RGB) images with a header that does not say RGB (for example TIFF photometric *minisblack* with three samples per pixel). The acquisition declared `image_type = "rgb"` is then refused, and the message says so and names `rgb_header_override`. If the three samples are red, green and blue in this order, add `rgb_header_override = true` to that acquisition in `morphobricks.toml` (beside `image_type = "rgb"`; in the notebook, tick **Read these folders as colour (RGB) although their header does not say colour** on the Image type card of the Channels step; on the command line, only while a new fast-mode description is published, `describe ... --image-type rgb --channels R,G,B --rgb-header-override`, §5; a published description is changed in the notebook) and publish again: the run then accepts the header and records the acquisition in the manifest as declared RGB with the header overridden (`image_type_header_overridden`, `header_photometric`). Every image whose header does not say RGB must have exactly three interleaved samples per pixel, else `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` names the image (reported before `R_UNIT_NOT_HOMOGENEOUS`); the key on an acquisition that is not declared `rgb` is `E_RGB_OVERRIDE_WITHOUT_RGB`. Images of the acquisition that differ only in colour interpretation (some *minisblack*, some RGB) are then one layout. Images whose header already says RGB, or whose format states no colour interpretation (OME-Zarr), do not use the key; the manifest records, per image, whether it was used (`rgb_header_override_images`). Adding, removing or changing the key reopens the "same way" confirmation of that replicate. Only headers are read, never pixels. | -| `R_FAST_LAYOUT_CONTRADICTION` | Error | The published description is in **fast mode** (it has a `channel_layout` table: "every imaging unit has the same channels in the same order", Spec ADR 0006) and some images of the acquisitions that follow it (`channels_from = "experiment"`) contradict that list. One message lists **every** contradicting image, with its FOV key (condition, repeat and acquisition folders, then the image name) and path, and every contradiction found in it: `image_type` (the header says colour where the list is not, or the reverse), `channel_count` (another number of channels), `header_order` (header names of the list in another order) or `header_names` (a header name that is no confirmed name of any channel of the list), each with its C index and what was expected and found. It is decided from the image headers only, before any pixel is read; nothing is reordered, dropped or guessed, and nothing was processed. Tag the acquisitions of these images on their own (`channels_from = "unit"`, confirmed per acquisition), publish again and run again. When the contradiction is an `image_type` of colour scanner files whose header does not say colour (three interleaved samples), the suggested action names the RGB header override instead (`rgb_header_override = true`, the notebook's Image type card), once; while a new description is published from the command line, `describe` also names `--rgb-header-override [FOLDER]` (§5). An image whose header gives no channel names (or an empty name) needs no evidence and follows the list; the manifest records each image of a fast acquisition in `fast_layout_images` (`header_verified` true only when every channel was confirmed by its header name). In such acquisitions this one code replaces `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER` and `R_UNIT_NOT_HOMOGENEOUS` (which stays for the other axes); `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` keeps its priority. An acquisition tagged on its own is checked as in a description without fast mode. Experiments with extra channels in some acquisitions are refused here: tag those acquisitions on their own. | +| `R_FAST_LAYOUT_CONTRADICTION` | Error | The published description is in **fast mode** (it has a `channel_layout` table: "every imaging unit has the same channels in the same order", Spec ADR 0006) and some images of the acquisitions that follow it (`channels_from = "experiment"`) contradict that list. One message lists **every** contradicting image, with its FOV key (condition, repeat and acquisition folders, then the image name) and path, and every contradiction found in it: `image_type` (the header says colour where the list is not, or the reverse), `channel_count` (another number of channels), `header_order` (header names of the list in another order) or `header_names` (a header name that is no confirmed name of any channel of the list), each with its C index and what was expected and found. It is decided from the image headers only, before any pixel is read; nothing is reordered, dropped or guessed, and nothing was processed. Tag the acquisitions of these images on their own (`channels_from = "unit"`, confirmed per acquisition), save the description and run again. When the contradiction is an `image_type` of colour scanner files whose header does not say colour (three interleaved samples), the suggested action names the RGB header override instead (`rgb_header_override = true`, the notebook's Image type card), once; while a new description is published from the command line, `describe` also names `--rgb-header-override [FOLDER]` (§5). An image whose header gives no channel names (or an empty name) needs no evidence and follows the list; the manifest records each image of a fast acquisition in `fast_layout_images` (`header_verified` true only when every channel was confirmed by its header name). In such acquisitions this one code replaces `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER` and `R_UNIT_NOT_HOMOGENEOUS` (which stays for the other axes); `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` keeps its priority. An acquisition tagged on its own is checked as in a description without fast mode. Experiments with extra channels in some acquisitions are refused here: tag those acquisitions on their own. | | `folder_and_id_changed` | Error | *Check and save* (and publication) found an ID changed in the same save as a folder change of the same entity: for example a repeat ID `Day1 -> DayX` while one of its folders was renamed or removed, a condition ID changed while its folder was renamed, or a removed folder's ID typed for the new folder. Neither change is guessed from the other, so the message names the entity, its saved ID and its folders. Undo the ID edit: put the saved ID back (the folder change then saves on its own). A removed folder's ID stays used and is not given to another folder (experiment-v1 4.9). Nothing was published. | | `R_DRAFT_CHANGED` | Error | Notebook: `morphobricks.draft.json` was changed since this notebook read or saved it (another notebook, or a program, saved its own answers in the same output folder). Nothing was saved or published, and the answers saved there are kept. Press **Check folder** in step 1 to read them, then give your change again. | | `R_DRAFT_EXISTS` | Error | Command line (`describe --publish`): the output folder holds `morphobricks.draft.json`, answers saved in the notebook that the command does not read. Nothing was published or written. Finish those answers and publish them in the notebook (step 1, **Check folder**, then **Check and save**), or, if they are not wanted, remove or archive that file yourself and run the command again. | @@ -1787,7 +1977,7 @@ continues. | `plane_over_memory_limit` | Error | A plane cannot be read within the memory limit, not even in blocks (for example, it is stored compressed in one piece). Raise the limit, or save the images again as tiled or uncompressed TIFF files or as OME-Zarr with smaller chunks. | | `compression_not_bounded` | Error | Planes too large to read whole within the memory limit are stored with a TIFF compression whose decoding memory has not been measured (old-style JPEG, PackBits, Zstandard, WebP, JPEG 2000, ..., or JPEG in another form than 8-bit greyscale, RGB or YCbCr), so they are not read in blocks: only uncompressed, deflate (zlib), LZW, LZMA and 8-bit greyscale, RGB or YCbCr JPEG TIFF images are (decoded by imagecodecs, a required dependency: an image is also refused when the installed imagecodecs is missing, older than 2024.12.30 or, for JPEG, not built on libjpeg-turbo 3, and the message says so). The message names the compression. Save the images again as uncompressed, deflate, LZW or LZMA TIFF files (tiled, for large images) or as OME-Zarr, or raise the memory limit so that their planes are read whole. The same refusal, from the header and before any pixel is read, stops window reads and `RunInputs.read_plane` of such an image whatever its size. | | `unsupported_layout` | Error | The image cannot be read one plane at a time. Check the axis roles or export again. | -| `unreadable_planes` | Error | Pixel data cannot be decoded. The message names each plane that failed (its T, Z and C index and the channel ID) and why, at most 20 per image followed by "and N more"; the run report lists every one (`unreadable_planes`; in the notebook's run report, under *Unreadable planes*, one folded list per image); no `plane_histograms.csv` is written, since one channel that cannot be measured fails the whole table. Export again, or exclude the image. | +| `unreadable_planes` | Error | Pixel data cannot be decoded. The message names each plane that failed (its T, Z and C index and the channel ID) and why, at most 20 per image followed by "and N more"; the run report lists every one (`unreadable_planes`; in the notebook's run report, under *Unreadable planes*, one folded list per image); no `plane_histograms.parquet` is written, since one channel that cannot be measured fails the whole table. Export again, or exclude the image. | | `image_over_max_ram` | Error | `--workers auto --max-ram`: an image needs more working memory to read than the budget leaves (estimated from its header). Nothing was read. Raise `--max-ram`, or lower `--memory-limit` so its planes are read in smaller blocks. | | `invalid_bin_count` | Error | Bin count outside the allowed range. Use the default or a value in range. | | `experiment_not_recorded` | Error | `run` was given no experiment folder, and the output folder holds no v0.4.0 run that records one (or no output folder was given). Give the experiment folder. | @@ -1806,15 +1996,15 @@ continues. | `copy_folder_not_empty` | Error | `convert`: the folder for the copies holds files and no conversion record. Nothing is overwritten; choose a new or empty folder. When the folder also holds the work folder of a stopped conversion, the message says the files named may be copies it had moved into place when it was interrupted: remove them, then convert again. | | `copy_differs` | Error | `convert`: images in the folder of copies differ from the copies this conversion would write (an original changed, other roles, a copy changed, an image no longer in the experiment), or the folder holds copies of another experiment. Nothing is overwritten; convert into a new folder, or remove those copies first. | | `cannot_convert_pixel_type` | Error | `convert`: images of 64-bit integers cannot be saved as OME-TIFF, and pixel values are never changed to fit. Save them again with named axes in a 32-bit type if their values fit, or correct the roles. | -| `nothing_to_project` | Error | `convert` with a projection: no image has a depth axis (Z) under the roles you gave. Check the roles; nothing was written. | +| `nothing_to_project` | Error | `convert` with a projection: no image has a depth axis (Z) under the roles you gave. Check the stored axis order: Z must be the axis of the slices of a stack. If these images have no depth dimension, omit `--project`. Nothing was written. | | `projection_z_range_outside` | Error | `convert` with a projection: the slice range does not fit every image; the shorter images are named. Give a range every image has, or leave it out. | | `projection_cannot_be_exact` | Error | `convert` with a projection: a sum or mean of that many slices of that pixel type could not be held exactly. Use max or mean, or a shorter slice range. | | `projection_overflow` | Error | `convert` with a projection: a sum overflows to infinity (float64) at the pixels named. Use max, or mean if the values allow it. | | `projection_undefined` | Error | `convert` with a projection: a sum adds an infinity to its opposite at the pixels named, which is undefined. Use max. | -| `projection_over_memory_limit` | Error | `convert` with a projection: one input plane and its running total do not fit the memory limit. Raise `--memory-limit`. | -| `projection_masks_3d` | Error | `convert` with a projection: masks of the images have depth slices (Z), and masks are never projected. Make 2-D masks on the projected images, or move these masks out of the masks folder. | -| `projection_masks_axes_unknown` | Error | `convert` with a projection: masks have more than Y and X and their axes are not named, so it is not known whether they have depth slices. Name the axes in the masks' metadata, or move them out. | -| `projection_zarr_not_supported` | Error | `convert` with a projection: OME-Zarr images are not projected yet. Exclude them. | +| `projection_over_memory_limit` | Error | `convert` with a projection: one input plane and its running total do not fit the memory limit. Increase `--memory-limit` only if sufficient RAM is available, or export smaller images for projection. | +| `projection_masks_3d` | Error | `convert` with a projection: masks of the images have depth slices (Z), and masks are never projected. Keep the original masks separately, outside the masks folder, then convert the images without those 3-D masks; create new 2-D masks from the projected images and register them with the new experiment. | +| `projection_masks_axes_unknown` | Error | `convert` with a projection: masks have more than Y and X and their axes are not named, so it is not known whether they have depth slices. Check and export the mask axes correctly. If these masks belong to the original 3-D images, keep them separate from the projected experiment. | +| `projection_zarr_not_supported` | Error | `convert` with a projection: projection of OME-Zarr source images is not supported in this release, and no projected copies were written. Export suitable TIFF copies of these images before projection, or process the TIFF images separately. | | `source_changed_during_check` | Error | `convert`: an original changed while its metadata was read, so the metadata may not describe the file that would be copied. Nothing was written; convert again when nothing writes into the experiment. | | `conversion_failed` | Error | `convert`: an image could not be copied (unreadable, changed while copied, or the folder cannot be written). The copies written by this conversion were removed; fix the cause and convert again, or exclude the image. | | `not_enough_space` | Error | `convert`: the copies would not fit on the drive. Free space or choose another drive. | @@ -1857,7 +2047,7 @@ continues. | `lab_links_repeat_unknown` | Error | A lab-tool repeat code names a biological repeat the description does not declare (IDs are compared exactly; a folder name or display name is not an ID). Correct the file. | | `lab_links_repeat_twice` | Error | Two lab-tool repeat codes name the same biological repeat; each repeat has exactly one code. Correct the file. | | `lab_links_repeat_missing` | Error | The lab-tool repeat codes leave out a biological repeat of the description; a mapping names every repeat. Add its code, or leave `repeat_codes` out. | -| `rgb_not_possible` | Error | The image type RGB was chosen, but the images are not three channels of a whole-number pixel type. Choose fluorescence, or check the axis roles: the RGB samples must have the role C. | +| `rgb_not_possible` | Error | The image type RGB was chosen, but the images are not three channels of a whole-number pixel type. If the images are separate stains, describe them as separate channels. If they are genuinely RGB, verify that the stored colour-sample count and axis roles are correct. | | `repeat_group_conflict` | Error | A repeat group holds two folders of the same condition. Move one into another replicate on the *Replicates* page and save the description again (*Check and save*). | | `invalid_experiment_design` | Error | A repeat group has no usable name (empty, `NA`, `nan`, `none`, `null`, `n/a`, ``, or spaces around it), two repeat groups are spelled the same apart from upper and lower case, or a confirmation date is not written `YYYY-MM-DD`. It comes from a description edited by hand or rows built in code; correct the description (the message names the folder). | | `image_intensity_outlier` | Warning (intensity check) | An image's median or high percentile in a channel is far from the other images of its condition and biological repeat. Look at it: it may be out of focus, contain debris or bubbles, or have been acquired differently. Exclude it if it is faulty. | @@ -1878,7 +2068,7 @@ continues. | `manifest_channel_coverage_mismatch` | Error (other bricks) | `RunInputs.open` found a `channel_coverage` in the run manifest that is not the channel coverage of the published `morphobricks.toml` the run read (`ChannelCoverageMismatchError`); the message names `experiment_description.channel_coverage` and each biological repeat that differs. The manifest was changed after the run, so the run is refused, never corrected. Run preprocessing again. | | `manifest_unit_record_malformed` | Error (other bricks) | A record of the run manifest's `experiment_description.units` is not an object with `repeat`, `condition`, `technical_repeat`, `channels` and `image_type_header_verified` of their types, or holds a field the run does not write (`ManifestUnitRecordError`, when the manifest is read). The manifest was changed after the run, or was written by a newer release that records a unit field this one does not know (refused, never ignored); the message names the unit record and the field. Nothing is filled in: run preprocessing again. A manifest written before v0.5.2 never reaches this check: its version is refused first. | | `manifest_unit_record_mismatch` | Error (other bricks) | `RunInputs.open` found a unit record in the run manifest that is not a unit of the published `morphobricks.toml` the run read: an unknown repeat, condition or technical repeat, a unit recorded twice or not at all, other channels, or a declared `rgb_header_override` that the description does not declare (`UnitRecordMismatchError`); the message names the unit record and the field. Run preprocessing again. | -| `ignored_masks_invalid` | Error | `ignored_masks.toml` in the output folder cannot be read as `declare-masks --ignore` writes it (other keys, another version, a name twice or with a `/`, a link). Write it again with `declare-masks --ignore`, or remove the file. | +| `ignored_masks_invalid` | Error | `ignored_masks.toml` in the output folder cannot be read as `declare-masks --ignore` writes it (other keys, another version, a name twice or with a `/`, a link). `declare-masks` reads the list before changing it, so it cannot rewrite an unreadable one: move the file out of the output folder (keep it as a backup), recreate the list with `declare-masks --output FOLDER --ignore TYPE` for every mask type you still intend to skip, and run preprocessing again. | | `masks_folder_not_found` | Error | The masks folder does not exist. Select the folder that holds one folder per kind of mask. Later bricks opening a run (`RunInputs.open(..., masks_root=...)`) refuse a masks folder given that does not exist or is a file with the same code (`MasksFolderNotFoundError`); it is never read as a folder without masks. Give the folder that holds the masks, or leave `masks_root` out to use the one the run recorded. | | `masks_folder_unreadable` | Error | A masks folder given to a later brick (`RunInputs.open(..., masks_root=...)`) cannot be listed, for example for lack of permission, so its masks cannot be checked against the run (`MasksFolderUnreadableError`); the message names the folder and the reason. Check its permissions, or give another folder. | | `output_inside_masks` | Error | The output folder is inside the masks folder, where the run's files would be read as masks. Choose another output folder. | @@ -1992,8 +2182,8 @@ write_mask_report(report, "/data/exp1_MorphoBricks_Preprocessing/mask_relationsh ``` `scan_masks(..., thresholds={"inside_object_share": 0.8})` changes a threshold (the others -keep their defaults, `DEFAULT_THRESHOLDS`). The label images of OME-Zarr images are always -used, with or without a masks folder; `preflight(..., mask_axes={"Cells": "TYX"})` states +keep their defaults, `DEFAULT_THRESHOLDS`). OME-Zarr label images are discovered +automatically, except for mask types explicitly listed in `ignored_masks.toml`; `preflight(..., mask_axes={"Cells": "TYX"})` states the axes of a mask type whose files do not name them; `read_mask` reads one mask's pixels (a `ValueError` for a negative label or a label above 2,147,483,647, the int32 limit of every MorphoBricks brick, as in `piece_counts`, `pair_counts` and `scan_masks`; `check_labels` diff --git a/pyproject.toml b/pyproject.toml index c8057452..2d1673e0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -283,9 +283,11 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.preview_render" = "pure" "morphobricks_preprocessing.cli" = "ui" "morphobricks_preprocessing.cli_run" = "ui" +"morphobricks_preprocessing.cli_run_options" = "ui" "morphobricks_preprocessing.cli_calibrate" = "ui" "morphobricks_preprocessing.cli_masks" = "ui" "morphobricks_preprocessing.cli_describe" = "ui" +"morphobricks_preprocessing.cli_describe_options" = "ui" "morphobricks_preprocessing.cli_convert" = "ui" "morphobricks_preprocessing.cli_convert_mask" = "ui" "morphobricks_preprocessing.cli_declare_masks" = "ui" diff --git a/src/morphobricks_preprocessing/cli.py b/src/morphobricks_preprocessing/cli.py index 6ff42a8e..0843eb60 100644 --- a/src/morphobricks_preprocessing/cli.py +++ b/src/morphobricks_preprocessing/cli.py @@ -37,6 +37,7 @@ import argparse import logging +import shlex import sys from collections.abc import Sequence from pathlib import Path @@ -90,6 +91,48 @@ __all__ = ["build_parser", "main", "parse_size"] +_CHECK_DESCRIPTION = """\ +Check a described experiment without measuring image pixels: the folders, the +image headers and any masks folder you give. Write a report and suggest the +image axis roles. + +Requires: a published experiment description (describe --publish). +check does not perform every validation of the description that run performs, +and it does not reuse the recorded --exclude, --masks and --mask-axes choices: +give the same options as your intended run.""" + +_CHECK_EXAMPLE = """\ +Example: + morphobricks-preprocessing check my_experiment + +If the check passes, run preprocessing next (run).""" + +_RUN_DESCRIPTION = """\ +Process a described experiment: validate the description and the axis roles, +then compute one intensity histogram per channel of every image plane +(plane_histograms.parquet). A rerun reads only new or changed images and reuses +the recorded exclusions and masks folder. + +Requires: a published experiment description (describe --publish).""" + +_RUN_EXAMPLE = """\ +Example: + morphobricks-preprocessing run my_experiment + +Then, if your analysis uses masks, check them (masks). Give the output folder +(my_experiment_MorphoBricks_Preprocessing) to the next MorphoBricks tool.""" + +_MASKS_DESCRIPTION = """\ +Check the mask pixels of a preprocessing run against their declared +representation, and report how the mask types relate. Run it after run when +your analysis uses masks; skip it otherwise. + +Requires: a preprocessing run whose masks are declared (declare-masks).""" + +_MASKS_EXAMPLE = """\ +Example: + morphobricks-preprocessing masks --output my_experiment_MorphoBricks_Preprocessing""" + def build_parser() -> argparse.ArgumentParser: """Build the argument parser.""" @@ -102,18 +145,31 @@ def build_parser() -> argparse.ArgumentParser: check = commands.add_parser( "check", - help="check the folder and image headers, suggest axis roles and write the report", + help="check a described experiment without measuring image pixels; write a report " + "and suggest the image axis roles", + description=_CHECK_DESCRIPTION, + epilog=_CHECK_EXAMPLE, + formatter_class=argparse.RawDescriptionHelpFormatter, ) _common(check) add_missing_as_singleton(check) - run = commands.add_parser("run", help="compute or update the histogram table") + run = commands.add_parser( + "run", + help="process a described experiment: compute or update the histogram table", + description=_RUN_DESCRIPTION, + epilog=_RUN_EXAMPLE, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) _common(run, recorded=True) add_run_arguments(run) masks = commands.add_parser( "masks", - help="find every image's masks, describe them and how they relate (reads the masks)", + help="check the mask pixels of a preprocessing run and how the mask types relate", + description=_MASKS_DESCRIPTION, + epilog=_MASKS_EXAMPLE, + formatter_class=argparse.RawDescriptionHelpFormatter, ) _common(masks, recorded=True) add_masks_arguments(masks) @@ -198,11 +254,16 @@ def _common(parser: argparse.ArgumentParser, *, recorded: bool = False) -> None: help="the experiment folder (default: the one the run in --output recorded)", ) else: - parser.add_argument("experiment", help="the experiment folder") + parser.add_argument( + "experiment", + help="folder containing your original experiment images, organised by condition " + "and repeat", + ) parser.add_argument( "--output", metavar="FOLDER", - help="output folder (default: next to the experiment, _MorphoBricks_Preprocessing)", + help="folder containing the published experiment description and preprocessing " + "results (default: EXPERIMENT_MorphoBricks_Preprocessing beside the images folder)", ) parser.add_argument( "--exclude", @@ -214,8 +275,9 @@ def _common(parser: argparse.ArgumentParser, *, recorded: bool = False) -> None: parser.add_argument( "--masks", metavar="FOLDER", - help="masks folder: one subfolder per mask type, each mirroring the experiment's " - "folders, outside the experiment; the label images of OME-Zarr images are added", + help="external masks folder, separate from the experiment folder: one subfolder per " + "mask type, or the mask type as an ending of each file name (image_01_cp_masks.tif); " + "OME-Zarr label images are also found automatically", ) _mask_axes_option(parser) _remove_stale_lock_option(parser) @@ -309,8 +371,7 @@ def _check(args: argparse.Namespace) -> int: if undeclared: # as 'run' refuses them, with its words print() print(format_issues(undeclared)) - axis_errors = () - chunks: list[ValidationIssue] = [] + axis_errors, chunks = (), [] if review is not None: # The suggested roles are the header's own, so they never contradict it; 'run' # checks the roles given with --axes. @@ -332,18 +393,59 @@ def _check(args: argparse.Namespace) -> int: f"Suggested option for 'run': --axes {pre.suggested_mapping.roles_string}" f"{singleton} (axes in the files: {pre.suggested_mapping.axes})" ) - type_review = review_image_type(pre.metadata, review, declared=declared_type(args, pre)) - print( - f"Suggested image type: {type_review.suggested}, because {type_review.reason}. " - "'run' uses it unless you give --image-type." - ) + _print_image_type(args, pre, review) path, refusal = write_check_report(pre, args.output, review, extra=[*undeclared, *chunks]) - print() - print(format_issues([refusal]) if refusal else f"Report written to {path}" if path else "") + if refusal is not None: + print("\n" + format_issues([refusal])) blocked = not pre.ok or axis_errors or undeclared or refusal is not None + roles = None if review is None else pre.suggested_mapping.roles_string + print("\n" + check_status(args, path, blocked=bool(blocked), roles=roles, missing=missing)) return 1 if blocked else 0 # every error printed exits with 1, as 'run' does +def _print_image_type(args: argparse.Namespace, pre: Preflight, review: AxisReview) -> None: + """Print the image type the headers suggest, to compare with the published description.""" + type_review = review_image_type(pre.metadata, review, declared=declared_type(args, pre)) + print( + f"Suggested image type: {type_review.suggested}, because {type_review.reason}. " + "Confirm that it agrees with the published experiment description." + ) + + +def check_status( + args: argparse.Namespace, + path: Path | None, + *, + blocked: bool, + roles: str | None, + missing: bool, +) -> str: + """Return the final line of ``check``: passed (with the run command) or failed (P1.8). + + The run command keeps the experiment, ``--output``, ``--exclude``, ``--masks`` and + ``--mask-axes`` given to ``check``, and adds the suggested ``--axes``; paths are quoted. + """ + saved = f" Report saved to {path}." if path else "" + if blocked: + return f"Header check failed.{saved} Correct the errors above, then repeat the check." + words = ["morphobricks-preprocessing run", shlex.quote(args.experiment)] + if args.output: + words.append(f"--output {shlex.quote(args.output)}") + words += [f"--exclude {shlex.quote(item)}" for item in args.exclude] + if args.masks: + words.append(f"--masks {shlex.quote(args.masks)}") + stated = args.mask_axes or {} # read by main into {type: roles} + words += [f"--mask-axes {shlex.quote(f'{kind}={value}')}" for kind, value in stated.items()] + if roles: + words.append(f"--axes {roles}") + if missing: + words.append("--missing-as-singleton") + return ( + f"Header check passed.{saved} Review the warnings and axis roles above, then run " + f"preprocessing:\n {' '.join(words)}" + ) + + def undeclared_mask_issues(args: argparse.Namespace, pre: Preflight) -> list[ValidationIssue]: """Return ``run``'s refusal of every mask type found that the description does not declare. diff --git a/src/morphobricks_preprocessing/cli_calibrate.py b/src/morphobricks_preprocessing/cli_calibrate.py index 9356a290..5e724fdb 100644 --- a/src/morphobricks_preprocessing/cli_calibrate.py +++ b/src/morphobricks_preprocessing/cli_calibrate.py @@ -36,7 +36,19 @@ def add_calibrate_parser(commands: argparse._SubParsersAction) -> argparse.Argum """Add the ``calibrate`` command and its options; return its parser.""" parser = commands.add_parser( "calibrate", - help="show or state the pixel sizes in calibration.csv in the output folder", + help="show or state the physical pixel sizes of the images", + description="""\ +Show or state the physical pixel sizes of the images (calibration.csv in the +output folder). A stated size replaces what the image metadata say; images +without a stated size keep the sizes in their metadata, or stay uncalibrated. +The image pixels are never changed.""", + epilog="""\ +Example (every image: 0.65 micrometres along X and Y): + morphobricks-preprocessing calibrate my_experiment --size . XY 0.65 um + morphobricks-preprocessing run my_experiment + +Run preprocessing again afterwards to record the sizes.""", + formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( "experiment", @@ -50,9 +62,9 @@ def add_calibrate_parser(commands: argparse._SubParsersAction) -> argparse.Argum action="append", default=[], metavar=("TARGET", "AXES", "SIZE", "UNIT"), - help="state a size: TARGET is . for the whole experiment, or a folder or image " - "relative to the experiment folder; AXES are X, Y and/or Z (XY: the same size for " - "both); UNIT is a length unit such as um or nm (repeatable)", + help="state the physical pixel size: TARGET is . for every image, or a folder or image " + "path relative to the experiment; AXES are X, Y and/or Z (XY: the same size for both); " + "UNIT is a length unit such as um or nm. Example: --size . XY 0.65 um (repeatable)", ) parser.add_argument( "--pixels", @@ -60,7 +72,8 @@ def add_calibrate_parser(commands: argparse._SubParsersAction) -> argparse.Argum action="append", default=[], metavar=("TARGET", "AXES"), - help="state that these axes are measured in pixels: deliberately uncalibrated (repeatable)", + help="use pixel units rather than physical lengths for these axes; does not rescale or " + "modify the image pixels (repeatable)", ) parser.add_argument( "--remove", @@ -114,7 +127,10 @@ def calibrate_command(args: argparse.Namespace) -> int: print(f"Nothing was changed: {exc}") return 1 if written is not None: - print(f"Written to {written}. The next run records these sizes; no row is recomputed.") + print( + f"Calibration saved to {written}. Run preprocessing again to record these pixel " + "sizes; existing verified histograms can be reused." + ) print(calibration_summary(changed)) return 0 @@ -143,7 +159,10 @@ def _axes(text: str) -> tuple[str, ...]: def calibration_summary(calibration: Calibration) -> str: """Describe the statements, one per line, or say there are none.""" if not calibration.entries: - return "No pixel size is stated: every image uses the sizes in its metadata." + return ( + "No pixel sizes have been stated. Pixel sizes are taken from the image metadata " + "where available; otherwise the images remain uncalibrated." + ) lines = ["Stated pixel sizes (calibration.csv):"] lines.extend( f" {entry.target} {entry.axis}: {entry.describe()}" for entry in calibration.entries diff --git a/src/morphobricks_preprocessing/cli_convert.py b/src/morphobricks_preprocessing/cli_convert.py index 6a0259e5..c55aa98b 100644 --- a/src/morphobricks_preprocessing/cli_convert.py +++ b/src/morphobricks_preprocessing/cli_convert.py @@ -26,7 +26,9 @@ from __future__ import annotations import argparse +import shlex import sys +from dataclasses import dataclass from pathlib import Path from .cli_run import mapping_option, parse_size, print_progress @@ -57,11 +59,29 @@ def add_convert_parser(commands: argparse._SubParsersAction) -> argparse.Argumen """ convert = commands.add_parser( "convert", - help="save the images whose axes are wrong or not named as named-axis OME-TIFF copies " - "with your roles (or every image as OME-Zarr, --store ome-zarr), in a new folder (the " - "originals are only read)", + help="write image copies with corrected axis metadata, convert images to OME-Zarr, or " + "project Z-stacks to 2-D; the original images are unchanged", + description="""\ +Write image copies in a new folder: with corrected axis metadata (OME-TIFF), as +OME-Zarr (--store ome-zarr), or as 2-D projections of Z-stacks (--project). +The original images are only read. The copies are an experiment of their own: +describe and publish it before you check and run preprocessing on it.""", + epilog="""\ +Examples (the axis orders are examples: give the stored order of your images; +an RGB TIFF stores its colours last, YXC): + morphobricks-preprocessing convert my_experiment --to my_experiment_named --axes CYX + morphobricks-preprocessing convert my_slides --to my_slides_zarr --axes CYX \\ + --store ome-zarr + morphobricks-preprocessing convert my_experiment --to my_experiment_max \\ + --axes ZCYX --project max + +convert does not check the axis order against the image: look at a copy.""", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + convert.add_argument( + "experiment", + help="folder containing your original experiment images, organised by condition and repeat", ) - convert.add_argument("experiment", help="the experiment folder") convert.add_argument( "--to", metavar="FOLDER", @@ -73,22 +93,33 @@ def add_convert_parser(commands: argparse._SubParsersAction) -> argparse.Argumen "--axes", metavar="ROLES", required=True, - help="the role of each axis of the images, in the order of their axes (X, Y, Z, C, T, " - "or - for none): the roles the copies are written with", + help="roles of the stored dimensions, in their stored order: Y and X are image height " + "and width, C is channel, Z is depth, T is time, - an unused length-1 dimension; for " + "example CYX (an RGB TIFF: YXC). The copies are written with these roles", ) convert.add_argument( "--exclude", action="append", default=[], metavar="PATH", - help="image to leave unread, relative to the experiment folder; it is copied as it " - "is (repeatable)", + help="copy this image unchanged instead of converting it, relative to the experiment " + "folder (repeatable). The next commands printed keep it excluded; give the same " + "exclusion whenever you describe, check or run the copies", ) convert.add_argument( "--missing-as-singleton", action="store_true", - help="confirm that images lacking some axes have one plane along them", + help="confirm that an image without a particular dimension has size 1 along it; " + "this does not enable analysis of multi-slice Z-stacks", ) + _add_folder_options(convert) + _add_projection_options(convert) + _add_store_options(convert) + return convert + + +def _add_store_options(convert: argparse.ArgumentParser) -> None: + """Add the memory, lock, store and log options of ``convert``.""" convert.add_argument( "--memory-limit", type=parse_size, @@ -106,15 +137,11 @@ def add_convert_parser(commands: argparse._SubParsersAction) -> argparse.Argumen "--store", choices=STORES, default=OME_TIFF, - help="how the copies are written: ome-tiff (default; only the images whose axes are " - "wrong or not named, the others copied as they are) or ome-zarr (every image that is " - "read, as an OME-Zarr image .ome.zarr, OME-NGFF 0.4; RGB colour images " - "too). Reading OME-Zarr copies needs the zarr extra", + help="ome-tiff (default): correct the axis metadata where needed and copy the other " + "images unchanged; ome-zarr: convert every selected image to OME-Zarr (OME-NGFF 0.4), " + "RGB images included. Writing and reading OME-Zarr needs the zarr extra", ) - _add_folder_options(convert) - _add_projection_options(convert) convert.add_argument("--log", metavar="FILE", help="write technical details to this file") - return convert def _add_folder_options(convert: argparse.ArgumentParser) -> None: @@ -122,14 +149,16 @@ def _add_folder_options(convert: argparse.ArgumentParser) -> None: convert.add_argument( "--output", metavar="FOLDER", - help="the output folder of your runs on the originals, named in the next commands " - "(default: the experiment folder's name with _MorphoBricks_Preprocessing)", + help="preprocessing output folder of the original experiment (default: " + "EXPERIMENT_MorphoBricks_Preprocessing); --to says where the copies go. Projected " + "copies get a new output folder of their own", ) convert.add_argument( "--masks", metavar="FOLDER", - help="the masks folder of your runs, which the copies may not be inside; by default " - "the one recorded by the run in the output folder (--output)", + help="masks folder of the original experiment, used to check that the copies are not " + "written inside it and that projection can proceed; masks are not converted " + "(default: the one recorded in --output)", ) @@ -141,19 +170,19 @@ def _add_projection_options(convert: argparse.ArgumentParser) -> None: const="", type=_method, metavar="METHOD", - help="write every image as a recorded 2-D projection of its Z-stack: max, mean or " - "sum (there is no default). Z must be among the roles in --axes. The copies are " - "named-axis OME-TIFFs without Z; a 16-bit sum is written in 32 bits, a mean in 64-bit " - "floats, a maximum keeps the type; the Z size is not written but recorded. Masks " - "are never projected: masks with depth slices stop the projection", + help="project the Z slices of each selected image with max, mean or sum (no " + "default); Z must be among the roles in --axes. The output has no Z dimension and is " + "OME-TIFF by default, OME-Zarr with --store ome-zarr. A maximum keeps the pixel type; " + "a 16-bit sum uses 32-bit values, a mean 64-bit floats. Masks are not projected: " + "masks with depth slices stop the projection", ) convert.add_argument( "--z-range", type=_z_range, metavar="START:STOP", - help="with --project: use only these slices of every image (zero-based, STOP " - "excluded, for example 2:10; 4:5 is the single slice 4). Every image must have " - "them. Default: all slices", + help="with --project: the Z slices to project; 2:10 uses slices 2 to 9, counting the " + "first slice as 0 (4:5 is slice 4 alone). Every selected image must contain that " + "range. Default: all slices", ) @@ -213,12 +242,44 @@ def convert_command(args: argparse.Namespace) -> int: print() if result.projection is not None: output, given = default_output_folder(Path(args.to).resolve()), True - print(conversion_text(result, output, given=given, store=args.store)) + after = _NextOptions(tuple(args.exclude), args.missing_as_singleton) + print(conversion_text(result, output, given=given, store=args.store, after=after)) return 0 if result.written else 1 +@dataclass(frozen=True) +class _NextOptions: + """The options of a conversion the next commands on the copies keep (review P0.2, P1.18).""" + + exclude: tuple[str, ...] = () + missing_as_singleton: bool = False + + def arguments(self) -> str: + """Return the options as command-line text, each path quoted for the shell.""" + words = [f" --exclude {shlex.quote(path)}" for path in self.exclude] + return "".join(words) + (" --missing-as-singleton" if self.missing_as_singleton else "") + + +def _next_commands(dest: Path, output: Path, axes: str, after: _NextOptions) -> list[str]: + """Return the describe, check and run lines for the copies in ``dest`` (paths quoted).""" + folder, out, keep = shlex.quote(str(dest)), shlex.quote(str(output)), after.arguments() + exclude = "".join(f" --exclude {shlex.quote(path)}" for path in after.exclude) + return [ + f" morphobricks-preprocessing describe {folder} --output {out}{exclude}", + "Publish the description with describe --publish and your confirmed channel and " + "design options (or in the notebook). Once it is published, run:", + f" morphobricks-preprocessing check {folder} --output {out}{keep}", + f" morphobricks-preprocessing run {folder} --output {out}{axes}{keep}", + ] + + def conversion_text( - result: ConversionResult, output: Path, *, given: bool = True, store: str = OME_TIFF + result: ConversionResult, + output: Path, + *, + given: bool = True, + store: str = OME_TIFF, + after: _NextOptions | None = None, ) -> str: """Say what a conversion wrote and what to run next, in plain ASCII-safe words. @@ -233,17 +294,21 @@ def conversion_text( says to give the folder of the runs on the originals if it is another one. store ``"ome-tiff"`` or ``"ome-zarr"``: the format the copies were written in. + after + The exclusions and ``--missing-as-singleton`` of the conversion, kept in the next + commands (default: none). Returns ------- str """ + after = after or _NextOptions() dest = result.destination fmt = "OME-Zarr" if store == OME_ZARR else "OME-TIFF" if not result.written: return f"No copies were written in {dest}: read the messages above." if result.projection is not None: - return projection_text(result, output, store=store) + return projection_text(result, output, store=store, after=after) # Cross-brick test F8: the next commands name the output folder of the user's runs, # given with --output; a default one may hold no run (the user then gives theirs). where = "" if given else f" (by default {output}; if your runs used another one, give it)" @@ -252,18 +317,26 @@ def conversion_text( f" written as {fmt} with your roles: {plural(len(result.converted), 'image')}", f" copied as they are: {plural(len(result.copied), 'image')}", f" already there and unchanged: {plural(len(result.reused), 'image')}", - f"Conversion record: {dest / RECORD_FILENAME} (SHA-256 {result.record_sha256})", + f"Conversion details saved to {dest / RECORD_FILENAME}.", "", - "Next, run preprocessing on the copies with the output folder of your runs on the " - f"originals{where}:", - f" morphobricks-preprocessing check {dest} --output {output}", + f"Next, preprocess the copies with the output folder of your runs on the originals" + f"{where}. If it already holds a published description that matches these copies, " + "keep using it and skip describe. Otherwise describe the copied experiment first:", ] axes = f" --axes {result.suggested_axes}" if result.suggested_axes else " --axes ROLES" - lines.append(f" morphobricks-preprocessing run {dest} --output {output}{axes}") + lines += _next_commands(dest, output, axes, after) + if not result.suggested_axes: + lines.append("Replace ROLES with the roles of the copies' stored dimensions.") return "\n".join(lines) -def projection_text(result: ConversionResult, output: Path, *, store: str = OME_TIFF) -> str: +def projection_text( + result: ConversionResult, + output: Path, + *, + store: str = OME_TIFF, + after: _NextOptions | None = None, +) -> str: """Say what a projection wrote and what to run next (a new output folder, a new source). Parameters @@ -275,11 +348,15 @@ def projection_text(result: ConversionResult, output: Path, *, store: str = OME_ different source, so its description starts a new lineage. store ``"ome-tiff"`` or ``"ome-zarr"``: the format the copies were written in. + after + The exclusions and ``--missing-as-singleton`` of the conversion, kept in the next + commands (default: none). Returns ------- str """ + after = after or _NextOptions() dest, projection = result.destination, result.projection bounds = projection.z_range slices = "all slices" if bounds is None else f"slices {bounds[0]}:{bounds[1]}" @@ -294,13 +371,12 @@ def projection_text(result: ConversionResult, output: Path, *, store: str = OME_ f" already there and unchanged: {plural(len(result.reused), 'image')}", " The Z size is not written to the copies; the record keeps it, the slices used " "and the SHA-256 of every source.", - f"Conversion record: {dest / RECORD_FILENAME} (SHA-256 {result.record_sha256})", + f"Conversion details saved to {dest / RECORD_FILENAME}.", "", - "The projected copies are a different source: run preprocessing on them with a new " - f"output folder ({output}), which starts a new description; the design and the " - "pixel sizes are then entered again. Masks are never projected: 2-D masks pair " - "with the projected images as usual.", - f" morphobricks-preprocessing check {dest} --output {output}", - f" morphobricks-preprocessing run {dest} --output {output}{axes}", + f"Projected images were saved in {dest}. Describe them as a new experiment before " + f"running preprocessing, with a new output folder ({output}). Review the channel " + "names, experimental design and pixel sizes. Masks are not projected: make 2-D " + "masks for the projected images.", + *_next_commands(dest, output, axes, after), ] ) diff --git a/src/morphobricks_preprocessing/cli_declare_masks.py b/src/morphobricks_preprocessing/cli_declare_masks.py index b4e1c7fd..44a902d9 100644 --- a/src/morphobricks_preprocessing/cli_declare_masks.py +++ b/src/morphobricks_preprocessing/cli_declare_masks.py @@ -8,8 +8,8 @@ unless ``:ID`` is given (needed when the folder name is not a valid mask ID). ``--masks`` also checks each mask type against the masks folder. The command prints what it declared and the two commands that follow (``run``, then ``masks``): with ``--masks`` they name that folder; without -it they name none, because OME-Zarr label images and ``_.tif`` masks beside the -images are found without a masks folder, and say when to add one. The experiment folder is +it they name none, because OME-Zarr label images are found without a masks folder (other masks are +always in a separate masks folder), and say when to add one. The experiment folder is named only when no run of the output folder records it. ``--ignore TYPE`` (repeatable; owner, 4 December 2026) lists a mask type or OME-Zarr label image the runs do not use in ``ignored_masks.toml`` (:mod:`.ignored_masks`): ``check`` and ``run`` skip it instead of @@ -36,9 +36,9 @@ from .run.reuse import recorded_experiment_root NO_MASKS_FOLDER = ( - "Add --masks FOLDER to both only when the masks are in a masks folder of their own: " - "OME-Zarr label images, and masks named _.tif beside their images, are found " - "without it." + "OME-Zarr label images are discovered automatically. External TIFF masks must be stored " + "in a separate masks folder: add --masks FOLDER to both commands, unless an earlier " + "preprocessing run already recorded it." ) @@ -57,11 +57,37 @@ def add_declare_masks_parser(commands: argparse._SubParsersAction) -> argparse.A """ declare = commands.add_parser( "declare-masks", - help="declare mask types (added after preprocessing) in the published description, " - "so run --masks accepts them", + help="declare mask types (existing masks, or masks added later) in the published " + "description, so preprocessing accepts them", + description="""\ +Declare each mask type before running preprocessing with those masks: right +after publishing the experiment description, or later for masks added to an +existing preprocessing run. Then run preprocessing, and check the mask pixels +with the masks command. + +Mask representations: + instances one positive label per object (for example a Cellpose mask) + binary foreground and background (a region) + parent_labels one label per group of objects""", + epilog="""\ +Examples: + morphobricks-preprocessing declare-masks \\ + --output my_experiment_MorphoBricks_Preprocessing \\ + --masks my_masks --type Cells=instances + morphobricks-preprocessing declare-masks \\ + --output my_experiment_MorphoBricks_Preprocessing \\ + --masks my_masks --type cp_masks=instances:Cells + +The second declares masks named like image_01_cp_masks.tif (the mask type as a +file-name ending) with the mask ID Cells. Do not declare and ignore the same +mask type.""", + formatter_class=argparse.RawDescriptionHelpFormatter, ) declare.add_argument( - "--output", metavar="FOLDER", required=True, help="the output folder of the run" + "--output", + metavar="FOLDER", + required=True, + help="the preprocessing output folder containing morphobricks.toml", ) declare.add_argument( "--type", @@ -69,23 +95,25 @@ def add_declare_masks_parser(commands: argparse._SubParsersAction) -> argparse.A action="append", default=[], metavar="TYPE=REPRESENTATION[:ID]", - help=f"a mask type (its folder name) and what it is: {', '.join(REPRESENTATIONS)}; " - "optionally its ID (default: the folder name). Repeatable", + help="mask type and representation: instances (one positive label per object), " + "binary (foreground and background) or parent_labels (one label per group of " + "objects); optionally a different mask ID after a colon. Example: Cells=instances " + f"(representations: {', '.join(REPRESENTATIONS)}; repeatable)", ) declare.add_argument( "--ignore", action="append", default=[], metavar="TYPE", - help="a mask type or OME-Zarr label image the runs do not use (repeatable): left out " - "of check and run instead of refused as undeclared; listed in ignored_masks.toml " - "beside morphobricks.toml and recorded by the run. Declaring a type with --type " - "takes it off the list", + help="skip a mask type you do not want to analyse: give its exact folder name, " + "file-name ending or OME-Zarr label name (repeatable). A declared type cannot be " + "ignored; declaring an ignored type with --type uses it again", ) declare.add_argument( "--masks", metavar="FOLDER", - help="the masks folder: each mask type is also checked against it", + help="external masks folder, used to check the mask-type names; the mask pixels are " + "checked later by the masks command", ) return declare @@ -127,8 +155,14 @@ def declare_masks_command(args: argparse.Namespace) -> int: args.output, args.ignore, declared=declared_types(args.output) ) except (ValueError, OutputLockedError, OSError) as exc: - kept = "the --ignore list was not changed" - return _refused(exc, f"{'The masks above were declared; ' if done else ''}{kept}.") + if done is not None and done.publication is not None: + saved = ( + f"Mask declarations saved to {done.publication.path}: {', '.join(done.added)}. " + "The ignore list was not updated. The saved declarations remain in place." + ) + else: + saved = "No mask declaration changed. The ignore list was not updated." + return _refused(exc, saved, ignore=True) if done is not None and done.publication is None: print("Every mask type is declared as asked already; nothing was written.") elif done is not None: @@ -143,10 +177,10 @@ def declare_masks_command(args: argparse.Namespace) -> int: return 0 -def _refused(exc: Exception, written: str) -> int: +def _refused(exc: Exception, written: str, *, ignore: bool = False) -> int: """Print a refusal with its codes and what was (not) written; return exit status 1.""" codes = f" ({', '.join(exc.codes)})" if getattr(exc, "codes", ()) else "" - print(f"Not declared{codes}: {exc}") + print(f"{'Mask settings not updated' if ignore else 'Not declared'}{codes}: {exc}") print(written[0].upper() + written[1:]) return 1 @@ -155,18 +189,20 @@ def next_commands(output: str, masks: str | None) -> list[str]: """Return the lines naming the commands that follow a declaration. ``masks`` is the masks folder given, or None: the masks may then be OME-Zarr label images - or masks beside the images, which ``run`` finds without ``--masks``, so no placeholder - folder is named. The experiment folder is named (``EXPERIMENT``) unless a run of the - output folder records it. + or a masks folder the run already records, which ``run`` finds without ``--masks``, so no + placeholder folder is named. The experiment folder is named (``EXPERIMENT``) unless a run + of the output folder records it, and the text then says to replace it. """ recorded, _ = recorded_experiment_root(Path(output).resolve()) target = ("" if recorded is not None else "EXPERIMENT ") + f"--output {shlex.quote(output)}" if masks is not None: option = f" --masks {shlex.quote(masks)}" - lines = ["Next, run preprocessing with the masks folder, then describe the masks:"] + lines = ["Next, run preprocessing with the masks folder, then check the masks:"] else: option = "" - lines = ["Next, run preprocessing again, then describe the masks:"] + lines = ["Next, run preprocessing again, then check the masks:"] + if recorded is None: + lines.append("Replace EXPERIMENT below with the folder containing your original images.") lines += [ f" morphobricks-preprocessing run {target}{option}", f" morphobricks-preprocessing masks {target}{option}", diff --git a/src/morphobricks_preprocessing/cli_describe.py b/src/morphobricks_preprocessing/cli_describe.py index f49ecfad..fd2e48ae 100644 --- a/src/morphobricks_preprocessing/cli_describe.py +++ b/src/morphobricks_preprocessing/cli_describe.py @@ -45,8 +45,10 @@ from __future__ import annotations import argparse +import shlex from pathlib import Path +from .cli_describe_options import add_describe_parser as add_describe_parser from .describe_ids import apply_ids from .describe_questions import fast_question_lines, proposal, question_blockers, question_lines from .description import Description, DescriptionError @@ -129,98 +131,18 @@ def _confirm_again(rec: Reconciliation) -> dict[str, tuple[str, ...]]: return {repeat: reasons for repeat, reasons in found.items() if reasons} -def add_describe_parser(commands: argparse._SubParsersAction) -> argparse.ArgumentParser: - """Add the ``describe`` command and its options; return its parser.""" - describe = commands.add_parser( - "describe", - help="show the draft experiment description (proposals, open questions) in plain " - "language; writes nothing, and confirms nothing", - ) - describe.add_argument("experiment", help="the experiment folder") - describe.add_argument( - "--output", - metavar="FOLDER", - help="output folder holding morphobricks.toml " - "(default: next to the experiment, _MorphoBricks_Preprocessing)", - ) - describe.add_argument( - "--exclude", - action="append", - default=[], - metavar="PATH", - help="image to leave out, relative to the experiment folder (repeatable)", - ) - describe.add_argument( - "--strict", - action="store_true", - help="describe in the strict per-unit mode: each acquisition's channels confirmed on " - "its own (in the notebook). Default: fast mode, one channel list for the experiment " - "(Spec ADR 0006)", - ) - _add_fast_options(describe) - describe.add_argument( - "--publish", - action="store_true", - help="publish the description only when no question is open and every decision is " - "confirmed; otherwise exit with status 1 and list what is missing. Nothing is " - "confirmed for you", - ) - return describe - +PREVIEW_NOTE = ( + "Preview only. No description has been saved. Your options are reflected above; the " + "channel list and the image headers are validated when you publish (--publish)." +) +"""Said after a preview of a new description (review P1.3).""" -def _add_fast_options(describe: argparse.ArgumentParser) -> None: - """Add the fast-mode statements of ``describe`` (Spec ADR 0006, :mod:`.fast_answers`).""" - describe.add_argument( - "--channels", - metavar="ID,ID,...", - help="fast mode: the channel IDs of the first acquisition in folder order (the tagged " - "unit, named in the output), in source order C0, C1, ...; its header names are " - "confirmed as their header names. Every acquisition is stated to have them", - ) - describe.add_argument( - "--image-type", - choices=("channels", "rgb"), - help="fast mode: the image type of the list (never inferred)", - ) - describe.add_argument( - "--accept-ids", action="store_true", help="fast mode: accept every proposed ID" - ) - describe.add_argument( - "--id", - action="append", - default=[], - metavar="FOLDER=ID", - help="fast mode: the ID of a condition, biological-repeat or technical-repeat folder, " - "as you type it (repeatable), for example --id control=ctrl for a folder whose name " - "cannot be an ID; checked with the notebook's rules. A label used at two levels takes " - "the level: condition:FOLDER, repeat:FOLDER or technical:FOLDER", - ) - describe.add_argument( - "--comparable", - action="store_true", - help="fast mode: every biological repeat's folders were prepared and acquired under " - "the same circumstances (your answer, dated --confirmed-on)", - ) - describe.add_argument( - "--confirmed-on", - metavar="YYYY-MM-DD", - help="fast mode: the day of your statements (never read from the clock)", - ) - describe.add_argument( - "--rgb-header-override", - action="append", - nargs="?", - const=True, - default=[], - metavar="FOLDER", - help="fast mode, with --image-type rgb (give the experiment folder before this " - "option, or it is taken as FOLDER): the images of this acquisition folder (relative " - "to the experiment, for example CTRL/rep1; repeatable; without a folder: every " - "acquisition) store R, G and B as three interleaved samples per pixel although their " - "TIFF header does not say colour. Records rgb_header_override = true on those units, " - "as the notebook's Image type card does; an image that is not three interleaved " - "samples is still refused", - ) +PUBLISHED_NOTE = ( + "This experiment already has a published description. The command displays it but does " + "not change its channel list or experimental design. To edit it, open the existing " + "description in the notebook and use Check and save." +) +"""Said whenever describe shows an existing description (review P1.4).""" def describe_command(args: argparse.Namespace) -> int: @@ -261,13 +183,20 @@ def describe_command(args: argparse.Namespace) -> int: print(OVERRIDE_NEEDS_CHANNELS if new_fast else OVERRIDE_ONLY_FAST) return 1 print("\n".join(lines)) + if found is not None: + print() + print(PUBLISHED_NOTE) if not args.publish: + if found is None: + print() + print(PREVIEW_NOTE) return 0 print() if not blockers and any(line.startswith(" headers changed:") for line in lines): print( - "Nothing to publish: no answer is missing. The run stops until the image headers " - "fit the published description (headers changed, above)." + "The published description no longer matches the image headers. It was not " + "changed. Correct the channel names or order in the notebook, save the " + "description, then run preprocessing again." ) return 0 if not blockers: @@ -332,6 +261,8 @@ def describe_fast( ] print("\n".join(lines)) if not args.publish: + print() + print(PREVIEW_NOTE) return 0 print() channels = [c for c in (args.channels or "").split(",") if c] @@ -362,7 +293,10 @@ def describe_fast( print("Not published: some images cannot be checked against the channel list.") print(format_issues(refused)) return 1 - return _publish_fast(draft, answers, discovery, headers, output) + if not _publish_fast(draft, answers, discovery, headers, output): + return 1 + print("\n".join(next_steps(args, excluded))) + return 0 def override_units( @@ -409,25 +343,41 @@ def _image_units(discovery: DiscoveryResult) -> dict[str, tuple[str, str, str]]: return {image: leaf.labels for leaf in discovery.leaves for image in leaf.images} +def next_steps(args: argparse.Namespace, excluded: list[str]) -> list[str]: + """Return the check and run commands after a publication (review P1.2), paths quoted. + + The experiment folder is the one given; ``--output`` and ``--exclude`` are kept when given. + """ + options = f" --output {shlex.quote(args.output)}" if args.output else "" + options += "".join(f" --exclude {shlex.quote(path)}" for path in excluded) + experiment = shlex.quote(args.experiment) + return [ + "Next, check the experiment and run preprocessing:", + f" morphobricks-preprocessing check {experiment}{options}", + f" morphobricks-preprocessing run {experiment}{options}", + "If check suggests an --axes value, review it and give it to run.", + ] + + def _publish_fast( draft: Draft, answers: DraftAnswers, discovery: DiscoveryResult, headers: list, output: Path, -) -> int: - """Check every image against the list, then publish; nothing is written on any refusal.""" +) -> bool: + """Check every image against the list, then publish; False (nothing written) on a refusal.""" try: candidate = description_from_draft(draft, answers) except DraftError as exc: print(f"Not published: {exc}") - return 1 + return False report = check_physical(candidate, discovery, headers) if report.issues: print(format_issues(physical_issues(report.issues))) if any(issue.override_fits for issue in report.issues): print(OVERRIDE_CLI) - return 1 + return False if report.unchecked: # every image's count and type checked, never a guessed count print( "Not published: these images could not be checked against the channel list (their " @@ -435,7 +385,7 @@ def _publish_fast( "example with the notebook or convert, and describe again):" ) print("\n".join(f" - {path}" for path in report.unchecked)) - return 1 + return False output.mkdir(parents=True, exist_ok=True) try: publication = publish_description( @@ -443,12 +393,13 @@ def _publish_fast( ) except (PublicationRefused, DescriptionError, ValueError) as exc: print(f"Not published: {exc}") - return 1 + return False print( - f"Published {publication.path} in fast mode (channel list " - f"{list(candidate.channel_layout.channels)})." + f"Experiment description saved to {publication.path}. Channels, in their stored " + f"order: {', '.join(candidate.channel_layout.channels)}. The channel list agrees " + "with the image headers checked during publication." ) - return 0 + return True def draft_lines(draft: Draft, root: Path, *, questions: bool = True) -> list[str]: diff --git a/src/morphobricks_preprocessing/cli_describe_options.py b/src/morphobricks_preprocessing/cli_describe_options.py new file mode 100644 index 00000000..b04ed175 --- /dev/null +++ b/src/morphobricks_preprocessing/cli_describe_options.py @@ -0,0 +1,127 @@ +"""The ``describe`` command's options: its parser, help texts and fast-mode options. + +Moved from :mod:`.cli_describe` (which re-exports :func:`add_describe_parser`) to keep that +module within the line limit. What the options mean is in :mod:`.cli_describe`. +""" + +from __future__ import annotations + +import argparse + +__all__ = ["add_describe_parser"] + + +def add_describe_parser(commands: argparse._SubParsersAction) -> argparse.ArgumentParser: + """Add the ``describe`` command and its options; return its parser.""" + describe = commands.add_parser( + "describe", + help="preview an experiment description or publish it with --publish", + description="""\ +Preview an experiment description: the proposed IDs of conditions and repeats, +and the questions still open. With --publish and the options below, validate +and save it (morphobricks.toml in the output folder); every check, run and masks +command needs a published description. + +Fast publication from the command line creates a new description for an +experiment with one shared channel list. Use the notebook to edit an existing +description, change repeat pairing or describe acquisitions with different +channel lists or orders.""", + epilog="""\ +Example (two fluorescence channels stored in the order collagen, fibronectin): + morphobricks-preprocessing describe my_experiment + morphobricks-preprocessing describe my_experiment \\ + --channels COL,FN --image-type channels \\ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish + +Review the proposed IDs before accepting them. Give --comparable only if it is +true. Then check and run preprocessing.""", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + describe.add_argument( + "experiment", + help="folder containing your original experiment images, organised by condition and repeat", + ) + describe.add_argument( + "--output", + metavar="FOLDER", + help="folder that holds (or will hold) the published description, morphobricks.toml " + "(default: EXPERIMENT_MorphoBricks_Preprocessing beside the images folder)", + ) + describe.add_argument( + "--exclude", + action="append", + default=[], + metavar="PATH", + help="image to leave out, relative to the experiment folder (repeatable)", + ) + describe.add_argument( + "--strict", + action="store_true", + help="use separate channel descriptions for each acquisition; complete and publish " + "them in the notebook. By default, one channel list is used for the whole experiment", + ) + _add_fast_options(describe) + describe.add_argument( + "--publish", + action="store_true", + help="validate and save the description; without --publish, show a preview only. " + "When a question is still open, exit with status 1 and list it", + ) + return describe + + +def _add_fast_options(describe: argparse.ArgumentParser) -> None: + """Add the fast-mode statements of ``describe`` (Spec ADR 0006, :mod:`.fast_answers`).""" + describe.add_argument( + "--channels", + metavar="ID,ID,...", + help="channel names separated by commas, in the order stored in the images (C0, C1, " + "...), for example COL,FN; give it only when all acquisitions have the same channels " + "in the same order", + ) + describe.add_argument( + "--image-type", + choices=("channels", "rgb"), + help="channels: separate stains or markers, such as fluorescence; rgb: red, green " + "and blue colour images (use --channels R,G,B). Never inferred", + ) + describe.add_argument( + "--accept-ids", + action="store_true", + help="accept the proposed identifiers of conditions and repeats; review them with " + "describe first, and give --id for folders without a valid proposed ID", + ) + describe.add_argument( + "--id", + action="append", + default=[], + metavar="FOLDER=ID", + help="assign a folder an identifier without renaming it, for example " + "--id control=ctrl (repeatable). If a name occurs at more than one folder level, " + "write condition:NAME=ID, repeat:NAME=ID or technical:NAME=ID", + ) + describe.add_argument( + "--comparable", + action="store_true", + help="confirm that the samples of each biological repeat were prepared and acquired " + "under comparable conditions; give this option only if that statement is true", + ) + describe.add_argument( + "--confirmed-on", + metavar="YYYY-MM-DD", + help="the date on which you confirm the description, written YYYY-MM-DD", + ) + describe.add_argument( + "--rgb-header-override", + action="append", + nargs="?", + const=True, + default=[], + metavar="FOLDER", + help="with --image-type rgb: use only for images known to store red, green and " + "blue as three interleaved samples per pixel although their TIFF headers do not say " + "RGB. Without a folder, applies to all acquisitions; otherwise give an acquisition " + "folder relative to the experiment, for example CTRL/rep1 (repeatable). Place the " + "experiment folder before this option. An image that is not three interleaved " + "samples is still refused", + ) diff --git a/src/morphobricks_preprocessing/cli_masks.py b/src/morphobricks_preprocessing/cli_masks.py index ccfcb7b7..43608b88 100644 --- a/src/morphobricks_preprocessing/cli_masks.py +++ b/src/morphobricks_preprocessing/cli_masks.py @@ -21,14 +21,15 @@ from .mask_scan import DEFAULT_THRESHOLDS, mask_thresholds from .mask_text import mask_report_summary, mask_summary from .report import format_issues -from .run.mask_step import describe_masks, prepare_mask_step +from .run.mask_step import MaskStepResult, describe_masks, prepare_mask_step from .validation import has_errors THRESHOLD_HELP = { "inside_pixel_share": "share of a child's pixels in one parent for it to be inside", "inside_object_share": "share of the children inside for a mask to be inside another", "parent_larger_share": "share of the inside children whose parent is larger", - "same_objects_iou": "intersection over union for two objects to match one to one", + "same_objects_iou": "minimum overlap of two objects, divided by their combined area, for " + "them to count as a match", "same_objects_share": "share of the objects of both masks matched for the same objects", "grouped_label_share": "share of a grouped mask's pixels carrying the parent's label", "grouped_median_pieces": "median pieces per label above which a mask is grouped", @@ -56,7 +57,9 @@ def add_masks_arguments(masks: argparse.ArgumentParser) -> None: "each mask whole twice more; default: as in the earlier run, else no)", ) limits = masks.add_argument_group( - "relationship thresholds", "change the defaults (contract §15.1); shares are 0 to 1" + "relationship thresholds", + "optional thresholds for identifying mask relationships; fractions range from 0 to 1 " + "(0.8 means 80 percent)", ) for name, text in THRESHOLD_HELP.items(): limits.add_argument( @@ -96,7 +99,10 @@ def masks_command(args: argparse.Namespace) -> int: if has_errors(step.issues): return 1 if not step.masks.types: - print("Give the masks folder with --masks, or use OME-Zarr images with label images.") + print( + "No masks were found. If you have external masks, give their folder with --masks. " + "If you do not intend to analyse masks, skip this command." + ) return 1 def progress(done: int, total: int, path: str) -> None: @@ -118,11 +124,26 @@ def progress(done: int, total: int, path: str) -> None: if result.report is None: # the description is gone or unreadable: nothing read (#418) print(format_issues(result.issues)) return 1 + return _report(result) + + +def _report(result: MaskStepResult) -> int: + """Print the mask report, its issues and the closing line; return the exit status.""" print() print(mask_report_summary(result.report)) - print() - print(f"Report written to {result.path}") if result.issues: print() print(format_issues(result.issues)) - return 1 if has_errors(result.issues) else 0 + print() + if has_errors(result.issues): + print( + f"Mask check failed. A report was saved to {result.path}, but some masks did not " + "pass validation. Correct the errors above and repeat the mask check before using " + "those masks." + ) + return 1 + print( + f"Mask check completed. Relationships saved to {result.path}. The checked masks can " + "now be used in the next MorphoBricks analysis." + ) + return 0 diff --git a/src/morphobricks_preprocessing/cli_run.py b/src/morphobricks_preprocessing/cli_run.py index 16b2bff1..eaa65577 100644 --- a/src/morphobricks_preprocessing/cli_run.py +++ b/src/morphobricks_preprocessing/cli_run.py @@ -9,28 +9,28 @@ uses the recorded experiment folder (``experiment_not_recorded`` without one). ``--lab-links FILE`` gives lab-tool links, recorded in the run manifest only (never taken over by a later run), and ``--confirm-repeat-codes`` confirms their repeat codes (:mod:`.lab_links`). -Also the helpers every command shares: :func:`parse_size` and :func:`command_preflight`. +Also the helper every command shares, :func:`command_preflight`; :func:`parse_size` is in +:mod:`.cli_run_options` (re-exported here). """ from __future__ import annotations import argparse -import re +import shlex from dataclasses import replace -from fractions import Fraction from pathlib import Path from typing import Literal from morphobricks_normalization.checks import IntensityCheckSettings from morphobricks_normalization.ranges import ( - DEFAULT_ROBUST_QUANTILES, - HISTOGRAM_RANGES, HistogramSettings, ) from .axes import AxisMapping, reference_axes from .axis_review import review_axes from .channel_identity import channel_identity_text +from .cli_run_options import INTENSITY_HELP, add_run_settings +from .cli_run_options import parse_size as parse_size from .discovery import default_output_folder from .image_type import IMAGE_TYPES, RGB, ImageTypeReview, review_image_type from .intensity import intensity_text @@ -38,7 +38,6 @@ from .lab_links_file import read_lab_links from .manifest import RunManifest from .metadata import header_axes -from .planes import DEFAULT_MEMORY_LIMIT from .report import ( axis_check_summary, format_issues, @@ -52,60 +51,6 @@ from .run.reuse import read_previous, recorded_experiment_root from .validation import ValidationIssue, error -_UNITS = { - "": 1, - "B": 1, - "KIB": 2**10, - "MIB": 2**20, - "GIB": 2**30, - "KB": 10**3, - "MB": 10**6, - "GB": 10**9, -} - - -def parse_size(text: str) -> int: - """Parse a memory size such as ``"1GiB"``, ``"1.5 GiB"`` or ``"1073741824"``. - - The size must be an exact whole number of bytes above 0, computed without rounding - (``"1.5GiB"`` is 1610612736 bytes; ``"1.5"`` and ``"0.5B"`` are refused, issue #80). - ``argparse`` calls it while reading the command line, so a refused size stops the - command before anything is read. - - Raises - ------ - argparse.ArgumentTypeError - If the text is not a whole positive number of bytes. - """ - match = re.fullmatch(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([A-Za-z]*)\s*", text, flags=re.ASCII) - unit = match.group(2).upper() if match else None - if not match or unit not in _UNITS: - raise argparse.ArgumentTypeError( - f"{text!r} is not a memory size; use for example 1GiB, 512MiB or a number of bytes." - ) - size = Fraction(match.group(1)) * _UNITS[unit] - if size.denominator != 1 or size <= 0: - raise argparse.ArgumentTypeError( - f"{text!r} is not a whole number of bytes above 0; use for example 1GiB, 512MiB " - "or a whole number of bytes." - ) - return int(size) - - -def parse_workers(text: str) -> int | str: - """Parse ``--workers``: a whole number of at least 1, or ``auto`` (issue #107). - - Raises - ------ - argparse.ArgumentTypeError - For any other text. - """ - if text == "auto": - return text - if not re.fullmatch(r"[0-9]+", text, flags=re.ASCII) or int(text) < 1: - raise argparse.ArgumentTypeError(f"{text!r} is not a whole number of at least 1 or auto.") - return int(text) - def command_preflight(args: argparse.Namespace) -> Preflight: """Run :func:`preflight` with the options every command shares.""" @@ -162,8 +107,9 @@ def add_missing_as_singleton(parser: argparse.ArgumentParser) -> None: parser.add_argument( "--missing-as-singleton", action=argparse.BooleanOptionalAction, - help="confirm that images lacking some axes have one plane along them (default: as " - "in the earlier run, else no)", + help="confirm that an image without a particular dimension has size 1 along it " + "(default: as in the earlier run, else no). This does not enable analysis of " + "multi-slice Z-stacks", ) @@ -239,7 +185,7 @@ def add_run_arguments(run: argparse.ArgumentParser) -> None: The ``run`` command's parser. """ _run_inputs(run) - _run_settings(run) + add_run_settings(run) run.add_argument("--log", metavar="FILE", help="write technical details to this file") @@ -248,20 +194,24 @@ def _run_inputs(run: argparse.ArgumentParser) -> None: run.add_argument( "--axes", metavar="ROLES", - help="role of each axis of the images, in the order of their axes: X, Y, Z, C, T, or " - "- for none (for example ZCYX). 'check' prints the suggested value. Needed for the " - "first run unless every image names its axes, and again for plain stacks that are " - "new or changed", + help="roles of the stored dimensions, in their stored order: Y and X are image height " + "and width, C is channel, Z is depth, T is time, - an unused length-1 dimension (for " + "example CYX). 'check' prints the suggested value. Needed for the first run unless " + "every image names its axes, and again for plain stacks that are new or changed", ) run.add_argument( "--image-type", choices=IMAGE_TYPES, - help="fluorescence (each channel a separate stain) or rgb (colour images with " - "three channels); default: the earlier run's, else the type suggested from the " - "image headers, printed", + help="fluorescence (each channel a separate stain; the description calls it " + "channels) or rgb (colour images with three channels); default: the earlier run's, " + "else the type suggested from the image headers. The published description is the " + "record of what your channels are: correct it there, not with this option", ) run.add_argument( - "--no-masks", action="store_true", help="drop the masks folder of the earlier run" + "--no-masks", + action="store_true", + help="stop using the previously recorded external masks folder (does not delete mask " + "files)", ) run.add_argument( "--no-exclude", @@ -293,77 +243,11 @@ def _run_inputs(run: argparse.ArgumentParser) -> None: run.add_argument( "--verify-content", action=argparse.BooleanOptionalAction, - help="reuse rows only when each image's content SHA-256 is the one recorded with them, " - "not only its size and modification time (reads every image once more; changing it " - "recomputes every row; on by default: as in the earlier run, else yes; " - "--no-verify-content opts out and the manifest records that)", - ) - - -def _run_settings(run: argparse.ArgumentParser) -> None: - """Add the settings of ``run``; each one left out is the earlier run's, else the default.""" - run.add_argument("--bins", type=int, help="bins per plane (default: depends on pixel type)") - run.add_argument( - "--histogram-range", - choices=HISTOGRAM_RANGES, - help="range of histograms that are not exact (float images, and integer images with " - "more values than bins): minmax (default, each plane's minimum to maximum) or robust " - "(between the --robust-quantiles, the pixels outside counted separately); 8- and " - "16-bit histograms are the same either way", - ) - run.add_argument( - "--robust-quantiles", - type=float, - nargs=2, - metavar=("LOW", "HIGH"), - help="quantiles in percent of the robust range, also used by the range check " - f"(default {DEFAULT_ROBUST_QUANTILES[0]:g} {DEFAULT_ROBUST_QUANTILES[1]:g})", - ) - run.add_argument( - "--memory-limit", - type=parse_size, - default=DEFAULT_MEMORY_LIMIT, - metavar="SIZE", - help="working-memory limit per plane, e.g. 2GiB (default: 1GiB)", - ) - run.add_argument( - "--workers", - type=parse_workers, - default=1, - metavar="N|auto", - help="images read at once, each in its own thread (default 1: one after another); " - "auto: at most the CPUs and, with --max-ram, what the largest image's estimate fits. " - "The outputs are the same with any value", - ) - run.add_argument( - "--max-ram", - type=parse_size, - metavar="SIZE", - help="with --workers auto: memory the run may use, e.g. 8GiB (an image that does not " - "fit stops the run before any pixel is read)", + help="verify that each image's contents are unchanged before reusing its histogram " + "(on by default for a new run; as in the earlier run otherwise). This reads the image " + "files again but avoids recomputing unchanged histograms; changing it recomputes " + "every row. --no-verify-content opts out, and the run manifest records that", ) - checks = run.add_argument_group( - "intensity checks", "limits of the warnings printed after the run; the defaults suit most" - ) - for name, (kind, metavar, text) in _INTENSITY_HELP.items(): - checks.add_argument( - "--" + name.replace("_", "-"), dest=name, type=kind, metavar=metavar, help=text - ) - - -_INTENSITY_HELP = { - "outlier_limit": ( - float, - "N", - "robust deviations beyond which an image or biological repeat is reported (default 3)", - ), - "saturation_limit": ( - float, - "FRACTION", - "fraction of saturated pixels above which an image is reported (default 0.01, 1 %%)", - ), - "min_images": (int, "N", "fewest images a comparison needs (default 5)"), -} def run_command(args: argparse.Namespace) -> int: @@ -417,9 +301,34 @@ def run_command(args: argparse.Namespace) -> int: print(intensity_text(result.intensity)) if result.channel_identity is not None: print(f"\n{channel_identity_text(result.channel_identity)}") + if result.written: + print(f"\n{completed_text(result.output_folder)}") return 0 if result.written else 1 +def completed_text(output: Path) -> str: + """Return the hand-off of a run that wrote its outputs (review 7.1): which folder to give on. + + Parameters + ---------- + output + The run's output folder. + + Returns + ------- + str + """ + folder = shlex.quote(str(output)) + return "\n".join( + [ + f"Preprocessing completed. Review the warnings above. Use {output} as the input " + "folder for your next MorphoBricks analysis.", + "If your analysis uses masks, check their pixel values and relationships first:", + f" morphobricks-preprocessing masks --output {folder}", + ] + ) + + def lab_links_option(args: argparse.Namespace) -> LabLinks | None | Literal[False]: """Return the links of ``--lab-links``, None without it, or False after printing a refusal. @@ -530,7 +439,7 @@ def _settings_options( Each is None when none of its options is given (the run then uses the recorded one); None as a whole when a value is refused, which is printed. """ - intensity = {k: getattr(args, k) for k in _INTENSITY_HELP if getattr(args, k) is not None} + intensity = {k: getattr(args, k) for k in INTENSITY_HELP if getattr(args, k) is not None} histogram = { k: v for k, v in ( diff --git a/src/morphobricks_preprocessing/cli_run_options.py b/src/morphobricks_preprocessing/cli_run_options.py new file mode 100644 index 00000000..6dad77b7 --- /dev/null +++ b/src/morphobricks_preprocessing/cli_run_options.py @@ -0,0 +1,149 @@ +"""The ``run`` command's settings options and the size parsers the commands share. + +Moved from :mod:`.cli_run` to keep that module within the line limit: :func:`parse_size` +(memory sizes such as ``1GiB``), :func:`parse_workers` (``--workers``) and +:func:`add_run_settings` (the histogram, memory, worker and intensity-check options of ``run``). +""" + +from __future__ import annotations + +import argparse +import re +from fractions import Fraction + +from morphobricks_normalization.ranges import DEFAULT_ROBUST_QUANTILES, HISTOGRAM_RANGES + +from .planes import DEFAULT_MEMORY_LIMIT + +__all__ = ["INTENSITY_HELP", "add_run_settings", "parse_size", "parse_workers"] + +_UNITS = { + "": 1, + "B": 1, + "KIB": 2**10, + "MIB": 2**20, + "GIB": 2**30, + "KB": 10**3, + "MB": 10**6, + "GB": 10**9, +} + + +def parse_size(text: str) -> int: + """Parse a memory size such as ``"1GiB"``, ``"1.5 GiB"`` or ``"1073741824"``. + + The size must be an exact whole number of bytes above 0, computed without rounding + (``"1.5GiB"`` is 1610612736 bytes; ``"1.5"`` and ``"0.5B"`` are refused, issue #80). + ``argparse`` calls it while reading the command line, so a refused size stops the + command before anything is read. + + Raises + ------ + argparse.ArgumentTypeError + If the text is not a whole positive number of bytes. + """ + match = re.fullmatch(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([A-Za-z]*)\s*", text, flags=re.ASCII) + unit = match.group(2).upper() if match else None + if not match or unit not in _UNITS: + raise argparse.ArgumentTypeError( + f"{text!r} is not a memory size; use for example 1GiB, 512MiB or a number of bytes." + ) + size = Fraction(match.group(1)) * _UNITS[unit] + if size.denominator != 1 or size <= 0: + raise argparse.ArgumentTypeError( + f"{text!r} is not a whole number of bytes above 0; use for example 1GiB, 512MiB " + "or a whole number of bytes." + ) + return int(size) + + +def parse_workers(text: str) -> int | str: + """Parse ``--workers``: a whole number of at least 1, or ``auto`` (issue #107). + + Raises + ------ + argparse.ArgumentTypeError + For any other text. + """ + if text == "auto": + return text + if not re.fullmatch(r"[0-9]+", text, flags=re.ASCII) or int(text) < 1: + raise argparse.ArgumentTypeError(f"{text!r} is not a whole number of at least 1 or auto.") + return int(text) + + +def add_run_settings(run: argparse.ArgumentParser) -> None: + """Add the settings of ``run``; each one left out is the earlier run's, else the default. + + Parameters + ---------- + run + The ``run`` command's parser. + """ + run.add_argument( + "--bins", + type=int, + help="number of intensity-histogram bins for each channel of an image plane (default: " + "depends on the pixel type)", + ) + run.add_argument( + "--histogram-range", + choices=HISTOGRAM_RANGES, + help="range of histograms that are not exact (float images, and integer images with " + "more values than bins): minmax (default, each plane's minimum to maximum) or robust " + "(between the --robust-quantiles, the pixels outside counted separately); 8- and " + "16-bit histograms are the same either way", + ) + run.add_argument( + "--robust-quantiles", + type=float, + nargs=2, + metavar=("LOW", "HIGH"), + help="quantiles in percent of the robust range, also used by the range check " + f"(default {DEFAULT_ROBUST_QUANTILES[0]:g} {DEFAULT_ROBUST_QUANTILES[1]:g})", + ) + run.add_argument( + "--memory-limit", + type=parse_size, + default=DEFAULT_MEMORY_LIMIT, + metavar="SIZE", + help="working-memory limit per plane, e.g. 2GiB (default: 1GiB)", + ) + run.add_argument( + "--workers", + type=parse_workers, + default=1, + metavar="N|auto", + help="number of images processed in parallel (default 1: one after another); with " + "auto, chosen from the available CPUs and, with --max-ram, memory. Does not change " + "the scientific results", + ) + run.add_argument( + "--max-ram", + type=parse_size, + metavar="SIZE", + help="total memory budget, used only with --workers auto, for example --workers auto " + "--max-ram 8GiB (an image that does not fit stops the run before any pixel is read)", + ) + checks = run.add_argument_group( + "intensity checks", "limits of the warnings printed after the run; the defaults suit most" + ) + for name, (kind, metavar, text) in INTENSITY_HELP.items(): + checks.add_argument( + "--" + name.replace("_", "-"), dest=name, type=kind, metavar=metavar, help=text + ) + + +INTENSITY_HELP = { + "outlier_limit": ( + float, + "N", + "robust deviations beyond which an image or biological repeat is reported (default 3)", + ), + "saturation_limit": ( + float, + "FRACTION", + "fraction of saturated pixels above which an image is reported (default 0.01, 1 %%)", + ), + "min_images": (int, "N", "fewest images a comparison needs (default 5)"), +} diff --git a/src/morphobricks_preprocessing/cli_tissue_mask.py b/src/morphobricks_preprocessing/cli_tissue_mask.py index 6f5d3611..4f4b0b67 100644 --- a/src/morphobricks_preprocessing/cli_tissue_mask.py +++ b/src/morphobricks_preprocessing/cli_tissue_mask.py @@ -26,7 +26,7 @@ from .run_inputs_tissue import ( HE_TISSUE_V2, NOT_REUSED, - PROVISIONAL_NOTE, + provisional_note, rgb_positions, tissue_next_steps, ) @@ -49,25 +49,46 @@ def add_tissue_mask_parser(commands: argparse._SubParsersAction) -> argparse.Arg """ tissue = commands.add_parser( "tissue-mask", - help="write an H&E tissue mask (nuclei, red blood cells and empty space left out) of " - "each RGB image as a new binary region mask (needs the he-mask extra)", + help="create a binary H&E tissue mask for each 8-bit RGB image of a preprocessing run " + "(provisional rule; needs the he-mask extra)", + description="""\ +Create a binary region mask for each selected 8-bit RGB H&E image in a +completed preprocessing run. A provisional fixed rule attempts to exclude +nuclei, red blood cells and empty background. Inspect the masks before you use +them. + +Requires: + 8-bit RGB images (three colour channels), one depth plane and one time point + the he-mask installation extra""", + epilog="""\ +Example: + morphobricks-preprocessing tissue-mask \\ + --output he_MorphoBricks_Preprocessing --to HETissue + +Inspect the generated masks, then declare them as binary. The command prints +the next commands to run.""", + formatter_class=argparse.RawDescriptionHelpFormatter, ) tissue.add_argument( - "--output", metavar="FOLDER", required=True, help="the output folder of the run" + "--output", + metavar="FOLDER", + required=True, + help="the preprocessing output folder containing morphobricks.toml", ) tissue.add_argument( "--to", metavar="NEW_ID", required=True, - help="the new mask ID; declare it binary afterwards", + help="new, unused mask identifier, for example HETissue; declare it as binary after " + "checking the generated masks", ) tissue.add_argument( "--image", action="append", default=[], metavar="PATH", - help="only this image, relative to the experiment folder (repeatable; default: every " - "image of a unit declared rgb)", + help="create masks only for this image, relative to the experiment folder " + "(repeatable). By default, every RGB image; other images do not receive this mask", ) tissue.add_argument( "--masks", @@ -93,7 +114,10 @@ def tissue_mask_command(args: argparse.Namespace) -> int: return 1 images = tuple(args.image) or rgb_positions(run) if not images: - print("The run has no image of a unit declared rgb; nothing was written.") + print( + "No images in this preprocessing run are declared RGB; tissue-mask requires RGB " + "H&E images. Nothing was written." + ) return 1 if args.masks and run.masks_root is not None: print( @@ -101,17 +125,18 @@ def tissue_mask_command(args: argparse.Namespace) -> int: f"{run.masks_root}, where the tissue masks go. Nothing was written." ) return 1 - if run.masks_root is None: + created = run.masks_root is None + if created: try: run = create_masks_folder(run, args.masks).run except MasksFolderRefused as exc: print(f"No tissue mask written. {exc}") return 1 print( - f"The run had no masks folder: created {run.masks_root} and recorded it, as " - "run --masks does." + f"Masks folder created and registered: {run.masks_root}. The preprocessing run " + "now records this folder." ) - print(PROVISIONAL_NOTE) + print(provisional_note(args.rule)) written = [] for image in images: try: @@ -119,15 +144,20 @@ def tissue_mask_command(args: argparse.Namespace) -> int: # Every refusal: RunInputsError, a missing extra, and a plane that cannot be read (#469). except (ValueError, ImportError, PlaneReadError, OSError) as exc: print(_refusal(image, exc)) + if created: + print(f"The registered masks folder {run.masks_root} remains in place.") if written: - print(f"{plural(len(written), 'image')} before it stay written.") + print( + f"The masks of {plural(len(written), 'earlier image')} remain available. " + "Complete the required masks before declaring this mask type." + ) return 1 written.append(result) - state = "written" if result.published else "already written" + state = "saved" if result.published else "already saved" kept = 100 * result.fractions["kept"] - line = f"{image}: {result.path} ({state}), kept {kept:.1f} %" + line = f"{image}: mask {state} to {result.path}; retained area: {kept:.1f} % of the image" if kept == 0: - line += " (nothing kept: an empty region)" + line += " (empty region: no tissue pixels retained; inspect this image)" print(line if result.reusable else f"{line}; {NOT_REUSED}") print() ids = sorted({r.mask_id for r in written}) diff --git a/src/morphobricks_preprocessing/conversion_issues.py b/src/morphobricks_preprocessing/conversion_issues.py index 8146bf48..14eb7493 100644 --- a/src/morphobricks_preprocessing/conversion_issues.py +++ b/src/morphobricks_preprocessing/conversion_issues.py @@ -87,25 +87,18 @@ def work_folder_issue(dest: Path, name: str, all_nul: bool = False) -> Validatio """ if all_nul: cause = ( - "Its owner file is unreadable: it holds only NUL bytes, possibly left by a power " - "loss while a conversion wrote it, so it cannot be proven that a conversion made " - "this folder." + "'s ownership record is unreadable (it holds only NUL bytes, possibly left by a " + "power loss)" ) else: - cause = ( - "So it was not made by a conversion, or was changed since, and it cannot be " - "proven that a conversion made it." - ) + cause = " has an invalid or missing ownership record, or contains unexpected files" return error( "conversion_work_folder_unowned", - f"The folder for the named-axis copies holds {name}, the name of the folder a " - "conversion writes its copies in, but not as a conversion leaves it: the owner file a " - "conversion writes into it first is missing or not well formed, or it holds something " - f"else than that file and the folder 'files'. {cause} Nothing was removed and " - "nothing was written.", + f"The temporary conversion folder {dest / name}{cause}. The folder has not been " + "removed: it has been left untouched. Nothing was removed and nothing was written.", [name], - f"Check {dest / name}, then move or remove it yourself if you no longer need what it " - "holds, or choose a new, empty folder for the copies.", + "Use a new, empty folder for the copies (--to), or inspect the temporary folder before " + "moving it.", ) @@ -117,13 +110,12 @@ def work_folder_in_use_issue(dest: Path, name: str, holder: LockHolder) -> Valid """ return error( "conversion_work_folder_in_use", - f"The folder for the named-axis copies holds {name}, the work folder of a " - f"conversion by {holder.describe()}, which is still running on this computer, so it " - "may still be writing there (its lock was probably removed by mistake). Nothing was " - "removed and nothing was written.", + "A process associated with an earlier conversion is still running on this computer " + f"({holder.describe()}). The temporary folder {dest / name} has been left untouched. " + "Nothing was removed and nothing was written.", [name], - "Wait for that conversion to finish, then convert again. If that process is not a " - f"conversion (process IDs are reused), move or remove {dest / name} yourself.", + "Wait for the conversion to finish, or use another destination. If that process is not " + "a conversion (process IDs are reused), inspect the temporary folder before moving it.", ) @@ -131,13 +123,11 @@ def work_folder_not_removed_issue(dest: Path, name: str, exc: OSError) -> Valida """Refuse a conversion whose leftover work folder ``name`` cannot be removed (#488).""" return error( "conversion_work_folder_not_removed", - f"The folder for the named-axis copies holds {name}, the work folder of a conversion " - f"that was stopped, and it cannot be removed ({exc}): a file in it may be open in " - "another program, such as an antivirus or a sync client (OneDrive, Dropbox). Part of " - "it may have been removed. Nothing was written.", + f"The temporary conversion folder {dest / name}, left by a stopped conversion, could " + f"not be removed: {exc}. Part of it may have been removed; nothing was written.", [name], - "Close the programs that may use it, or wait for them to finish, then convert again " - f"(the conversion removes it). Or remove {dest / name} yourself.", + f"Close programs using {dest / name} (such as an antivirus or a sync client like " + "OneDrive) and retry, or choose another empty destination.", ) @@ -154,13 +144,12 @@ def path_too_long_issue( ) return error( "copy_path_too_long", - f"{plural(len(paths), 'copy', 'copies')} would have {what} while it is written in the " - f"conversion's work folder in {dest}, and Windows cannot handle such paths without " - "long paths enabled. Nothing was written.", + f"The converted files would exceed Windows' path-length limit: " + f"{plural(len(paths), 'copy', 'copies')} would have {what} in the conversion's work " + f"folder in {dest}. Nothing was written.", paths, - "Choose a folder for the copies with a shorter path (for example near the top of the " - "drive), or shorten the names of these images or of their folders, or ask your " - "administrator to enable Windows' long paths (LongPathsEnabled).", + "Choose a destination with a shorter path, shorten the named folders or ask your " + "administrator to enable long paths.", ) diff --git a/src/morphobricks_preprocessing/describe_ids.py b/src/morphobricks_preprocessing/describe_ids.py index 8456a1ba..4475c13c 100644 --- a/src/morphobricks_preprocessing/describe_ids.py +++ b/src/morphobricks_preprocessing/describe_ids.py @@ -14,10 +14,12 @@ from __future__ import annotations -from collections.abc import Sequence +import shlex +import unicodedata +from collections.abc import Collection, Iterable, Sequence from .draft import Draft, DraftError -from .draft_ids import IdKind +from .draft_ids import IdKind, id_problems LEVELS: dict[str, IdKind] = { "condition": "conditions", @@ -32,9 +34,74 @@ } -def id_option(folder: str, value: str = "") -> str: - """Return the ``--id`` option that names ``folder``'s ID (```` as a placeholder).""" - return f"--id {folder}={value}" +_RESERVED = "This name is reserved. Choose another identifier." +_USED = "This identifier has already been used for another entry. Choose an unused identifier." +REASONS: dict[str, str] = { + "E_FORBIDDEN_FIELD": _RESERVED, + "E_ID_RESERVED": _RESERVED, + "E_ID_SYNTAX": ( + "This identifier contains characters that are not permitted. Choose a valid identifier." + ), + "E_ID_TEXT": ( + "This identifier is empty, starts or ends with a space, or reads as a missing value " + "(such as NA or none). Choose a valid identifier." + ), + "E_ID_NOT_NFC": ( + "This identifier contains accented characters in a form that is not permitted (not " + "Unicode NFC). Type it again, or choose another identifier." + ), + "E_SINGLE_MISUSE": ( + "'single' is kept, in lower case, for a level without its own folder. Choose another " + "identifier." + ), + "E_ID_CASE_COLLISION": ( + "This identifier differs from another identifier only in upper/lower case. Choose a " + "distinct identifier." + ), + "R_USED_ID_REUSED": _USED, + "id_in_use_in_draft": _USED, + "in_use": _USED, +} +"""Why an ID is refused, in words, by the code the ID rules give (``id_problems``, the draft).""" + + +def reasons(codes: Iterable[str]) -> str: + """Say why an ID is refused, each reason once, then the codes in brackets.""" + codes = tuple(dict.fromkeys(codes)) or ("in_use",) + said = dict.fromkeys(REASONS.get(code, "This identifier is not permitted.") for code in codes) + shown = ", ".join(code for code in codes if code != "in_use") + text = " ".join(said) + return f"{text[:-1]} ({shown})." if shown else text + + +def example_id(kind: IdKind, folder: str, used: Collection[str] = ()) -> str: + """Return an allowed ID to show for ``folder``: ``ctrl`` for ``control``, else from its name.""" + if folder == "control": + return "ctrl" + base = unicodedata.normalize("NFC", folder.strip()) or "Group" + for candidate in (base, f"{base}_1", f"{base}_2", "Group1"): + if not id_problems(kind, candidate, used): + return candidate + return "Group1" + + +def id_option(folder: str, value: str) -> str: + """Return the ``--id`` option that names ``folder``'s ID, quoted for the shell where needed.""" + return f"--id {shlex.quote(f'{folder}={value}')}" + + +def needs_id(kind: IdKind, folder: str, used: Collection[str] = ()) -> str: + """Say why ``folder`` has no proposed ID and which ``--id`` names one (a concrete example).""" + codes = id_problems(kind, folder, used) + noun, option = NOUNS[kind], id_option(folder, example_id(kind, folder, used)) + if {"E_FORBIDDEN_FIELD", "E_ID_RESERVED"} & set(codes): + why = f" because {folder!r} is reserved ({', '.join(codes)})." + else: + why = f". {reasons(codes)}" + return ( + f"The {noun} {folder!r} needs another identifier{why} Keep the folder name and add " + f"{option} (or type the ID in the notebook)." + ) def _keys(draft: Draft, kind: IdKind) -> Sequence[str]: @@ -79,7 +146,10 @@ def apply_ids(draft: Draft, given: Sequence[str]) -> tuple[Draft, list[str]]: if len(found) > 1: prefixes = [p for p, kind in LEVELS.items() if (kind, folder) in found] levels = " or ".join(id_option(f"{p}:{folder}", value) for p in prefixes) - refusals.append(f"--id {item}: {folder!r} names folders of two levels: give {levels}") + refusals.append( + f"--id {item}: the name {folder!r} occurs at more than one folder level. " + f"Specify which level you mean: {levels}." + ) continue key = found[0] if key in seen: @@ -89,11 +159,12 @@ def apply_ids(draft: Draft, given: Sequence[str]) -> tuple[Draft, list[str]]: try: draft = draft.confirm_id(key[0], key[1], value) except DraftError as exc: + example = example_id(key[0], key[1], draft.used_ids.get(key[0], ())) refusals.append( - f"--id {item}: {value!r} cannot be the ID of {NOUNS[key[0]]} {key[1]} " - f"({', '.join(exc.codes) or exc}); give an allowed ID: {id_option(folder)}" + f"--id {item}: {value!r} cannot be the ID of {NOUNS[key[0]]} {key[1]!r}. " + f"{reasons(exc.codes)} For example: {id_option(folder, example)}" ) return draft, refusals -__all__ = ["LEVELS", "apply_ids", "id_option"] +__all__ = ["LEVELS", "REASONS", "apply_ids", "example_id", "id_option", "needs_id", "reasons"] diff --git a/src/morphobricks_preprocessing/describe_questions.py b/src/morphobricks_preprocessing/describe_questions.py index 71452e9c..dd6e131b 100644 --- a/src/morphobricks_preprocessing/describe_questions.py +++ b/src/morphobricks_preprocessing/describe_questions.py @@ -8,16 +8,17 @@ from __future__ import annotations -from .describe_ids import id_option +from .describe_ids import needs_id from .draft import Draft, OpenQuestion -from .draft_ids import IdKind, id_problems +from .draft_ids import IdKind from .validation import plural QUESTION_TEXT = { "id_pending": "choose the ID of {subject} (accept the proposal or type another)", "repeat_not_confirmed": ( - "confirm that the folders of {subject} were prepared and acquired under the same " - "circumstances, so they are comparable" + "confirm, only if it is true, that the samples of {subject} were prepared and acquired " + "comparably; otherwise review the experimental grouping in the notebook. Do not confirm " + "an incorrect experimental design" ), "confirmed_on_missing": "{subject} is confirmed but has no date: confirm it again", } @@ -30,8 +31,7 @@ def proposal(kind: IdKind, folder: str, proposed: str | None, named: str | None return f"ID {named!r} (yours, --id)" if proposed is not None: return f"proposed ID {proposed!r}" - why = ", ".join(id_problems(kind, folder)) - return f"no ID can be proposed ({why or 'in use'}): you name it ({id_option(folder)})" + return f"no ID proposed. {needs_id(kind, folder)}" def unproposed(draft: Draft) -> dict[str, tuple[IdKind, str]]: @@ -54,11 +54,7 @@ def unproposed(draft: Draft) -> dict[str, tuple[IdKind, str]]: def _text(q: OpenQuestion, named_by: dict[str, tuple[IdKind, str]]) -> str: """Return one open question in words; an unproposable ID names its ``--id`` option.""" if q.code == "id_pending" and q.subject in named_by: - kind, label = named_by[q.subject] - why = ", ".join(id_problems(kind, label)) or "in use" - return ( - f"name the ID of {q.subject}: {label!r} cannot be one ({why}); give {id_option(label)}" - ) + return needs_id(*named_by[q.subject]) return QUESTION_TEXT[q.code].format(subject=q.subject) diff --git a/src/morphobricks_preprocessing/description_run_text.py b/src/morphobricks_preprocessing/description_run_text.py index 38458e93..b6d19334 100644 --- a/src/morphobricks_preprocessing/description_run_text.py +++ b/src/morphobricks_preprocessing/description_run_text.py @@ -10,6 +10,7 @@ import shlex from collections.abc import Iterable +from pathlib import PurePath from .channel_plan import channel_coverage, partial_repeats from .description import Description @@ -21,7 +22,6 @@ from .description_report import DescriptionIssue from .description_rules import Code from .fast_layout import FAST_LAYOUT_CONTRADICTION, contradiction_message -from .fast_layout import FIX as FAST_FIX from .physical_check import ( CHANNEL_COUNT_MISMATCH, HEADER_CONTRADICTION, @@ -44,17 +44,43 @@ _ACTIONS = { UNIT_NOT_FOUND: "Remove that acquisition from the description or restore its folder.", UNIT_NOT_DECLARED: "Add the acquisition to the description, or exclude its images.", - MASK_TYPE_NOT_DECLARED: ( - "Declare the mask type in the description (the notebook's describe steps, or " - "morphobricks-preprocessing declare-masks --output FOLDER --type " - "TYPE=REPRESENTATION, where REPRESENTATION is what the mask is: instances, binary or " - "parent_labels); or, if the run does not use it (an OME-Zarr label image of another " - "tool, for example), skip it: declare-masks --output FOLDER --ignore TYPE; or remove " - "its files." - ), } +_DECLARE = ( + "If every object has its own positive label, declare it as instance labels{where}:\n" + " morphobricks-preprocessing declare-masks --output {output} --type {instances}\n" + "To skip this mask type instead:\n" + " morphobricks-preprocessing declare-masks --output {output} --ignore {name}\n" + "For a foreground/background mask, use {binary} instead. For labels grouping several " + "objects, use {parent}. Then run preprocessing again." +) +"""The undeclared mask type's fix: each representation with what it means, none guessed.""" + + +def declare_action(mask_type: str, output_folder: str | PurePath | None = None) -> str: + """Return how to declare or skip an undeclared mask type, its name and folder quoted.""" + where = "" + if output_folder is None: + where, output = " (replacing OUTPUT with your output folder)", "OUTPUT" + else: + output = shlex.quote(str(output_folder)) + return _DECLARE.format( + where=where, + output=output, + instances=shlex.quote(f"{mask_type}=instances"), + name=shlex.quote(mask_type), + binary=shlex.quote(f"{mask_type}=binary"), + parent=shlex.quote(f"{mask_type}=parent_labels"), + ) +FAST_ACTION = ( + "Review the channel order in the acquisitions listed above. Tag acquisitions separately in " + 'the notebook where their channel lists differ (channels_from = "unit"), save the ' + "description and run again." +) +"""The fix of ``R_FAST_LAYOUT_CONTRADICTION`` (experiment-v1 section 8 names it: tag those units +on their own, ``channels_from = "unit"``); the message lists every image and its unit once.""" + OVERRIDE_FIX = ( "Images that store R, G and B as three interleaved samples under a header that does not " "say colour need no own tags: declare the RGB header override on their acquisitions " @@ -82,8 +108,8 @@ def _what(issue: PhysicalIssue) -> str: return f"The experiment has images in {where}, which the description does not list." if issue.code == MASK_TYPE_NOT_DECLARED: return ( - f"Masks of type {issue.detail!r} were found (in the masks folder, beside the " - "images or as OME-Zarr label images), but are not declared in the description." + f"The mask type {issue.detail!r} was found but has not been declared. Choose how " + "its pixel values should be interpreted." ) reasons = { UNIT_NOT_HOMOGENEOUS: "Images of one acquisition differ in their layout", @@ -99,14 +125,18 @@ def _what(issue: PhysicalIssue) -> str: return f"{reasons[issue.code]} in {where}{image}: {issue.detail}." -def physical_issue(issue: PhysicalIssue) -> ValidationIssue: - """Return one physical check refusal as an error naming its code, unit and image.""" +def physical_issue( + issue: PhysicalIssue, output_folder: str | PurePath | None = None +) -> ValidationIssue: + """Return one physical check refusal as an error naming its code, unit and image. + + ``output_folder``, when known, is named in an undeclared mask type's commands; without it + they say OUTPUT and what to replace it with. + """ paths = () if issue.path is None else (issue.path,) action = _ACTIONS.get(issue.code, FIX) if issue.code == MASK_TYPE_NOT_DECLARED: # the type found, never a guessed representation - typed = shlex.quote(f"{issue.detail}=REPRESENTATION") - action = action.replace("TYPE=REPRESENTATION", typed) - action = action.replace("--ignore TYPE", f"--ignore {shlex.quote(issue.detail)}") + action = declare_action(issue.detail, output_folder) return error(issue.code, _what(issue), paths, action) @@ -115,15 +145,14 @@ def fast_layout_issue(issues: Iterable[PhysicalIssue]) -> ValidationIssue: Every image of every fast unit is listed once, with its FOV key, path and every contradiction found in it (kind, C index, expected and found), and the action names the - one fix: tag those units on their own, then run again. + one fix: tag those acquisitions separately in the notebook, then run again. """ listed = { (fov_text(issue), issue.path): issue.contradictions for issue in issues if issue.code == FAST_LAYOUT_CONTRADICTION } - units = sorted({unit_text(i.unit) for i in issues if i.code == FAST_LAYOUT_CONTRADICTION}) - action = f"{FAST_FIX} Units: " + "; ".join(units) + "." + action = FAST_ACTION if any(i.override_fits for i in issues if i.code == FAST_LAYOUT_CONTRADICTION): action += f" {OVERRIDE_FIX}" paths = [path for _, path in listed] @@ -136,29 +165,71 @@ def fov_text(issue: PhysicalIssue) -> str: return f"{unit.condition}/{unit.biological_repeat}/{unit.technical_repeat}/{issue.fov}" -def physical_issues(issues: Iterable[PhysicalIssue]) -> list[ValidationIssue]: +def physical_issues( + issues: Iterable[PhysicalIssue], output_folder: str | PurePath | None = None +) -> list[ValidationIssue]: """Return the physical refusals, every fast-mode contradiction as one issue (ADR 0006). One publication or run carries ``R_FAST_LAYOUT_CONTRADICTION`` at most once, with all images, beside every other applicable code (AQ2); the others are one issue each. + ``output_folder`` is as in :func:`physical_issue`. """ issues = list(issues) - out = [physical_issue(i) for i in issues if i.code != FAST_LAYOUT_CONTRADICTION] + out = [physical_issue(i, output_folder) for i in issues if i.code != FAST_LAYOUT_CONTRADICTION] if any(i.code == FAST_LAYOUT_CONTRADICTION for i in issues): out.append(fast_layout_issue(issues)) return out +_MEANINGS = { + "E_FILE_ENCODING": "is not saved as UTF-8 text", + "E_TOML_SYNTAX": "is not valid TOML text", + "E_DUPLICATE_KEY": "names the same entry twice", + "E_SCHEMA_ID": "is not an experiment description of this format", + "E_SCHEMA_VERSION_MISSING": "does not say which format version it is", + "E_SCHEMA_VERSION_UNSUPPORTED": "is of a format version this release does not read", + "E_TYPE": "has a value of the wrong kind", + "E_UNKNOWN_FIELD": "has a field this release does not know", + "E_FORBIDDEN_FIELD": "has a field that is not allowed in it", + "E_MISSING_FIELD": "is missing a required field", + "E_EMPTY": "has an empty list or table", + "E_TEXT_EMPTY": "has an empty text", + "E_ENUM": "has a value that is not one of the allowed choices", + "E_DATE_FORMAT": "has a date that is not written as YYYY-MM-DD", + "E_VALUE_RANGE": "has a number out of its allowed range", + "E_REPEAT_UNCONFIRMED": "has a biological repeat that is not confirmed", + "E_UNKNOWN_CONDITION": "refers to a condition it does not define", + "E_UNKNOWN_CHANNEL": "refers to a channel it does not define", + "E_REFERENCE_UNKNOWN": "compares a condition against one it does not define", + "E_REFERENCE_SELF": "compares a condition against itself", + "E_REFERENCE_CYCLE": "has conditions compared against each other in a circle", +} +"""What a reader code means, in plain words, after "The experiment description".""" + + +def _meaning(code: str) -> str: + """Say in plain words what a reader code means (a family's meaning for the others).""" + if code in _MEANINGS: + return _MEANINGS[code] + if code.startswith(("E_ID_", "E_SINGLE_")): + return "has an identifier that is not permitted" + if code.startswith("E_RGB_"): + return "has colour (RGB) settings that do not agree" + if code.startswith("R_"): + return "differs from what was published before in a way that is not allowed" + return "breaks one of its rules" + + def reader_issue(issue: DescriptionIssue) -> ValidationIssue: - """Return one reader (or file) refusal as an error with its code, table path and value.""" + """Return one reader (or file) refusal: its plain meaning, then its table path and code.""" code = issue.code.value - shown = "" if issue.value is None else f" (value {issue.value!r})" + parts = [f"at {issue.path}"] if issue.path else [] if issue.code is Code.E_TYPE: # the type found, which the code alone does not say - shown = f" (value {issue.value!r}, of type {type_name(issue.value)})" - message = ( - f"The experiment description morphobricks.toml cannot be used: {code} at " - f"{issue.path}{shown}." - ) + parts.append(f"value {issue.value!r} of type {type_name(issue.value)}") + elif issue.value is not None: + parts.append(f"value {issue.value!r}") + shown = ", ".join([*parts, code]) + message = f"The experiment description (morphobricks.toml) {_meaning(code)} ({shown})." return error(code, message, (), FIX) diff --git a/src/morphobricks_preprocessing/fast_answers.py b/src/morphobricks_preprocessing/fast_answers.py index 044f0bb9..ea033bbf 100644 --- a/src/morphobricks_preprocessing/fast_answers.py +++ b/src/morphobricks_preprocessing/fast_answers.py @@ -29,6 +29,7 @@ from collections.abc import Collection, Sequence +from .describe_ids import needs_id from .draft import Draft from .draft_answers import ( CHANNELS, @@ -62,31 +63,25 @@ def _ids(draft: Draft) -> tuple[dict, dict, dict, list[str]]: for folder, slot in sorted(draft.conditions.items()): chosen = slot.confirmed or slot.proposed if chosen is None: - missing.append(f"condition folder {folder!r} has no proposed ID: {_name(folder)}") + missing.append(needs_id("conditions", folder, draft.used_ids.get("conditions", ()))) conditions[folder] = ConditionAnswer(chosen) technical = {} for folder, slot in sorted(draft.technical_repeats.items()): chosen = slot.confirmed or slot.proposed if chosen is None: - missing.append( - f"technical repeat folder {folder!r} has no proposed ID: {_name(folder)}" - ) + used = draft.used_ids.get("technical_repeats", ()) + missing.append(needs_id("technical_repeats", folder, used)) else: technical[folder] = chosen repeats = {} for label, repeat in sorted(draft.repeats.items()): chosen = repeat.id.confirmed or repeat.id.proposed if chosen is None: - missing.append(f"repeat {label!r} has no proposed ID: {_name(label)}") + missing.append(needs_id("repeats", label, draft.used_ids.get("repeats", ()))) repeats[label] = RepeatAnswer(chosen) return conditions, technical, repeats, missing -def _name(folder: str) -> str: - """Say how the user names an ID that cannot be proposed.""" - return f"name it with --id {folder}= (or in the notebook)" - - def _all_named(draft: Draft) -> bool: """Return whether every ID of the draft is already the user's (``--id``).""" slots = [*draft.conditions.values(), *draft.technical_repeats.values()] @@ -106,8 +101,10 @@ def _statements( ) if not comparable: blockers.append( - "say that every biological repeat's folders were prepared and acquired under the " - "same circumstances (--comparable)" + "Comparability has not been confirmed. Add --comparable only if the samples in each " + "biological repeat were prepared and acquired comparably. Otherwise, review the " + "experimental grouping in the notebook. Do not confirm an incorrect experimental " + "design." ) if confirmed_on is None or not valid_day(confirmed_on): blockers.append("give the day of your statements as YYYY-MM-DD (--confirmed-on)") @@ -150,8 +147,10 @@ def fast_answers( blockers.append("--channels lists each channel ID once") if len(header_names) not in (0, len(channels)): blockers.append( - f"the tagged unit's image has {len(header_names)} named channels, --channels " - f"lists {len(channels)}: tag it again" + f"The first acquisition has {len(header_names)} named channels, but --channels lists " + f"{len(channels)}. Check the number and stored order of the channels, then correct " + "--channels. If acquisitions have different channel lists, describe their channels " + "separately in the notebook." ) conditions, technical, repeats, missing = _ids(draft) blockers += missing diff --git a/src/morphobricks_preprocessing/he_tissue_mask.py b/src/morphobricks_preprocessing/he_tissue_mask.py index d2acf192..15cfaf10 100644 --- a/src/morphobricks_preprocessing/he_tissue_mask.py +++ b/src/morphobricks_preprocessing/he_tissue_mask.py @@ -267,8 +267,9 @@ def current_rule(rule: str) -> dict: found = stain.PRESETS[PRESET].version if found != PRESET_VERSION: raise ValueError( - f"The installed normalization's {PRESET} preset is version {found}; {rule} is " - f"defined on version {PRESET_VERSION}" + "The installed normalization version is incompatible with this tissue-mask rule " + f"({rule} needs its {PRESET} preset at version {PRESET_VERSION}, found {found}). " + "Reinstall this preprocessing release with its required dependencies and retry." ) source, digest = hed_matrix() return rule_record(rule, hed_source=source, hed_sha256=digest) @@ -296,18 +297,21 @@ def resolved_fov(run: RunInputs, fov: object) -> Fov: raise RunInputsError(f"{relative} is not an image of this run.") if found.image_type != "rgb": raise ValueError( - f"{relative} is declared {found.image_type}; the H&E tissue mask takes a unit declared " - 'image_type = "rgb"' + f"{relative} was described as separate channels rather than RGB. If it is genuinely " + "a colour image, correct the experiment description and run preprocessing again." ) if found.z_count > 1 or found.t_count > 1: raise ValueError( - f"{relative} has {found.z_count} Z planes and {found.t_count} time points; the H&E " - "tissue mask takes one 2-D plane" + f"{relative} has {found.z_count} Z planes and {found.t_count} time points. The H&E " + "tissue mask does not accept Z-stacks or time-lapses. Use a supported single-plane " + "RGB image, or create appropriate masks with another segmentation tool." ) if found.dtype != "uint8" or found.c_count != 3: raise ValueError( - f"{relative} has the pixel type {found.dtype} and {found.c_count} channels; the H&E " - "tissue mask takes 8-bit RGB (uint8, three channels R, G, B)" + f"{relative} has the pixel type {found.dtype} and {found.c_count} channels. This " + "helper requires 8-bit colour images containing red, green and blue (uint8). Export " + "a suitable RGB copy (converting to 8-bit changes the intensities the rule's " + "thresholds apply to) or create a region mask using another tool." ) return found @@ -396,14 +400,14 @@ def _differences( def _collision(relative: str, differences: list[str]) -> ValueError: """Return the refusal of an existing output that is not this computation's.""" text = ( - f"{relative} exists in the masks folder and is not this computation's output (it " - f"differs in: {', '.join(differences)}); nothing is overwritten. Choose another output " - "mask ID" + f"A different mask already exists at {relative} in the masks folder (it differs in: " + f"{', '.join(differences)}). It will not be overwritten. Choose another output mask ID " + "(--to on the command line), for example HETissue_v2." ) if "rule" in differences or "rule_sha256" in differences: text += ( - ": a rule with another record (a frozen rule included) makes a new mask under a new " - "output mask ID, declared binary, with the masks step run again" + " A rule with another record (a frozen rule included) makes a new mask under a new " + "output mask ID, declared binary, with the masks step run again." ) return ValueError(text) diff --git a/src/morphobricks_preprocessing/ignored_masks.py b/src/morphobricks_preprocessing/ignored_masks.py index 3d779a5e..06c84576 100644 --- a/src/morphobricks_preprocessing/ignored_masks.py +++ b/src/morphobricks_preprocessing/ignored_masks.py @@ -30,6 +30,7 @@ from __future__ import annotations import os +import shlex import tomllib from collections.abc import Iterable from dataclasses import dataclass @@ -104,12 +105,31 @@ def ignored_types(manifest: object) -> frozenset[str]: return frozenset(() if entry is None else entry["types"]) +def unreadable_fix(output_folder: str | os.PathLike) -> str: + """Say how to recover from an ignore list that cannot be read (declare-masks reads it first). + + ``declare-masks`` reads the file before it writes it, so it refuses while the unreadable + file is there: the file is moved out (kept as a backup), then the list is made again. + """ + output = shlex.quote(Path(output_folder).as_posix()) + return ( + f"Move {IGNORED_FILENAME} out of the output folder and keep it as a backup: " + "declare-masks reads the list before changing it, so it cannot rewrite an unreadable " + "one. Then recreate the list with morphobricks-preprocessing declare-masks --output " + f"{output} --ignore TYPE, once for every mask type you still intend to skip (replacing " + "TYPE with its name; --ignore can be repeated), and run preprocessing again." + ) + + def name_problem(name: str) -> str | None: """Return why ``name`` cannot be an ignored mask type, or None when it can.""" if not name or name != name.strip(): - return "a mask type's name is not empty and has no space at its start or end" + return "Give a non-empty mask-type name without leading or trailing spaces." if any(c in name for c in "/\\") or any(ord(c) < 32 for c in name): - return "a mask type's name is one folder or label name: no '/', '\\' or control character" + return ( + "Give a mask-type name that is one folder or label name, without '/', '\\' or " + "control characters." + ) return None @@ -187,4 +207,5 @@ def read_ignored(output_folder: str | os.PathLike) -> IgnoredMasks: "parse_ignored", "read_ignored", "recorded_ignored", + "unreadable_fix", ] diff --git a/src/morphobricks_preprocessing/mask_declare.py b/src/morphobricks_preprocessing/mask_declare.py index ac0df19c..f26a4d5d 100644 --- a/src/morphobricks_preprocessing/mask_declare.py +++ b/src/morphobricks_preprocessing/mask_declare.py @@ -25,12 +25,14 @@ from __future__ import annotations import os +import shlex import unicodedata from collections.abc import Iterable, Mapping from dataclasses import dataclass, replace from pathlib import Path from ._io import write_text_atomic +from .describe_ids import reasons from .description import Description, DescriptionError, Mask from .description_rules import REPRESENTATIONS from .draft_ids import id_problems, propose_id @@ -40,6 +42,7 @@ ignored_text, name_problem, read_ignored, + unreadable_fix, ) from .run.description_file import Publication, PublicationRefused, publish_description from .run.description_run import load_description @@ -75,15 +78,17 @@ def _mask_id(item: MaskDeclaration) -> str: codes = id_problems("masks", item.mask_id) if codes: raise MaskDeclarationRefused( - f"{item.mask_id!r} cannot be a mask ID: {', '.join(codes)}", tuple(codes) + f"{item.mask_id!r} cannot be a mask ID. {reasons(codes)}", tuple(codes) ) return item.mask_id proposal = propose_id("masks", item.source_type) if proposal is None: codes = id_problems("masks", item.source_type) + example = shlex.quote(f"{item.source_type}=instances:Nuclei") raise MaskDeclarationRefused( - f"The mask type {item.source_type!r} is not a valid mask ID ({', '.join(codes)}): " - f"give its ID (for example --type {item.source_type}=:).", + f"The mask type {item.source_type!r} needs a different ID ({', '.join(codes)}). " + f"Keep its folder name and supply an ID, for example --type {example}, if it " + "contains instance labels.", ("mask_id_needed",), ) return proposal @@ -272,7 +277,12 @@ def ignore_masks( if not folder.is_dir(): raise IgnoredMasksError(f"The output folder {folder} does not exist.") with output_lock(folder): - before = read_ignored(folder).types + try: + before = read_ignored(folder).types + except IgnoredMasksError as exc: + raise IgnoredMasksError( + f"The ignored-mask list cannot be read: {exc}. {unreadable_fix(folder)}" + ) from exc after = tuple(sorted((set(before) | set(add)) - declared)) if after == before: return after, False diff --git a/src/morphobricks_preprocessing/mask_text.py b/src/morphobricks_preprocessing/mask_text.py index 91ecd522..018ee732 100644 --- a/src/morphobricks_preprocessing/mask_text.py +++ b/src/morphobricks_preprocessing/mask_text.py @@ -49,14 +49,17 @@ def mask_summary(masks: MaskInventory) -> str: def mask_report_summary(report: MaskReport) -> str: """Describe the mask types, their relationships and the hierarchy in plain words. - Every statement is a suggestion from the masks' pixels; the text ends by asking the - user to name the masks and check the relationships. + Every statement is measured from the masks' pixels and never replaces the declared + representation; the text ends by saying the relationships are inferred from overlap. """ - lines = [f"Mask types ({plural(report.images, 'image')} scanned):"] + lines = [ + f"Mask properties measured from the pixel values ({plural(report.images, 'image')} " + "scanned). These properties do not replace the declared mask representation.", + ] for name, summary in sorted(report.types.items()): lines.append( - f" {name}: {_MASK_KINDS[summary.kind]}; {plural(summary.objects, 'object')}, " - f"median {summary.median_pieces_per_label:g} piece(s) per label" + f" {name}: {_MASK_KINDS[summary.kind]}; {plural(summary.objects, 'positive label')}; " + f"median {summary.median_pieces_per_label:g} connected piece(s) per label" ) relationships = [pair for pair in report.relationships if pair.relation != "same_objects"] if relationships: @@ -67,15 +70,15 @@ def mask_report_summary(report: MaskReport) -> str: lines += [f" {first} and {second}" for first, second in report.same_objects] ambiguous = mask_ambiguous_lines(report) if ambiguous: - lines += ["", "Objects given no parent (equally in two or more objects of the other mask):"] + lines += ["", "Objects with no assigned parent because of equal overlap:"] lines += [f" {line}" for line in ambiguous] lines += ["", "Hierarchy (direct parents only):"] lines += _hierarchy_lines(report.hierarchy) lines += ["", f"Thresholds: {mask_thresholds_used(report)}"] lines += [ "", - "These are suggestions from the masks' pixels: name each mask, then check the " - "relationships before using them.", + "The relationships above are inferred from spatial overlap. Review them before using " + "them in a biological analysis.", ] return "\n".join(lines) @@ -179,8 +182,9 @@ def mask_ambiguous_lines(report: MaskReport) -> list[str]: the relation of the pair, so every pair is listed, ``none`` included. """ return [ - f"{pair.child} in {pair.parent}: {plural(pair.evidence['ambiguous_parent'], 'object')}" - f" of {pair.evidence['children']:,} equally in two or more {pair.parent}" + f"{pair.child} in {pair.parent}: {pair.evidence['ambiguous_parent']:,} of " + f"{plural(pair.evidence['children'], pair.child + ' label')} overlap two or more " + f"{pair.parent} labels equally; no parent was assigned" for pair in report.pairs if pair.evidence.get("ambiguous_parent") ] @@ -198,9 +202,9 @@ def _relationship_line(pair: PairRelation) -> str: f" {pair.child} {_RELATIONS[pair.relation]} {pair.parent}" f"{'' if pair.direct else ' (through another mask)'}: " f"{e['inside']} of {plural(e['children'], 'object')} inside; " - f"{pair.parent} with 0/1/2/3+ {pair.child}: {e['parents_with_0_children']}/" - f"{e['parents_with_1_child']}/{e['parents_with_2_children']}/" - f"{e['parents_with_3_or_more_children']}" + f"{pair.parent} containing {pair.child}: none = {e['parents_with_0_children']}, " + f"one = {e['parents_with_1_child']}, two = {e['parents_with_2_children']}, three or " + f"more = {e['parents_with_3_or_more_children']}" ) extra = [] if e["outside_parents"]: diff --git a/src/morphobricks_preprocessing/physical_check.py b/src/morphobricks_preprocessing/physical_check.py index 4ece9ff6..66914674 100644 --- a/src/morphobricks_preprocessing/physical_check.py +++ b/src/morphobricks_preprocessing/physical_check.py @@ -288,8 +288,8 @@ def undeclared_mask_types( """Return ``R_MASK_TYPE_NOT_DECLARED`` for each mask type found that is not declared. The one rule of ``run`` (through :func:`check_physical`) and ``check``: a mask type found - (a masks folder's subfolder, ``_.tif`` beside the images, or an OME-Zarr - label image) must be the ``source_type`` of a declared mask. Only names are compared. + (a masks folder's subfolder, ``_.tif`` in the masks folder, or an + OME-Zarr label image) must be the ``source_type`` of a declared mask. Only names are compared. """ known = {mask.source_type for mask in description.masks.values()} return [ diff --git a/src/morphobricks_preprocessing/projection_issues.py b/src/morphobricks_preprocessing/projection_issues.py index e608c555..046c8ce7 100644 --- a/src/morphobricks_preprocessing/projection_issues.py +++ b/src/morphobricks_preprocessing/projection_issues.py @@ -29,8 +29,8 @@ def nothing_to_project_issue(roles: str) -> ValidationIssue: f"--project was given, but no image has a depth axis (Z) under the roles {roles}. " "Nothing was written.", [], - "Check the roles: Z must be the axis of the slices of a stack, and every image is " - "otherwise left as it is.", + "Check the stored axis order: Z must be the axis of the slices of a stack. If these " + "images have no depth dimension, omit --project.", ) @@ -77,7 +77,8 @@ def over_memory_issue(path: str, needed: str, limit: str, count: int) -> Validat f"Projecting {path}{more} needs {needed} for one plane and its running total; the " f"limit is {limit}. Nothing was written.", [path], - "Raise the memory limit (--memory-limit).", + "Increase --memory-limit only if sufficient RAM is available, or export smaller images " + "for projection.", ) @@ -85,10 +86,11 @@ def zarr_issue(paths: Sequence[str]) -> ValidationIssue: """Refuse OME-Zarr images in a projection (they are not projected yet).""" return error( "projection_zarr_not_supported", - f"{plural(len(paths), 'OME-Zarr image')} cannot be projected yet: a projected copy is " - "an OME-TIFF, and the copy tree keeps each image's path. Nothing was written.", + "Projection of OME-Zarr source images is not supported in this release " + f"({plural(len(paths), 'OME-Zarr image')}). No projected copies were written.", paths, - "Exclude these images, or project the TIFF images in a separate experiment folder.", + "Export suitable TIFF copies of these images before projection, or process the TIFF " + "images separately.", ) @@ -102,7 +104,10 @@ def masks_3d_issue(by_type: Mapping[str, Sequence[str]]) -> ValidationIssue: "Masks are never projected: a projected label image merges different objects. " "Nothing was written.", paths, - "Make 2-D masks on the projected images, or move these masks out of the masks folder.", + "Existing 3-D masks cannot be used with this projection. Keep the original masks " + "separately, outside the masks folder, then convert the images without those 3-D masks. " + "Create new 2-D masks from the projected images and register them with the new " + "experiment.", ) @@ -114,7 +119,8 @@ def masks_axes_unknown_issue(paths: Sequence[str]) -> ValidationIssue: "are not named, so it is not known whether they have depth slices (Z). Masks are " "never projected, and no axis is guessed. Nothing was written.", paths, - "Name the axes in the masks' metadata, or move these masks out of the masks folder.", + "Check and export the mask axes correctly. If these masks belong to the original 3-D " + "images, keep them separate from the projected experiment.", ) diff --git a/src/morphobricks_preprocessing/report.py b/src/morphobricks_preprocessing/report.py index bdf97015..95af6798 100644 --- a/src/morphobricks_preprocessing/report.py +++ b/src/morphobricks_preprocessing/report.py @@ -238,11 +238,12 @@ def _stopped_summary(result: RunResult) -> str: if result.report_written: written.append(f"{REPORT_FILENAME} and {REPORT_TEXT_FILENAME} (the report)") lines = [ - f"The run stopped ({issue_counts(result.issues)}): no table or manifest was written.", + f"Preprocessing stopped ({issue_counts(result.issues)}). No new histogram table or run " + "manifest was published; existing results from an earlier successful run were kept.", f"Written to {result.output_folder}: {', '.join(written)}." if written else "Nothing was written.", - "Resolve the errors and run again.", + "Review the errors, correct the problems and run again.", ] return "\n".join(lines) diff --git a/src/morphobricks_preprocessing/required_description.py b/src/morphobricks_preprocessing/required_description.py index 21642883..168f8369 100644 --- a/src/morphobricks_preprocessing/required_description.py +++ b/src/morphobricks_preprocessing/required_description.py @@ -11,6 +11,7 @@ from __future__ import annotations import os +import shlex from pathlib import Path from typing import Literal @@ -22,15 +23,33 @@ DESCRIPTION_REQUIRED = "A_DESCRIPTION_REQUIRED" """The refusal of a run without a published description (ADR 0002 AR11 ruling 1).""" -FIX = ( - "Describe the experiment first, which publishes morphobricks.toml in the output folder: " - "either in the notebook (its describe steps, then Check and save), or on the command line " - "with 'morphobricks-preprocessing describe EXPERIMENT --output FOLDER --channels ID,ID " - "--image-type channels|rgb --accept-ids --comparable --confirmed-on YYYY-MM-DD --publish' " - "(without --publish it shows what is still to be answered)." +_EXAMPLE = ( + "morphobricks-preprocessing describe my_experiment{output} --channels COL,FN " + "--image-type channels --accept-ids --comparable --confirmed-on 2026-12-04 --publish" +) +_FIX = ( + "Describe the experiment before running preprocessing. Start with the command below, " + "replacing EXPERIMENT with your images folder, and review the proposed IDs and channel " + "order:\n" + " morphobricks-preprocessing describe EXPERIMENT{output}\n" + "To publish a simple two-channel fluorescence experiment, use the following example, " + "replacing my_experiment, the channels and the confirmation date with your own:\n" + " {example}\n" + "If your acquisitions have different channel lists or orders, describe them in the notebook " + "instead." +) +FIX = _FIX.format(output="", example=_EXAMPLE.format(output="")) + ( + " Add --output with your output folder to both commands when it is not the default one." ) """What the user does about it: either route publishes (owner, 4 December 2026): the notebook's -describe steps, or the command line's ``describe --publish`` (fast mode).""" +describe steps, or the command line's ``describe --publish`` (fast mode). Placeholders are +named in words, never as shell-unsafe text such as ``a|b`` (external review, 4 December 2026).""" + + +def fix_text(output_folder: str | os.PathLike) -> str: + """Return :data:`FIX` naming the refused output folder in both commands (``--output``).""" + output = f" --output {shlex.quote(Path(output_folder).as_posix())}" + return _FIX.format(output=output, example=_EXAMPLE.format(output=output)) def is_published(output_folder: str | os.PathLike) -> bool: @@ -56,7 +75,7 @@ def description_required_issue(output_folder: str | os.PathLike) -> ValidationIs DESCRIPTION_REQUIRED, required_message(output_folder), [Path(output_folder).as_posix()], - FIX, + fix_text(output_folder), ) diff --git a/src/morphobricks_preprocessing/run/preflight.py b/src/morphobricks_preprocessing/run/preflight.py index 2cfa22f2..e8640802 100644 --- a/src/morphobricks_preprocessing/run/preflight.py +++ b/src/morphobricks_preprocessing/run/preflight.py @@ -26,7 +26,13 @@ from ..dataset import DatasetReport, check_dataset from ..discovery import DiscoveryResult, default_output_folder, discover_experiment from ..fingerprint import Fingerprint, current_fingerprint -from ..ignored_masks import IGNORED_FILENAME, IgnoredMasks, IgnoredMasksError, read_ignored +from ..ignored_masks import ( + IGNORED_FILENAME, + IgnoredMasks, + IgnoredMasksError, + read_ignored, + unreadable_fix, +) from ..mask_names import MASK_NAME_CODES, mask_name_issues from ..masks import MaskFile, MaskInventory, find_masks from ..metadata import ( @@ -309,9 +315,9 @@ def _ignored(output: Path) -> tuple[IgnoredMasks, tuple[ValidationIssue, ...]]: return IgnoredMasks(), ( error( "ignored_masks_invalid", - f"The list of ignored mask types cannot be read: {exc}", + f"The ignored-mask list cannot be read: {exc}", [IGNORED_FILENAME], - "Write it again with declare-masks --ignore, or remove the file.", + unreadable_fix(output), ), ) diff --git a/src/morphobricks_preprocessing/run_inputs_text.py b/src/morphobricks_preprocessing/run_inputs_text.py index f622b4e8..0d0e0ca5 100644 --- a/src/morphobricks_preprocessing/run_inputs_text.py +++ b/src/morphobricks_preprocessing/run_inputs_text.py @@ -7,6 +7,8 @@ from __future__ import annotations +import re +from importlib.metadata import PackageNotFoundError, version from typing import TYPE_CHECKING from .validation import plural @@ -30,10 +32,36 @@ def _without_axes_text(paths: list[str]) -> str: ) +REPOSITORY = "git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git" + + +def zarr_install_line(installed: str | None) -> str: + """Return the install command of the ``zarr`` extra for the installed release. + + A release version (``X.Y.Z``) names its tag, so the extra comes with the same release; any + other version (a development build, or none known) gets the unpinned extra and says so. + """ + if installed is not None and re.fullmatch(r"\d+\.\d+\.\d+", installed): + pinned = f"morphobricks-preprocessing[zarr] @ {REPOSITORY}@v{installed}" + return f'python -m pip install "{pinned}"' + return ( + 'python -m pip install "morphobricks-preprocessing[zarr]" (install the same release ' + "of morphobricks-preprocessing as the one you use)" + ) + + +def _installed() -> str | None: + """Return the installed version of this package, or None when it is not known.""" + try: + return version("morphobricks-preprocessing") + except PackageNotFoundError: + return None + + _ZARR_MISSING = ( "The run holds OME-Zarr images, and the zarr package is not installed, so their label " "images cannot be checked against the run (none is ever skipped). Install it with: " - 'pip install "morphobricks-preprocessing[zarr]"' + f"{zarr_install_line(_installed())}" ) diff --git a/src/morphobricks_preprocessing/run_inputs_tissue.py b/src/morphobricks_preprocessing/run_inputs_tissue.py index 24784400..0edf4601 100644 --- a/src/morphobricks_preprocessing/run_inputs_tissue.py +++ b/src/morphobricks_preprocessing/run_inputs_tissue.py @@ -84,9 +84,26 @@ def preview_he_tissue_mask( return preview(self, fov, rule=rule) -PROVISIONAL_NOTE = ( - "Sizes are in pixels. Fixed rule he_tissue_v2 (provisional), not a trained segmentation." -) +def provisional_note(rule: str) -> str: + """Return the note naming the tissue-mask ``rule`` actually used (review P1.14). + + Parameters + ---------- + rule + The rule the masks are computed with, for example ``he_tissue_v1``. + + Returns + ------- + str + """ + return ( + f"Tissue-mask rule: {rule} (provisional, a fixed rule, not a trained segmentation). " + "All spatial thresholds are in pixels. Inspect the resulting masks before analysis." + ) + + +PROVISIONAL_NOTE = provisional_note(HE_TISSUE_V2) +"""The note of the default rule (the notebook's previews use it).""" NOT_REUSED = "this mask will not be reused on retry" """Said whenever a code identity is unverified (the mask is written but never reused).""" @@ -108,7 +125,12 @@ def tissue_next_steps( ids = sorted(set(mask_ids)) if not ids: return "No mask was written." - lines = [f"Written to the masks folder {masks_root}. Next:"] + lines = [ + f"Masks saved in the masks folder {masks_root}.", + "Inspect representative images with their masks overlaid (in Fiji or QuPath). Check " + "that the retained regions are the tissue you intend to measure. If the masks are " + "suitable, register and check them:", + ] commands = list(commands) if commands: lines += [f" {command}" for command in commands] diff --git a/src/morphobricks_preprocessing/tissue_masks_folder.py b/src/morphobricks_preprocessing/tissue_masks_folder.py index 0671d82d..679df93a 100644 --- a/src/morphobricks_preprocessing/tissue_masks_folder.py +++ b/src/morphobricks_preprocessing/tissue_masks_folder.py @@ -15,6 +15,7 @@ from __future__ import annotations import os +import shlex from dataclasses import dataclass from pathlib import Path @@ -63,10 +64,12 @@ def create_masks_folder(run: RunInputs, folder: str | os.PathLike | None) -> Cre target = Path(folder).resolve() if folder else default_masks_folder(run.experiment_root) created = not target.exists() if not created and (not target.is_dir() or any(target.iterdir())): + output, masks = shlex.quote(str(run.output_folder)), shlex.quote(str(target)) raise MasksFolderRefused( - f"{target} exists and is not an empty folder, so it is not made the run's masks " - "folder. Give another with --masks FOLDER, or run preprocessing with " - f"--masks {target} if it is your masks folder." + f"{target} already exists and is not an empty folder. Choose another empty folder " + "with --masks. If this is your experiment's existing masks folder, register it " + f"using morphobricks-preprocessing run --output {output} --masks {masks} before " + "retrying." ) try: target.mkdir(parents=True, exist_ok=True) diff --git a/tests/test_axis_check.py b/tests/test_axis_check.py index 4d9fb9b1..576effa8 100644 --- a/tests/test_axis_check.py +++ b/tests/test_axis_check.py @@ -390,7 +390,7 @@ def test_cli_run_names_the_swapped_files(tmp_path, capsys): assert main_described(["run", str(root), "--axes", "CXY"]) == 1 out = capsys.readouterr().out assert "header CYX, confirmed CXY: ctrl/a.tif" in out - assert "no table or manifest was written" in out + assert "No new histogram table or run manifest was published" in out def test_notebook_marks_roles_that_disagree_with_the_header(tmp_path): diff --git a/tests/test_brick_checks.py b/tests/test_brick_checks.py index 004729a2..74d7041b 100644 --- a/tests/test_brick_checks.py +++ b/tests/test_brick_checks.py @@ -288,3 +288,15 @@ def refuse(path="."): assert raised.value.code == "masks_folder_unreadable" assert str(raised.value).startswith("masks_folder_unreadable: ") assert str(locked) in str(raised.value) + + +def test_the_zarr_install_line_names_the_installed_release(): + from morphobricks_preprocessing.run_inputs_text import zarr_install_line + + assert zarr_install_line("0.10.0") == ( + 'python -m pip install "morphobricks-preprocessing[zarr] @ ' + 'git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.0"' + ) + for unreleased in ("0.10.1.dev3+g197b6db", None): # no tag to name: never a made-up one + line = zarr_install_line(unreleased) + assert "@v" not in line and "the same release" in line diff --git a/tests/test_calibration.py b/tests/test_calibration.py index e928f5d6..26a4f013 100644 --- a/tests/test_calibration.py +++ b/tests/test_calibration.py @@ -462,7 +462,7 @@ def test_the_calibrate_command_keeps_an_unreadable_file(tmp_path, capsys): def test_the_calibrate_command_states_shows_and_removes(tmp_path, capsys): output = tmp_path / "out" assert main(["calibrate", "--output", str(output)]) == 0 - assert "No pixel size is stated" in capsys.readouterr().out + assert "No pixel sizes have been stated" in capsys.readouterr().out assert not (output / CALIBRATION_FILENAME).exists() args = ["calibrate", "--output", str(output), "--size", ".", "YX", "0.65", "um"] assert main_described([*args, "--pixels", "ctrl/rep1", "Z"]) == 0 diff --git a/tests/test_cli.py b/tests/test_cli.py index 588fabef..fbb6c4e4 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -48,7 +48,11 @@ def test_check_prints_summary_and_suggested_axes(experiment, capsys): assert "Suggested option for 'run': --axes TCYX (axes in the files: TCYX)" in out # 'check' is the run's step stopped after the report: it writes the report only. output = experiment.parent / "exp_MorphoBricks_Preprocessing" - assert check_outputs(output) and f"Report written to {output}" in out + assert ( + check_outputs(output) + and f"Report saved to {output}" in out + and "Header check passed." in out + ) def test_check_exits_with_1_on_errors(experiment, capsys): @@ -113,7 +117,10 @@ def test_rgb_is_refused_for_images_that_cannot_be_rgb(experiment, capsys): out = capsys.readouterr().out assert "contradict their header" in out assert "RGB images need exactly three colour channels" in out - assert "8 channels of type uint8" in out and "no table or manifest was written" in out + assert ( + "8 channels of type uint8" in out + and "No new histogram table or run manifest was published" in out + ) def test_image_type_must_be_known(experiment): @@ -188,7 +195,7 @@ def test_run_reports_blocking_errors(experiment, capsys): assert main_described(["run", str(experiment), "--axes", "Z-YX"]) == 1 out = capsys.readouterr().out assert "No role is chosen for the axis C (channel)" in out - assert "no table or manifest was written" in out + assert "No new histogram table or run manifest was published" in out def test_run_without_readable_images(tmp_path, capsys): @@ -217,7 +224,7 @@ def test_different_channel_counts_stop_check_and_run(tmp_path, capsys): assert "different numbers of channels: 3 channels (2 images), 2 channels (1 image)" in out assert main_described(["run", str(root), "--axes", "TCYX"]) == 1 out = capsys.readouterr().out # one described unit: its images are not homogeneous - assert "b.tif" in out and "no table or manifest was written" in out + assert "b.tif" in out and "No new histogram table or run manifest was published" in out def test_axes_are_needed_for_the_first_run_of_plain_stacks_only(tmp_path, capsys): diff --git a/tests/test_cli_describe.py b/tests/test_cli_describe.py index 6837cd80..129ae94e 100644 --- a/tests/test_cli_describe.py +++ b/tests/test_cli_describe.py @@ -68,7 +68,7 @@ def test_describe_prints_the_proposals_and_the_open_questions_and_writes_nothing assert "rep1: proposed ID 'rep1'; not confirmed" in out assert "CTRL / rep1: 2 images" in out assert "open questions (answered by you, in the notebook)" in out - assert "confirm that the folders of repeat rep1 were prepared and acquired" in out + assert "only if it is true, that the samples of repeat rep1 were prepared and acquired" in out assert "choose the ID of condition CTRL" in out assert listing(tmp_path) == before and not output.exists() @@ -77,7 +77,9 @@ def test_a_folder_that_cannot_be_an_id_has_no_proposal_and_is_not_repaired(tmp_p root = tree(tmp_path / "exp", "control/rep1", "DrugA/rep1") assert main(["describe", str(root)]) == 0 out = capsys.readouterr().out - assert "control: no ID can be proposed" in out and "you name it" in out + assert "control: no ID proposed. The condition folder 'control' needs another" in out + assert "because 'control' is reserved (E_FORBIDDEN_FIELD)" in out + assert "Keep the folder name and add --id control=ctrl" in out assert "DrugA: proposed ID 'DrugA'" in out @@ -123,7 +125,7 @@ def test_publish_refuses_a_draft_with_open_questions_and_lists_them(experiment, assert "Not published. What is missing:" in out missing = out.split("Not published. What is missing:")[1] assert missing.count(" - choose the ID of") == 5 # 2 conditions, single, 2 repeats - assert " - confirm that the folders of repeat rep2" in out + assert " - confirm, only if it is true, that the samples of repeat rep2" in out assert not (output / TOML).exists() and not output.exists() assert listing(tmp_path) == before @@ -142,7 +144,7 @@ def test_a_complete_draft_is_still_not_publishable_from_the_command_line(tmp_pat ]: draft = draft.confirm_id(kind, key, key) assert [q.code for q in draft.open_questions()] == ["repeat_not_confirmed"] - assert any("same circumstances" in item for item in draft_blockers(draft)) + assert any("prepared and acquired comparably" in item for item in draft_blockers(draft)) done = replace( draft, repeats={"rep1": replace(draft.repeats["rep1"], confirmed=True, confirmed_on="2026-11-01")}, @@ -208,4 +210,6 @@ def test_a_description_that_cannot_be_read_is_refused(tmp_path, capsys): root, output = published(tmp_path) (output / TOML).write_text("schema = 'nope'\n", encoding="utf-8") assert main(["describe", str(root), "--output", str(output)]) == 1 - assert "cannot be used" in capsys.readouterr().out + out = capsys.readouterr().out # the plain meaning first, then the field path and code + assert "The experiment description (morphobricks.toml) is not an experiment" in out + assert "(at schema, value 'nope', E_SCHEMA_ID)" in out diff --git a/tests/test_cli_tissue_mask.py b/tests/test_cli_tissue_mask.py index 78edc1f1..3a61ed80 100644 --- a/tests/test_cli_tissue_mask.py +++ b/tests/test_cli_tissue_mask.py @@ -44,8 +44,8 @@ def test_it_writes_every_rgb_image_and_names_the_next_steps(tmp_path, capsys, mo args = ["tissue-mask", "--output", str(run.output_folder), "--to", "HETissue"] assert main(args) == 0 printed = capsys.readouterr().out - assert "Fixed rule he_tissue_v2 (provisional)" in printed - assert f"{IMAGE}: HETissue/{IMAGE} (written), kept 80.4 %" in printed + assert "Tissue-mask rule: he_tissue_v2 (provisional" in printed + assert f"{IMAGE}: mask saved to HETissue/{IMAGE}; retained area: 80.4 % of the image" in printed output = run.output_folder assert ( f"morphobricks-preprocessing declare-masks --output {output} --type HETissue=binary " @@ -60,7 +60,7 @@ def test_it_writes_every_rgb_image_and_names_the_next_steps(tmp_path, capsys, mo assert line["operation"] == "he_tissue_mask" and line["reusable"] is True before = tree(run.masks_root) assert main([*args, "--image", IMAGE]) == 0 # the same call: a no-op - assert "(already written)" in capsys.readouterr().out + assert "mask already saved to" in capsys.readouterr().out assert tree(run.masks_root) == before @@ -144,9 +144,10 @@ def test_a_run_without_masks_folder_gets_one_recorded_as_run_masks_would( assert main(args) == 0 printed = capsys.readouterr().out folder = (tmp_path / "experiment_masks").resolve() - created = [line for line in printed.splitlines() if "had no masks folder" in line] + created = [line for line in printed.splitlines() if "Masks folder created" in line] assert created == [ - f"The run had no masks folder: created {folder} and recorded it, as run --masks does." + f"Masks folder created and registered: {folder}. The preprocessing run now records " + "this folder." ] assert (folder / "HETissue" / IMAGE).is_file() manifest = json.loads((run.output_folder / "run_manifest.json").read_text()) @@ -156,7 +157,7 @@ def test_a_run_without_masks_folder_gets_one_recorded_as_run_masks_would( assert RunInputs.open(run.output_folder).masks_root == folder assert main(args) == 0 # the same call again: the recorded folder, nothing created printed = capsys.readouterr().out - assert "had no masks folder" not in printed and "(already written)" in printed + assert "Masks folder created" not in printed and "mask already saved to" in printed def test_masks_names_the_folder_to_create_and_a_busy_folder_is_refused( @@ -174,7 +175,7 @@ def test_masks_names_the_folder_to_create_and_a_busy_folder_is_refused( assert not (manifest.get("masks") or {}).get("folder") chosen = tmp_path / "chosen" assert main([*args, "--masks", str(chosen)]) == 0 - assert f"created {chosen.resolve()}" in capsys.readouterr().out + assert f"Masks folder created and registered: {chosen.resolve()}." in capsys.readouterr().out assert (chosen / "HETissue" / IMAGE).is_file() assert main([*args, "--masks", str(tmp_path / "third")]) == 1 # the run has one now assert "this run records" in capsys.readouterr().out diff --git a/tests/test_cli_usability.py b/tests/test_cli_usability.py index 36ab6972..44c58cb1 100644 --- a/tests/test_cli_usability.py +++ b/tests/test_cli_usability.py @@ -223,14 +223,21 @@ def test_check_reports_an_undeclared_ome_zarr_label_mask_as_run_refuses_it(tmp_p assert main(["run", str(root), "--output", str(out)]) == 1 ran = capsys.readouterr().out message = ( - "Masks of type 'cells' were found (in the masks folder, beside the images or as " - "OME-Zarr label images), but are not declared in the description." + "The mask type 'cells' was found but has not been declared. Choose how its pixel " + "values should be interpreted." + ) + # Every representation is offered with what it means; none is guessed from the name. + action = ( + "If every object has its own positive label, declare it as instance labels (replacing " + "OUTPUT with your output folder):\n" + " morphobricks-preprocessing declare-masks --output OUTPUT --type cells=instances\n" ) - action = "declare-masks --output FOLDER --type cells=REPRESENTATION" for text in (checked, ran): assert message in text and action in text - assert "declare-masks --output FOLDER --ignore cells" in text # owner, 4 Dec 2026 - assert "--type TYPE=instances" not in checked # no representation is suggested for you + assert "declare-masks --output OUTPUT --ignore cells" in text # owner, 4 Dec 2026 + assert "For a foreground/background mask, use cells=binary instead." in text + assert "For labels grouping several objects, use cells=parent_labels." in text + assert "beside the images" not in checked # masks live in a masks folder, never there import json report = json.loads((out / "discovery_report.json").read_text()) @@ -243,8 +250,14 @@ def test_an_undeclared_mask_type_with_a_space_is_quoted_in_the_fix(): from morphobricks_preprocessing.physical_unit import PhysicalIssue issue = physical_issue(PhysicalIssue(MASK_TYPE_NOT_DECLARED, None, detail="Cell outlines")) - assert "--type 'Cell outlines=REPRESENTATION'" in issue.action + assert "--type 'Cell outlines=instances'" in issue.action assert "--ignore 'Cell outlines'" in issue.action + assert "use 'Cell outlines=binary'" in issue.action + named = physical_issue( + PhysicalIssue(MASK_TYPE_NOT_DECLARED, None, detail="cells"), "/data/my out" + ) + assert "declare-masks --output '/data/my out' --type cells=instances" in named.action + assert "OUTPUT" not in named.action def test_declare_masks_ignore_skips_a_label_image_and_the_run_records_it(tmp_path, capsys): @@ -300,9 +313,18 @@ def test_an_invalid_ignore_file_stops_check_and_run(tmp_path, capsys): capsys.readouterr() (out / "ignored_masks.toml").write_text('version = 2\nignore = ["cells"]\n') assert main(["check", str(root), "--output", str(out)]) == 1 - assert "The list of ignored mask types cannot be read" in capsys.readouterr().out + checked = capsys.readouterr().out + assert "The ignored-mask list cannot be read" in checked + # declare-masks reads the list first, so the fix moves the file out before recreating it. + assert "Move ignored_masks.toml out of the output folder and keep it as a backup" in checked + assert f"declare-masks --output {out.as_posix()} --ignore TYPE" in checked assert main(["declare-masks", "--output", str(out), "--ignore", "x"]) == 1 - assert "this release reads version 1" in capsys.readouterr().out + refused = capsys.readouterr().out + assert "this release reads version 1" in refused + assert "Move ignored_masks.toml out of the output folder" in refused + (out / "ignored_masks.toml").rename(tmp_path / "ignored_masks.toml.bak") # as it says + assert main(["declare-masks", "--output", str(out), "--ignore", "cells"]) == 0 + assert main(["check", str(root), "--output", str(out)]) == 0 def test_declare_masks_without_a_masks_folder_names_no_placeholder_folder(tmp_path, capsys): @@ -325,7 +347,8 @@ def test_declare_masks_with_a_masks_folder_names_it(tmp_path, capsys): from morphobricks_preprocessing.cli_declare_masks import next_commands lines = next_commands(str(tmp_path / "out"), str(tmp_path / "my masks")) - assert lines[1].endswith(f"--masks '{tmp_path / 'my masks'}'") + run_line = next(line for line in lines if "morphobricks-preprocessing run" in line) + assert run_line.endswith(f"--masks '{tmp_path / 'my masks'}'") assert all("Add --masks" not in line for line in lines) @@ -344,7 +367,7 @@ def test_fast_describe_lists_open_questions_only_while_some_remain(tmp_path, cap assert main(["describe", str(root), "--output", str(tmp_path / "o2"), *partial]) == 0 text = capsys.readouterr().out assert "1 open question (answer them with --comparable and --confirmed-on" in text - assert "confirm that the folders of repeat rep1" in text + assert "confirm, only if it is true, that the samples of repeat rep1" in text assert "choose the ID" not in text # --accept-ids answered those @@ -357,7 +380,8 @@ def test_an_id_with_no_proposal_stays_open_under_accept_ids(tmp_path, capsys): text = capsys.readouterr().out assert "are answered by your options" not in text assert "1 open question (answer them with --id FOLDER=ID, or in the notebook)" in text - assert "give --id files=" in text + assert "needs another identifier because 'files' is reserved" in text + assert "add --id files=files_1" in text and "" not in text # --- 4b. describe --id FOLDER=ID (owner, 4 December 2026) ---------------------------------- @@ -372,10 +396,11 @@ def test_describe_id_names_a_forbidden_folder_and_publishes(tmp_path, capsys): text = capsys.readouterr().out assert "answer them with --id FOLDER=ID, or in the notebook" in text assert "--accept-ids, " not in text.split("open question")[1].split("\n")[0] - assert "name it with --id control=" in text + assert "The condition folder 'control' needs another identifier because 'control' is" in text + assert "Keep the folder name and add --id control=ctrl" in text and "" not in text assert not (out / DESCRIPTION_FILENAME).exists() assert main([*command, "--id", "control=ctrl"]) == 0 - assert "Published" in capsys.readouterr().out + assert "Experiment description saved to" in capsys.readouterr().out published = description_from_bytes((out / DESCRIPTION_FILENAME).read_bytes()) assert published.conditions["ctrl"].source_folder == "control" assert set(published.conditions) == {"ctrl", "DrugA"} @@ -387,9 +412,13 @@ def test_describe_id_refuses_what_the_notebook_refuses_and_names_the_option(tmp_ _ome(root / condition / "rep1" / "img.ome.tif") base = ["describe", str(root), "--output", str(out), *CHANNELS, "--publish"] for given, said in [ - ("control=files", "(E_FORBIDDEN_FIELD); give an allowed ID: --id control="), - ("control=druga", "E_ID_CASE_COLLISION"), - ("control=DrugA", "id_in_use_in_draft"), + ( + "control=files", + "This name is reserved. Choose another identifier (E_FORBIDDEN_FIELD). For " + "example: --id control=ctrl", + ), + ("control=druga", "only in upper/lower case. Choose a distinct identifier"), + ("control=DrugA", "already been used for another entry. Choose an unused identifier"), ("nowhere=x", "'nowhere' is not a condition, biological-repeat or technical-repeat"), ("control", "write it as FOLDER=ID"), ]: @@ -417,7 +446,9 @@ def test_describe_id_needs_the_level_for_a_label_of_two_levels(tmp_path, capsys) _ome(root / "b" / "rep1" / "a" / "img.ome.tif") base = ["describe", str(root), "--output", str(out), *CHANNELS, "--publish"] assert main([*base, "--id", "a=A1"]) == 1 - assert "give --id condition:a=A1 or --id technical:a=A1" in capsys.readouterr().out + text = capsys.readouterr().out + assert "the name 'a' occurs at more than one folder level. Specify which level" in text + assert "--id condition:a=A1 or --id technical:a=A1" in text assert main([*base, "--id", "condition:a=A1"]) == 0 published = description_from_bytes((out / DESCRIPTION_FILENAME).read_bytes()) assert published.conditions["A1"].source_folder == "a" diff --git a/tests/test_convert_work_folder.py b/tests/test_convert_work_folder.py index 69557df2..27916549 100644 --- a/tests/test_convert_work_folder.py +++ b/tests/test_convert_work_folder.py @@ -256,5 +256,5 @@ def test_an_owner_file_of_nul_bytes_is_refused_as_possibly_from_a_power_loss( message = result.issues[0].message assert ("possibly left by a power loss" in message) is named assert ("is unreadable" in message) is named - assert ("So it was not made by a conversion" in message) is not named + assert ("has an invalid or missing ownership record" in message) is not named assert _tree(copies) == before diff --git a/tests/test_declare_masks.py b/tests/test_declare_masks.py index 69e90c7b..fc991463 100644 --- a/tests/test_declare_masks.py +++ b/tests/test_declare_masks.py @@ -42,7 +42,7 @@ def test_the_masks_of_a_run_are_declared_run_and_described_from_the_command_line out = str(run.output) assert main(["run", str(run.experiment), "--output", out, "--masks", str(masks)]) == 1 refused = capsys.readouterr().out - assert "not declared" in refused and "declare-masks" in refused + assert "has not been declared" in refused and "declare-masks" in refused assert main(["declare-masks", "--output", out, "--type", "Cells=instances"]) == 0 said = capsys.readouterr().out diff --git a/tests/test_he_tissue_mask.py b/tests/test_he_tissue_mask.py index 6b8b89c8..a4685cce 100644 --- a/tests/test_he_tissue_mask.py +++ b/tests/test_he_tissue_mask.py @@ -194,7 +194,7 @@ def test_a_hand_built_rgb_fov_of_a_channels_position_is_refused(tmp_path, monkey run = channels_run(tmp_path) (own,) = run.fovs() no_reads(monkeypatch) - with pytest.raises(ValueError, match="is declared channels; the H&E tissue mask takes a unit"): + with pytest.raises(ValueError, match="was described as separate channels rather than RGB"): run.he_tissue_mask(dataclasses.replace(own, image_type="rgb"), output_mask_id="HETissue") @@ -324,7 +324,9 @@ def test_a_foreign_file_and_an_existing_file_are_refused_before_any_read(run, mo no_reads(monkeypatch) with pytest.raises(ValueError, match="holds masks of the type 'Other' that this helper"): run.he_tissue_mask(IMAGE, output_mask_id="Other") - with pytest.raises(ValueError, match=f"{OUT} exists .* unverified code identity"): + with pytest.raises( + ValueError, match=f"A different mask already exists at {OUT} .* unverified code identity" + ): run.he_tissue_mask(IMAGE, output_mask_id="HETissue") assert tree(run.masks_root) == before diff --git a/tests/test_ignored_masks.py b/tests/test_ignored_masks.py index e72f539e..06b97501 100644 --- a/tests/test_ignored_masks.py +++ b/tests/test_ignored_masks.py @@ -33,8 +33,8 @@ def test_the_text_is_canonical_and_reads_back(): (b'version = true\nignore = ["a"]\n', "reads version 1"), (b'version = 1\nignore = "a"\n', "list of names"), (b'version = 1\nignore = ["a", "a"]\n', "listed twice"), - (b'version = 1\nignore = [" a"]\n', "no space at its start or end"), - (b'version = 1\nignore = ["a/b"]\n', "no '/'"), + (b'version = 1\nignore = [" a"]\n', "without leading or trailing spaces"), + (b'version = 1\nignore = ["a/b"]\n', "without '/'"), (b"\xff", "not UTF-8 TOML"), (b"version = [", "not UTF-8 TOML"), ], diff --git a/tests/test_mask_step.py b/tests/test_mask_step.py index 3060c6c7..55adbb11 100644 --- a/tests/test_mask_step.py +++ b/tests/test_mask_step.py @@ -58,7 +58,7 @@ def test_describe_masks_writes_the_report_the_command_writes(clean, capsys): result.path.unlink() assert main_described(["masks", "--output", str(clean.output)]) == 0 assert without_versions(clean.output / MASK_REPORT_FILENAME) == written - assert f"Report written to {result.path}" in capsys.readouterr().out + assert f"Mask check completed. Relationships saved to {result.path}." in capsys.readouterr().out def test_without_an_experiment_or_a_recorded_run_the_step_is_refused(tmp_path): diff --git a/tests/test_mask_ties.py b/tests/test_mask_ties.py index c784a9af..2a60bf1b 100644 --- a/tests/test_mask_ties.py +++ b/tests/test_mask_ties.py @@ -192,11 +192,12 @@ def test_the_report_and_its_texts_show_the_tie(tmp_path): (written,) = [p for p in data["pairs"] if (p["child"], p["parent"]) == ("Nuclei", "Cells")] assert written["evidence"]["ambiguous_parent"] == 2 assert mask_ambiguous_lines(report) == [ - "Nuclei in Cells: 2 objects of 4 equally in two or more Cells" + "Nuclei in Cells: 2 of 4 Nuclei labels overlap two or more Cells labels equally; no " + "parent was assigned" ] text = mask_report_summary(report) - assert "Objects given no parent (equally in two or more objects" in text - assert "Nuclei in Cells: 2 objects of 4" in text + assert "Objects with no assigned parent because of equal overlap" in text + assert "Nuclei in Cells: 2 of 4 Nuclei labels" in text def test_the_relationship_table_has_the_tied_children(tmp_path): diff --git a/tests/test_notebook_mask_step.py b/tests/test_notebook_mask_step.py index 6f9ace95..b1aab3e3 100644 --- a/tests/test_notebook_mask_step.py +++ b/tests/test_notebook_mask_step.py @@ -161,7 +161,10 @@ def test_a_child_equally_in_two_parents_is_shown_with_no_parent(tmp_path): nb.mask_step_button.click() shown = nb.mask_step_result.value assert "Objects given no parent (a tie, to check)" in shown - assert "
  • nuclei in cells: 4 objects of 4 equally in two or more cells
  • " in shown + assert ( + "
  • nuclei in cells: 4 of 4 nuclei labels overlap two or more cells labels equally; " + "no parent was assigned
  • " in shown + ) def test_a_locked_output_folder_shows_the_lock_card_and_writes_nothing(tmp_path): diff --git a/tests/test_notebook_tag_by_repeat_drafts.py b/tests/test_notebook_tag_by_repeat_drafts.py index d24839eb..e54c1131 100644 --- a/tests/test_notebook_tag_by_repeat_drafts.py +++ b/tests/test_notebook_tag_by_repeat_drafts.py @@ -18,7 +18,10 @@ from dataclasses import replace # noqa: E402 from morphobricks_preprocessing.description_file import DRAFT_FILENAME # noqa: E402 -from morphobricks_preprocessing.draft_format import answers_from_bytes, answers_to_bytes # noqa: E402 +from morphobricks_preprocessing.draft_format import ( # noqa: E402 + answers_from_bytes, + answers_to_bytes, +) from test_notebook_channels import set_labels # noqa: E402 from test_notebook_check_save import opened # noqa: E402 from test_notebook_tag_by_repeat import EXTRA # noqa: E402 diff --git a/tests/test_notebook_tissue_mask.py b/tests/test_notebook_tissue_mask.py index f54ee53f..56e43987 100644 --- a/tests/test_notebook_tissue_mask.py +++ b/tests/test_notebook_tissue_mask.py @@ -91,7 +91,7 @@ def test_the_preview_writes_nothing_and_shows_the_shares_and_notes(tmp_path, mon ) text = card.numbers.value assert "kept 80.4 % · nuclei 1.6 % · red cells 0.8 % · empty 17.2 %" in text - assert "Sizes are in pixels. Fixed rule he_tissue_v2 (provisional)" in text + assert "Tissue-mask rule: he_tissue_v2 (provisional" in text assert "this mask will not be reused on retry" in text # an unverified identity diff --git a/tests/test_report.py b/tests/test_report.py index 4c9dafa6..e0abf13f 100644 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -124,7 +124,7 @@ def test_run_summaries(experiment): def test_run_summary_when_blocked(experiment): result = run_described(experiment, prefill_mapping("TYX"), bin_count=0) - assert run_summary(result).startswith("The run stopped (1 error") + assert run_summary(result).startswith("Preprocessing stopped (1 error") def test_group_summaries_pool_the_planes(experiment): diff --git a/tests/test_run_description.py b/tests/test_run_description.py index def8459c..7d6e3541 100644 --- a/tests/test_run_description.py +++ b/tests/test_run_description.py @@ -111,7 +111,9 @@ def test_an_invalid_description_stops_the_run_with_its_code_and_path(tmp_path): assert not result.written and not (out / "run_manifest.json").exists() assert result.issues and all(i.is_error for i in result.issues) assert result.issues[0].code.startswith("E_") - assert "morphobricks.toml cannot be used" in result.issues[0].message + message = result.issues[0].message # its plain meaning first, then the path and code + assert "The experiment description (morphobricks.toml) is not an experiment" in message + assert "(at schema, value 'wrong', E_SCHEMA_ID)" in message def test_an_unreadable_records_file_stops_the_run(tmp_path): diff --git a/tests/test_stopped_run_text.py b/tests/test_stopped_run_text.py index a8290d96..aa23bae7 100644 --- a/tests/test_stopped_run_text.py +++ b/tests/test_stopped_run_text.py @@ -27,8 +27,8 @@ def test_a_stopped_api_run_records_that_its_report_was_written(tmp_path): result = run_described(root, prefill_mapping("ZYX"), output_folder=output) # wrong roles assert not result.written and result.report_written text = run_summary(result) - assert text.startswith("The run stopped (") - assert "no table or manifest was written" in text + assert text.startswith("Preprocessing stopped (") + assert "No new histogram table or run manifest was published" in text assert f"Written to {output}: discovery_report.json and discovery_report.txt" in text assert "experiment_design.csv" not in text From 15d1e756d06bdc118e40dd83ef9080682279fc12 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:17:24 +0000 Subject: [PATCH 17/25] convert: refuse axes that contradict an RGB header Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp99saj5j4QZfMeAZQUm --- CHANGELOG.md | 4 ++++ docs/user_guide.md | 1 + .../conversion_issues.py | 14 ++++++++++++++ .../conversion_plan.py | 16 ++++++++++++++++ tests/test_convert.py | 15 +++++++++++++++ 5 files changed, 50 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 818440f0..b855f709 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,10 @@ refuses the skipped label images as unrecorded: refused, never silently wrong. ### Fixed +- **`convert` refuses axis roles that put an RGB image's colours on rows or columns** + (`rgb_axes_contradict_header`, independent review of v0.10.1). `--axes CYX` on an RGB TIFF + (stored `YXS`) was written as channels of mixed colours and rows; the conversion now stops + before anything is written and names `--axes YXC`. - **OME-Zarr copies are written in spatial chunks, so a later brick can read them in windows.** `convert --store ome-zarr`, the notebook's OME-Zarr copy and `convert_experiment(..., store="ome-zarr")` wrote each plane as one chunk (the whole Y and X). A windowed route diff --git a/docs/user_guide.md b/docs/user_guide.md index 46c971e3..6f93b3cc 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1797,6 +1797,7 @@ continues. | `copy_folder_overlaps_masks` | Error | `convert`: the folder for the copies is the masks folder, inside it, or holds it; copies there would be read as masks. Choose a folder outside the masks folder. | | `copy_folder_not_a_folder` | Error | `convert`: the path given with `--to` is a file. Choose a folder. | | `copy_path_too_long` | Error | `convert` on Windows: a copy would have a file whose path, while it is written in the conversion's work folder, is longer than 259 characters, or a folder whose path is longer than 247, which Windows cannot handle. Nothing is written. Choose a folder for the copies with a shorter path, or shorten the names of the images or folders named. Not checked when Windows' long paths are enabled (the `LongPathsEnabled` setting). | +| `rgb_axes_contradict_header` | Error | `convert`: an image stored as RGB colour (three samples per pixel) was given axis roles that put the colour samples on another role than C, so the copies would mix colours with rows or columns (v0.10.1). Nothing is written. Give the stored order with the colours as C: an RGB TIFF stores them last, `--axes YXC`. | | `copy_names_collide` | Error | An OME-Zarr copy: two images of one folder differ only by their extension, so their copies would have the same name. Nothing is written. Rename or exclude one of them. | | `copy_folder_has_links` | Error | `convert`: the folder for the copies holds symbolic links (directory junctions on Windows) or mount points, named `link -> target`, through which the copies would be written elsewhere, perhaps over the originals. Nothing is written; remove them or choose a new, empty folder. | | `copy_folder_unreadable` | Error | `convert`: a folder below the folder for the copies cannot be read, or disappeared while it was checked, so it cannot be checked for links or mount points; it is named. Nothing is written. Make it readable or remove it, or choose a new, empty folder. | diff --git a/src/morphobricks_preprocessing/conversion_issues.py b/src/morphobricks_preprocessing/conversion_issues.py index 8146bf48..7b26889e 100644 --- a/src/morphobricks_preprocessing/conversion_issues.py +++ b/src/morphobricks_preprocessing/conversion_issues.py @@ -316,3 +316,17 @@ def lock_issue(exc: OutputLockedError) -> ValidationIssue: "Wait for it to finish. If none is going on (it was stopped or the computer " f"restarted), remove the lock: {removal}", ) + + +def rgb_axes_issue(paths: list[str]) -> ValidationIssue: + """Refuse axis roles that put an RGB TIFF's colour samples on another role than C.""" + return error( + "rgb_axes_contradict_header", + f"{plural(len(paths), 'image')} {agree(paths, 'is', 'are')} stored as RGB colour " + "(three samples per pixel), but the axis roles given put the colour samples on " + "another role than C, so the copies would mix colours with image rows or columns. " + "Nothing was written.", + paths, + "Give the stored order of these images with the colour samples as C: an RGB TIFF " + "stores its colours last, so --axes YXC.", + ) diff --git a/src/morphobricks_preprocessing/conversion_plan.py b/src/morphobricks_preprocessing/conversion_plan.py index bb69d706..74b5659f 100644 --- a/src/morphobricks_preprocessing/conversion_plan.py +++ b/src/morphobricks_preprocessing/conversion_plan.py @@ -40,6 +40,7 @@ overlap_issue, path_too_long_issue, pixel_type_issue, + rgb_axes_issue, ) from .conversion_record import CONVERTED, COPIED, PROJECTED, RECORD_FILENAME, CopyEntry from .conversion_write import WORK_FOLDER, partial_path @@ -166,6 +167,7 @@ def _plan( for rel, meta in headers.items() if rel in review.file_mappings and not meta.is_ome_zarr } + issues += _rgb_contradictions(to_convert, headers, review.file_mappings) issues += _cannot_convert(root, to_convert, headers, review.file_mappings, memory_limit) if has_errors(issues): return (), issues @@ -180,6 +182,20 @@ def _plan( return _stored(tuple(planned), issues, as_zarr) +def _rgb_contradictions( + to_convert: set[str], headers: dict[str, TiffMetadata], mappings: dict[str, AxisMapping] +) -> list[ValidationIssue]: + """Refuse the RGB TIFFs whose colour samples (``S``) are given another role than C.""" + wrong = sorted( + rel + for rel in to_convert + if headers[rel].rgb_samples + and "S" in mappings[rel].axes + and mappings[rel].roles[mappings[rel].axes.index("S")] != "C" + ) + return [rgb_axes_issue(wrong)] if wrong else [] + + WINDOWS_MAX_PATH = 259 """The longest path Windows handles without long-path support (``MAX_PATH`` 260, with the terminating NUL).""" diff --git a/tests/test_convert.py b/tests/test_convert.py index c27f90cc..9bcf87c4 100644 --- a/tests/test_convert.py +++ b/tests/test_convert.py @@ -409,6 +409,21 @@ def test_an_rgb_image_with_swapped_y_and_x_is_written_as_channel_pages(tmp_path) assert_bitwise_equal(source, mapping, copy) +def test_axes_that_put_an_rgb_images_colours_on_rows_are_refused_before_writing(tmp_path): + # Independent review of v0.10.1 (P0): --axes CYX on an RGB TIFF (stored YXS) used to be + # written as 6 "channels" of 9 x 3 pixels, mixing colours with rows and columns. + source = tmp_path / "exp" / "img.tif" + source.parent.mkdir(parents=True) + tifffile.imwrite( + source, pixels((6, 9, 3), np.uint8), photometric="rgb", metadata={"axes": "YXS"} + ) + result = convert(tmp_path, AxisMapping("YXS", ("C", "Y", "X"))) + assert not result.written and not (tmp_path / "copies" / "img.tif").exists() + refused = [i for i in result.issues if i.is_error] + assert [i.code for i in refused] == ["rgb_axes_contradict_header"] + assert refused[0].paths == ("img.tif",) and "--axes YXC" in refused[0].action + + def test_planes_that_cannot_be_read_within_the_memory_limit_stop_it_before_writing(tmp_path): # Review of PP-11 (issue #76's criterion): the memory budget fails fast. It used to be # found while writing, after the copies before it were written. From acc5d3019811e4e76911c272de005aa6620957d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:18:19 +0000 Subject: [PATCH 18/25] describe --publish: exit 1 when the headers contradict the description Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp99saj5j4QZfMeAZQUm --- CHANGELOG.md | 2 ++ docs/user_guide.md | 3 ++- src/morphobricks_preprocessing/cli_describe.py | 2 +- tests/test_notebook_prerelease.py | 4 +++- 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b855f709..5795029b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ refuses the skipped label images as unrecorded: refused, never silently wrong. ### Fixed +- **`describe --publish` exits with status 1 when the image headers contradict the published + description** (it printed "Nothing to publish" and exited 0, so a script read it as a success). - **`convert` refuses axis roles that put an RGB image's colours on rows or columns** (`rgb_axes_contradict_header`, independent review of v0.10.1). `--axes CYX` on an RGB TIFF (stored `YXS`) was written as channels of mixed colours and rows; the conversion now stops diff --git a/docs/user_guide.md b/docs/user_guide.md index 6f93b3cc..ff46d42a 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1084,7 +1084,8 @@ given in the notebook), so `--publish` publishes nothing from a draft made of fo lists what is missing. For a published description that matches the folders it says `Nothing to publish` and exits with status 0; for one whose only change is in the image headers, it says that no answer is -missing and that the run stops until the headers fit, and exits with status 0; for one that +missing and that the run stops until the headers fit, and exits with status 1 (v0.10.1: a +header contradiction is never reported as a success); for one that no longer matches otherwise, it lists the new, gone or changed folders and leaves the file as it is. Like the other commands, `describe` exits with status 1 when it reports an error (an experiment folder that is not found, an unreadable description) and 0 otherwise. diff --git a/src/morphobricks_preprocessing/cli_describe.py b/src/morphobricks_preprocessing/cli_describe.py index f49ecfad..d801a7f8 100644 --- a/src/morphobricks_preprocessing/cli_describe.py +++ b/src/morphobricks_preprocessing/cli_describe.py @@ -269,7 +269,7 @@ def describe_command(args: argparse.Namespace) -> int: "Nothing to publish: no answer is missing. The run stops until the image headers " "fit the published description (headers changed, above)." ) - return 0 + return 1 # a header contradiction is never a success (review of v0.10.1) if not blockers: print("Nothing to publish: the published description matches the folders.") return 0 diff --git a/tests/test_notebook_prerelease.py b/tests/test_notebook_prerelease.py index 4a56698e..901bd1f9 100644 --- a/tests/test_notebook_prerelease.py +++ b/tests/test_notebook_prerelease.py @@ -264,7 +264,9 @@ def test_the_cli_reports_a_header_only_rewrite_as_the_notebook_does(exp, capsys) assert "must be confirmed again" not in printed assert "headers changed: ctrl / rep1 / single" in printed assert "the run stops until they do" in printed - assert main(["describe", str(root), "--output", str(out), "--publish"]) == 0 + assert ( + main(["describe", str(root), "--output", str(out), "--publish"]) == 1 + ) # the headers contradict it: exit status 1 printed = capsys.readouterr().out assert f"repeat {rid}: confirm it again" not in printed and "Not published" not in printed assert "Nothing to publish: no answer is missing. The run stops until" in printed From d1702a3e47e9f5ecfa0acc53885576d3c3132aea Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:19:12 +0000 Subject: [PATCH 19/25] describe: refuse fast-mode options for a published description Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp99saj5j4QZfMeAZQUm --- CHANGELOG.md | 4 ++++ docs/user_guide.md | 4 +++- .../cli_describe.py | 22 +++++++++++++++++++ tests/test_cli_usability.py | 15 +++++++++++++ 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5795029b..2bfb9d66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,10 @@ refuses the skipped label images as unrecorded: refused, never silently wrong. ### Fixed +- **`describe` refuses the fast-mode options (`--channels`, `--image-type`, `--accept-ids`, + `--comparable`, `--confirmed-on`) for an output folder whose description is published**: they + were ignored, so a changed channel list looked accepted. Nothing is written; the message names + the options, the notebook and another output folder. - **`describe --publish` exits with status 1 when the image headers contradict the published description** (it printed "Nothing to publish" and exited 0, so a script read it as a success). - **`convert` refuses axis roles that put an RGB image's colours on rows or columns** diff --git a/docs/user_guide.md b/docs/user_guide.md index ff46d42a..25027da7 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1085,7 +1085,9 @@ lists what is missing. For a published description that matches the folders it says `Nothing to publish` and exits with status 0; for one whose only change is in the image headers, it says that no answer is missing and that the run stops until the headers fit, and exits with status 1 (v0.10.1: a -header contradiction is never reported as a success); for one that +header contradiction is never reported as a success); the fast-mode options (`--channels`, `--image-type`, +`--accept-ids`, `--comparable`, `--confirmed-on`) are refused for a published description, which +`describe` never changes (v0.10.1); for one that no longer matches otherwise, it lists the new, gone or changed folders and leaves the file as it is. Like the other commands, `describe` exits with status 1 when it reports an error (an experiment folder that is not found, an unreadable description) and 0 otherwise. diff --git a/src/morphobricks_preprocessing/cli_describe.py b/src/morphobricks_preprocessing/cli_describe.py index d801a7f8..06c37f79 100644 --- a/src/morphobricks_preprocessing/cli_describe.py +++ b/src/morphobricks_preprocessing/cli_describe.py @@ -99,6 +99,12 @@ "--id names the IDs of a new fast-mode description; a published description, or the " "strict mode, names them in the notebook. Nothing was written." ) +PUBLISHED_UNCHANGED = ( + "{options} would change the published description in {output}, which describe never " + "changes. Nothing was written. To check the experiment against it, repeat the command " + "without these options. To change it, open the notebook's Describe step; or publish a " + "new description into another output folder (--output)." +) NOT_IN_DRAFT = ( "the channels of each acquisition, the image type and the meaning of the masks are not " "part of this draft and are answered in the notebook; the command line cannot publish " @@ -253,6 +259,10 @@ def describe_command(args: argparse.Namespace) -> int: lines, blockers = draft_lines(draft, root), draft_blockers(draft) if not args.strict: lines.append(FAST_HINT) + given = _fast_options_given(args) + if found is not None and given: # never silently ignored (review of v0.10.1) + print(PUBLISHED_UNCHANGED.format(options=", ".join(given), output=output)) + return 1 if found is not None and args.id: # never silently ignored print(ID_ONLY_NEW) return 1 @@ -409,6 +419,18 @@ def _image_units(discovery: DiscoveryResult) -> dict[str, tuple[str, str, str]]: return {image: leaf.labels for leaf in discovery.leaves for image in leaf.images} + +def _fast_options_given(args: argparse.Namespace) -> list[str]: + """Return the fast-mode statements given, which only a new description can take.""" + given = { + "--channels": args.channels is not None, + "--image-type": args.image_type is not None, + "--accept-ids": args.accept_ids, + "--comparable": args.comparable, + "--confirmed-on": args.confirmed_on is not None, + } + return [name for name, used in given.items() if used] + def _publish_fast( draft: Draft, answers: DraftAnswers, diff --git a/tests/test_cli_usability.py b/tests/test_cli_usability.py index 36ab6972..7482a6d8 100644 --- a/tests/test_cli_usability.py +++ b/tests/test_cli_usability.py @@ -437,6 +437,21 @@ def test_describe_id_is_refused_for_a_published_or_strict_description(tmp_path, assert "--id names the IDs of a new fast-mode description" in capsys.readouterr().out +def test_describe_refuses_fast_options_that_would_change_a_published_description(tmp_path, capsys): + # Independent review of v0.10.1: --channels and the other fast-mode statements were ignored + # for a published description, so a changed channel list looked accepted. + root, out = tmp_path / "exp", tmp_path / "out" + _ome(root / "CTRL" / "rep1" / "img.ome.tif") + assert main(["describe", str(root), "--output", str(out), *CHANNELS, "--publish"]) == 0 + before = (out / DESCRIPTION_FILENAME).read_bytes() + capsys.readouterr() + assert main(["describe", str(root), "--output", str(out), *CHANNELS, "--publish"]) == 1 + printed = capsys.readouterr().out + assert "--channels" in printed and "would change the published description" in printed + assert (out / DESCRIPTION_FILENAME).read_bytes() == before + assert main(["describe", str(root), "--output", str(out), "--publish"]) == 0 + + # --- 5. and 6. RGB as OME-Zarr: convert --store ome-zarr, then the suggestion --------------- From e1477466efb4f12528c29e0bae14746e601b6796 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:20:11 +0000 Subject: [PATCH 20/25] declare-masks: check --ignore before declaring, so both apply or neither Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp99saj5j4QZfMeAZQUm --- CHANGELOG.md | 3 ++ .../cli_declare_masks.py | 8 ++- .../mask_declare.py | 53 ++++++++++++++----- tests/test_cli_usability.py | 16 ++++++ 4 files changed, 66 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bfb9d66..29a8d876 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,9 @@ refuses the skipped label images as unrecorded: refused, never silently wrong. ### Fixed +- **`declare-masks --type ... --ignore ...` either applies both or neither**: the `--ignore` + values (names, a type also declared, a missing output folder, an unreadable + `ignored_masks.toml`) are checked before any type is declared (`mask_declare.check_ignore`). - **`describe` refuses the fast-mode options (`--channels`, `--image-type`, `--accept-ids`, `--comparable`, `--confirmed-on`) for an output folder whose description is published**: they were ignored, so a changed channel list looked accepted. Nothing is written; the message names diff --git a/src/morphobricks_preprocessing/cli_declare_masks.py b/src/morphobricks_preprocessing/cli_declare_masks.py index b4e1c7fd..db4db417 100644 --- a/src/morphobricks_preprocessing/cli_declare_masks.py +++ b/src/morphobricks_preprocessing/cli_declare_masks.py @@ -28,6 +28,7 @@ from .mask_declare import ( MaskDeclaration, MaskDeclarationRefused, + check_ignore, declare_masks, declared_types, ignore_masks, @@ -115,12 +116,17 @@ def declare_masks_command(args: argparse.Namespace) -> int: return 1 try: declarations = [parse_type(text) for text in args.types] + if args.ignore: # refused before anything is declared: both apply or neither + declaring = {item.source_type for item in declarations} + check_ignore( + args.output, args.ignore, declared={*declared_types(args.output), *declaring} + ) done = ( declare_masks(args.output, declarations, masks_folder=args.masks) if declarations else None ) - except (ValueError, MaskDeclarationRefused) as exc: + except (ValueError, MaskDeclarationRefused, OutputLockedError, OSError) as exc: return _refused(exc, "Nothing was written.") try: ignored, changed = ignore_masks( diff --git a/src/morphobricks_preprocessing/mask_declare.py b/src/morphobricks_preprocessing/mask_declare.py index ac0df19c..bb715fb9 100644 --- a/src/morphobricks_preprocessing/mask_declare.py +++ b/src/morphobricks_preprocessing/mask_declare.py @@ -257,8 +257,42 @@ def ignore_masks( IgnoredMasksError A refused name, a declared type asked to be ignored, or a file that cannot be read. """ - add = tuple(add) - declared = set(declared) + add, declared = tuple(add), set(declared) + folder = check_ignore(output_folder, add, declared=declared, read=False) + with output_lock(folder): + before = read_ignored(folder).types + after = tuple(sorted((set(before) | set(add)) - declared)) + if after == before: + return after, False + path = folder / IGNORED_FILENAME + if after: + write_text_atomic(path, ignored_text(after)) + else: + path.unlink() + return after, True + + +def check_ignore( + output_folder: str | os.PathLike, + add: Iterable[str] = (), + *, + declared: Iterable[str] = (), + read: bool = True, +) -> Path: + """Refuse what :func:`ignore_masks` would refuse, writing nothing; return the folder. + + ``declare-masks`` calls it before declaring anything, with the types about to be declared + in ``declared``, so ``--type`` and ``--ignore`` given together either both apply or + neither does (review of v0.10.1). With ``read``, the ignore list is read too, so an + unreadable file is refused first. + + Raises + ------ + IgnoredMasksError + A refused name, a declared type asked to be ignored, a missing output folder or (with + ``read``) an ignore list that cannot be read. + """ + add, declared = tuple(add), set(declared) for name in add: if name_problem(name) is not None: raise IgnoredMasksError(f"--ignore {name!r}: {name_problem(name)}") @@ -271,20 +305,13 @@ def ignore_masks( folder = Path(output_folder) if not folder.is_dir(): raise IgnoredMasksError(f"The output folder {folder} does not exist.") - with output_lock(folder): - before = read_ignored(folder).types - after = tuple(sorted((set(before) | set(add)) - declared)) - if after == before: - return after, False - path = folder / IGNORED_FILENAME - if after: - write_text_atomic(path, ignored_text(after)) - else: - path.unlink() - return after, True + if read: + read_ignored(folder) + return folder __all__ = [ + "check_ignore", "DeclaredMasks", "MaskDeclaration", "MaskDeclarationRefused", diff --git a/tests/test_cli_usability.py b/tests/test_cli_usability.py index 7482a6d8..21081ba5 100644 --- a/tests/test_cli_usability.py +++ b/tests/test_cli_usability.py @@ -19,6 +19,8 @@ from morphobricks_preprocessing.cli import main from morphobricks_preprocessing.description import description_from_bytes from morphobricks_preprocessing.description_file import DESCRIPTION_FILENAME +from morphobricks_preprocessing.mask_declare import declared_types +from morphobricks_preprocessing.run.description_run import load_description DAY = "2026-12-03" YES = ["--accept-ids", "--comparable", "--confirmed-on", DAY] @@ -295,6 +297,20 @@ def test_declaring_an_ignored_type_takes_it_off_the_list_and_both_at_once_is_ref assert "Give at least one --type" in capsys.readouterr().out +def test_a_refused_ignore_declares_nothing_given_with_type(tmp_path, capsys): + # Review of v0.10.1: --type was published and then --ignore refused, leaving half a change. + _, out = _labelled(tmp_path) + found, _ = load_description(out) + before = (out / DESCRIPTION_FILENAME).read_bytes() if found is not None else None + capsys.readouterr() + command = ["declare-masks", "--output", str(out), "--type", "cells=instances"] + assert main([*command, "--ignore", "bad/name"]) == 1 + assert "Nothing was written." in capsys.readouterr().out + after = (out / DESCRIPTION_FILENAME).read_bytes() if found is not None else None + assert after == before and "cells" not in declared_types(out) + assert not (out / "ignored_masks.toml").exists() + + def test_an_invalid_ignore_file_stops_check_and_run(tmp_path, capsys): root, out = _labelled(tmp_path) capsys.readouterr() From 0ad63adbbc4e0442b35f82c614971766614b7db4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:21:17 +0000 Subject: [PATCH 21/25] tissue-mask: check the rule, the extra and the images before creating a masks folder Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp99saj5j4QZfMeAZQUm --- CHANGELOG.md | 3 +++ .../cli_tissue_mask.py | 24 +++++++++++++++++++ tests/test_cli_tissue_mask.py | 16 +++++++++++++ 3 files changed, 43 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29a8d876..80b35fec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,9 @@ refuses the skipped label images as unrecorded: refused, never silently wrong. ### Fixed +- **`tissue-mask` checks the rule, the `he-mask` extra and every image before it creates a masks + folder**: a refusal (scikit-image missing, an image not declared rgb or not 8-bit RGB) used to + come after the folder was created and recorded in the run manifest. - **`declare-masks --type ... --ignore ...` either applies both or neither**: the `--ignore` values (names, a type also declared, a missing output folder, an unreadable `ignored_masks.toml`) are checked before any type is declared (`mask_declare.check_ignore`). diff --git a/src/morphobricks_preprocessing/cli_tissue_mask.py b/src/morphobricks_preprocessing/cli_tissue_mask.py index 6f5d3611..8df16ae0 100644 --- a/src/morphobricks_preprocessing/cli_tissue_mask.py +++ b/src/morphobricks_preprocessing/cli_tissue_mask.py @@ -21,6 +21,7 @@ import argparse import shlex +from .he_tissue_mask import current_rule, resolved_fov from .plane_errors import PlaneReadError from .run_inputs import RunInputs from .run_inputs_tissue import ( @@ -101,6 +102,10 @@ def tissue_mask_command(args: argparse.Namespace) -> int: f"{run.masks_root}, where the tissue masks go. Nothing was written." ) return 1 + refused = _prerequisites(run, images, args.rule) + if refused is not None: # checked before a masks folder is created (review of v0.10.1) + print(refused) + return 1 if run.masks_root is None: try: run = create_masks_folder(run, args.masks).run @@ -135,6 +140,25 @@ def tissue_mask_command(args: argparse.Namespace) -> int: return 0 +def _prerequisites(run: RunInputs, images: tuple[str, ...], rule: str) -> str | None: + """Return the first refusal of the rule, scikit-image or an image; None when all are met. + + Nothing is read or written: the images are checked from the run's records (declared rgb, + 8-bit, three channels, one plane), the rule and the ``he-mask`` extra by + :func:`.he_tissue_mask.current_rule`. + """ + try: + current_rule(rule) + except (TypeError, ValueError, ImportError) as exc: + return f"No tissue mask written; nothing was created. {exc}" + for image in images: + try: + resolved_fov(run, image) + except ValueError as exc: # RunInputsError included + return _refusal(image, exc) + return None + + def _refusal(image: str, exc: Exception) -> str: """Return the refusal of one image, naming the image once (a message may name it already).""" text = str(exc).removeprefix(f"{image}: ") diff --git a/tests/test_cli_tissue_mask.py b/tests/test_cli_tissue_mask.py index 78edc1f1..91482305 100644 --- a/tests/test_cli_tissue_mask.py +++ b/tests/test_cli_tissue_mask.py @@ -133,6 +133,22 @@ def refuse(self, *args, **kwargs): # --- No masks folder: created and recorded (owner, 4 December 2026) -------------------------- +def test_a_missing_extra_is_refused_before_a_masks_folder_is_created(tmp_path, capsys, monkeypatch): + # Review of v0.10.1: the masks folder was created and recorded, then scikit-image refused. + from morphobricks_preprocessing import he_tissue_mask as helper + + run = rgb_run(tmp_path, masks=False) + manifest = (run.output_folder / "run_manifest.json").read_bytes() + monkeypatch.setitem(sys.modules, "skimage", None) + monkeypatch.setattr(helper, "hed_matrix", helper.hed_matrix.__wrapped__) + args = ["tissue-mask", "--output", str(run.output_folder), "--to", "HETissue"] + assert main(args) == 1 + printed = capsys.readouterr().out + assert "he-mask" in printed and "nothing was created" in printed + assert not (tmp_path / "experiment_masks").exists() + assert (run.output_folder / "run_manifest.json").read_bytes() == manifest + + def test_a_run_without_masks_folder_gets_one_recorded_as_run_masks_would( tmp_path, capsys, monkeypatch ): From 1b816c3835cd054b0b84e5c098340e15a3d444c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:21:59 +0000 Subject: [PATCH 22/25] describe: point to the notebook for repeats that are not comparable Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp99saj5j4QZfMeAZQUm --- CHANGELOG.md | 2 ++ src/morphobricks_preprocessing/cli_describe.py | 4 ++-- src/morphobricks_preprocessing/fast_answers.py | 4 +++- tests/test_cli_usability.py | 12 ++++++++++++ 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80b35fec..730e8a2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ refuses the skipped label images as unrecorded: refused, never silently wrong. ### Fixed +- **Without `--comparable`, `describe` says where to answer for repeats that are not comparable**: + the notebook's *Check and save* card (step 1); the command line has no answer for them. - **`tissue-mask` checks the rule, the `he-mask` extra and every image before it creates a masks folder**: a refusal (scikit-image missing, an image not declared rgb or not 8-bit RGB) used to come after the folder was created and recorded in the run manifest. diff --git a/src/morphobricks_preprocessing/cli_describe.py b/src/morphobricks_preprocessing/cli_describe.py index 06c37f79..2b9bb464 100644 --- a/src/morphobricks_preprocessing/cli_describe.py +++ b/src/morphobricks_preprocessing/cli_describe.py @@ -102,7 +102,7 @@ PUBLISHED_UNCHANGED = ( "{options} would change the published description in {output}, which describe never " "changes. Nothing was written. To check the experiment against it, repeat the command " - "without these options. To change it, open the notebook's Describe step; or publish a " + "without these options. To change it, use the notebook's step 1 (Check and save); or publish a " "new description into another output folder (--output)." ) NOT_IN_DRAFT = ( @@ -419,7 +419,6 @@ def _image_units(discovery: DiscoveryResult) -> dict[str, tuple[str, str, str]]: return {image: leaf.labels for leaf in discovery.leaves for image in leaf.images} - def _fast_options_given(args: argparse.Namespace) -> list[str]: """Return the fast-mode statements given, which only a new description can take.""" given = { @@ -431,6 +430,7 @@ def _fast_options_given(args: argparse.Namespace) -> list[str]: } return [name for name, used in given.items() if used] + def _publish_fast( draft: Draft, answers: DraftAnswers, diff --git a/src/morphobricks_preprocessing/fast_answers.py b/src/morphobricks_preprocessing/fast_answers.py index 044f0bb9..78a51d04 100644 --- a/src/morphobricks_preprocessing/fast_answers.py +++ b/src/morphobricks_preprocessing/fast_answers.py @@ -107,7 +107,9 @@ def _statements( if not comparable: blockers.append( "say that every biological repeat's folders were prepared and acquired under the " - "same circumstances (--comparable)" + "same circumstances (--comparable). If some were not, do not give --comparable: " + "answer for each biological repeat on the notebook's Check and save card (step 1), " + "which records the repeats that are not comparable" ) if confirmed_on is None or not valid_day(confirmed_on): blockers.append("give the day of your statements as YYYY-MM-DD (--confirmed-on)") diff --git a/tests/test_cli_usability.py b/tests/test_cli_usability.py index 21081ba5..650e2078 100644 --- a/tests/test_cli_usability.py +++ b/tests/test_cli_usability.py @@ -297,6 +297,18 @@ def test_declaring_an_ignored_type_takes_it_off_the_list_and_both_at_once_is_ref assert "Give at least one --type" in capsys.readouterr().out +def test_without_comparable_the_blocker_points_to_the_notebook(tmp_path, capsys): + # Review of v0.10.1: a repeat that is not comparable has no command-line answer. + root, out = tmp_path / "exp", tmp_path / "out" + _ome(root / "CTRL" / "rep1" / "img.ome.tif") + command = ["describe", str(root), "--output", str(out), "--channels", "DNA,ACTIN"] + rest = ["--image-type", "channels", "--accept-ids", "--confirmed-on", DAY, "--publish"] + assert main([*command, *rest]) == 1 + printed = capsys.readouterr().out + assert "--comparable" in printed and "Check and save card" in printed + assert not (out / DESCRIPTION_FILENAME).exists() + + def test_a_refused_ignore_declares_nothing_given_with_type(tmp_path, capsys): # Review of v0.10.1: --type was published and then --ignore refused, leaving half a change. _, out = _labelled(tmp_path) From 4dd8c774d8eefd0a2f9482e25275e463e91c1ffb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:24:25 +0000 Subject: [PATCH 23/25] check: use the earlier run's exclusions and masks folder, as run does Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp99saj5j4QZfMeAZQUm --- CHANGELOG.md | 3 ++ docs/user_guide.md | 4 ++- src/morphobricks_preprocessing/cli.py | 46 +++++++++++++++++++++------ tests/test_check_reuses_run.py | 44 +++++++++++++++++++++++++ 4 files changed, 87 insertions(+), 10 deletions(-) create mode 100644 tests/test_check_reuses_run.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 730e8a2d..b2f05a47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,9 @@ refuses the skipped label images as unrecorded: refused, never silently wrong. ### Fixed +- **`check` checks what the next `run` reads**: without `--exclude` and `--masks`, it takes the + earlier run's exclusions and masks folder, as `run` does, and says so. A check of an output + folder whose run used `--masks` checked no masks before. - **Without `--comparable`, `describe` says where to answer for repeats that are not comparable**: the notebook's *Check and save* card (step 1); the command line has no answer for them. - **`tissue-mask` checks the rule, the `he-mask` extra and every image before it creates a masks diff --git a/docs/user_guide.md b/docs/user_guide.md index 25027da7..6ef980e6 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -858,7 +858,9 @@ morphobricks-preprocessing check /data/exp1 prints what will be analysed, the label tree, the number of images per condition and biological repeat (with `!` marking unbalanced ones), the problems found and the -suggested axis roles, for example `--axes ZCYX`. Then: +suggested axis roles, for example `--axes ZCYX`. In an output folder that already holds a run, +`check` without `--exclude` or `--masks` uses that run's exclusions and masks folder, as the next +`run` does, and says so (v0.10.1). Then: ```bash morphobricks-preprocessing run /data/exp1 --axes ZCYX diff --git a/src/morphobricks_preprocessing/cli.py b/src/morphobricks_preprocessing/cli.py index 6ff42a8e..381f030a 100644 --- a/src/morphobricks_preprocessing/cli.py +++ b/src/morphobricks_preprocessing/cli.py @@ -67,6 +67,7 @@ from .discovery import default_output_folder from .image_type import review_image_type from .log_target import log_refusal, run_log_refusal +from .manifest import RunManifest from .mask_text import mask_summary from .masks import mask_axes_option from .physical_check import undeclared_mask_types @@ -287,21 +288,16 @@ def _check(args: argparse.Namespace) -> int: return 1 # As 'run' reads images lacking some axes (F10); no Z or T size without the axis. recorded = recorded_run(args) + reused_inputs = _reuse_recorded_inputs(args, recorded) missing = missing_as_singleton(args, recorded) pre, review = suggested_review(command_preflight(args), missing_as_singleton=missing) + if reused_inputs: + print(reused_inputs, end="\n\n") print(preflight_summary(pre)) if pre.discovery.leaves: print() print(label_tree(pre.discovery)) - if pre.masks is not None: - print() - print(mask_summary(pre.masks)) - if pre.dataset.balance.cells: - print() - print(balance_summary(pre.dataset.balance)) - if pre.calibration.calibration is not None: - print() - print(calibration_summary(pre.calibration.calibration)) + _print_found(pre) if pre.issues: print() print(format_issues(pre.issues)) @@ -344,6 +340,38 @@ def _check(args: argparse.Namespace) -> int: return 1 if blocked else 0 # every error printed exits with 1, as 'run' does +def _print_found(pre: Preflight) -> None: + """Print the masks, the balance of the design and the calibration the preflight found.""" + if pre.masks is not None: + print(f"\n{mask_summary(pre.masks)}") + if pre.dataset.balance.cells: + print(f"\n{balance_summary(pre.dataset.balance)}") + if pre.calibration.calibration is not None: + print(f"\n{calibration_summary(pre.calibration.calibration)}") + + +def _reuse_recorded_inputs(args: argparse.Namespace, recorded: RunManifest | None) -> str: + """Take the earlier run's exclusions and masks folder where none is given, as ``run`` does. + + ``check`` then checks what ``run`` would read (review of v0.10.1): without this, a check + of an output folder whose run used a masks folder or exclusions checked other inputs than + the next run. Returns the line saying what was taken over ("" when nothing was). + """ + if recorded is None: + return "" + taken = [] + if not args.exclude and recorded.settings.exclude: + args.exclude = list(recorded.settings.exclude) + taken.append(f"{len(args.exclude)} excluded image(s)") + folder = (recorded.masks or {}).get("folder") + if args.masks is None and folder: + args.masks = folder + taken.append(f"the masks folder {folder}") + if not taken: + return "" + return f"Checking with what the earlier run used, as the next run will: {' and '.join(taken)}." + + def undeclared_mask_issues(args: argparse.Namespace, pre: Preflight) -> list[ValidationIssue]: """Return ``run``'s refusal of every mask type found that the description does not declare. diff --git a/tests/test_check_reuses_run.py b/tests/test_check_reuses_run.py new file mode 100644 index 00000000..fd39a53c --- /dev/null +++ b/tests/test_check_reuses_run.py @@ -0,0 +1,44 @@ +"""``check`` takes the earlier run's masks folder and exclusions, as ``run`` does (v0.10.1). + +Independent review of v0.10.1: a check of an output folder whose run used ``--masks`` checked +no masks, so it did not check what the next run reads. +""" + +import pytest + +from morphobricks_preprocessing.cli import main +from morphobricks_preprocessing.testing import make_clean_run + + +@pytest.fixture +def clean(tmp_path): + return make_clean_run( + tmp_path / "run", axes="YX", shape=(16, 20), mask_types=("Cells",), design=True + ) + + +def test_check_uses_the_recorded_masks_folder(clean, capsys): + capsys.readouterr() + assert main(["check", str(clean.experiment), "--output", str(clean.output)]) == 0 + printed = capsys.readouterr().out + assert ( + "Checking with what the earlier run used, as the next run will: " + f"the masks folder {clean.masks}" in printed + ) + assert "Masks: 1 mask type for 4 images" in printed + + +def test_check_uses_the_recorded_exclusions(clean, capsys): + command = ["run", str(clean.experiment), "--output", str(clean.output)] + assert main([*command, "--exclude", "ctrl/rep1/a.ome.tif"]) == 0 + capsys.readouterr() + assert main(["check", str(clean.experiment), "--output", str(clean.output)]) == 0 + printed = capsys.readouterr().out + assert "1 excluded image(s)" in printed and "Images to analyse: 3" in printed + + +def test_a_given_masks_folder_is_used_as_given(clean, capsys): + capsys.readouterr() + args = ["check", str(clean.experiment), "--output", str(clean.output)] + assert main([*args, "--masks", str(clean.masks)]) == 0 + assert "Checking with what the earlier run used" not in capsys.readouterr().out From fdd838b7934257bfd08f5b4f02302844ea11a7fb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 18:28:44 +0200 Subject: [PATCH 24/25] Fix the full-suite failures #627's wording left - describe_ids.REASONS and description_run_text._MEANINGS keyed by the Code / Refusal constants of description_rules, not code strings, and _meaning reads a code's family instead of matching code prefixes: the Spec's "no second copy of the rules" scan (test_spec_no_fallback) allows code tables only in description_rules.py. - test_description_write_types and test_calibrate_containment expect the new wording ("of type numpy.bool, E_TYPE)", "Calibration saved to"). Co-Authored-By: Claude Opus 5.5 --- .../describe_ids.py | 17 ++++--- .../description_run_text.py | 50 ++++++++++--------- tests/test_calibrate_containment.py | 2 +- tests/test_description_write_types.py | 2 +- 4 files changed, 37 insertions(+), 34 deletions(-) diff --git a/src/morphobricks_preprocessing/describe_ids.py b/src/morphobricks_preprocessing/describe_ids.py index 4475c13c..f34fc1dd 100644 --- a/src/morphobricks_preprocessing/describe_ids.py +++ b/src/morphobricks_preprocessing/describe_ids.py @@ -18,6 +18,7 @@ import unicodedata from collections.abc import Collection, Iterable, Sequence +from .description_rules import Code, Refusal from .draft import Draft, DraftError from .draft_ids import IdKind, id_problems @@ -37,28 +38,28 @@ _RESERVED = "This name is reserved. Choose another identifier." _USED = "This identifier has already been used for another entry. Choose an unused identifier." REASONS: dict[str, str] = { - "E_FORBIDDEN_FIELD": _RESERVED, - "E_ID_RESERVED": _RESERVED, - "E_ID_SYNTAX": ( + Code.E_FORBIDDEN_FIELD: _RESERVED, + Code.E_ID_RESERVED: _RESERVED, + Code.E_ID_SYNTAX: ( "This identifier contains characters that are not permitted. Choose a valid identifier." ), - "E_ID_TEXT": ( + Code.E_ID_TEXT: ( "This identifier is empty, starts or ends with a space, or reads as a missing value " "(such as NA or none). Choose a valid identifier." ), - "E_ID_NOT_NFC": ( + Code.E_ID_NOT_NFC: ( "This identifier contains accented characters in a form that is not permitted (not " "Unicode NFC). Type it again, or choose another identifier." ), - "E_SINGLE_MISUSE": ( + Code.E_SINGLE_MISUSE: ( "'single' is kept, in lower case, for a level without its own folder. Choose another " "identifier." ), - "E_ID_CASE_COLLISION": ( + Code.E_ID_CASE_COLLISION: ( "This identifier differs from another identifier only in upper/lower case. Choose a " "distinct identifier." ), - "R_USED_ID_REUSED": _USED, + Refusal.R_USED_ID_REUSED: _USED, "id_in_use_in_draft": _USED, "in_use": _USED, } diff --git a/src/morphobricks_preprocessing/description_run_text.py b/src/morphobricks_preprocessing/description_run_text.py index b6d19334..e6ceadf5 100644 --- a/src/morphobricks_preprocessing/description_run_text.py +++ b/src/morphobricks_preprocessing/description_run_text.py @@ -182,27 +182,27 @@ def physical_issues( _MEANINGS = { - "E_FILE_ENCODING": "is not saved as UTF-8 text", - "E_TOML_SYNTAX": "is not valid TOML text", - "E_DUPLICATE_KEY": "names the same entry twice", - "E_SCHEMA_ID": "is not an experiment description of this format", - "E_SCHEMA_VERSION_MISSING": "does not say which format version it is", - "E_SCHEMA_VERSION_UNSUPPORTED": "is of a format version this release does not read", - "E_TYPE": "has a value of the wrong kind", - "E_UNKNOWN_FIELD": "has a field this release does not know", - "E_FORBIDDEN_FIELD": "has a field that is not allowed in it", - "E_MISSING_FIELD": "is missing a required field", - "E_EMPTY": "has an empty list or table", - "E_TEXT_EMPTY": "has an empty text", - "E_ENUM": "has a value that is not one of the allowed choices", - "E_DATE_FORMAT": "has a date that is not written as YYYY-MM-DD", - "E_VALUE_RANGE": "has a number out of its allowed range", - "E_REPEAT_UNCONFIRMED": "has a biological repeat that is not confirmed", - "E_UNKNOWN_CONDITION": "refers to a condition it does not define", - "E_UNKNOWN_CHANNEL": "refers to a channel it does not define", - "E_REFERENCE_UNKNOWN": "compares a condition against one it does not define", - "E_REFERENCE_SELF": "compares a condition against itself", - "E_REFERENCE_CYCLE": "has conditions compared against each other in a circle", + Code.E_FILE_ENCODING: "is not saved as UTF-8 text", + Code.E_TOML_SYNTAX: "is not valid TOML text", + Code.E_DUPLICATE_KEY: "names the same entry twice", + Code.E_SCHEMA_ID: "is not an experiment description of this format", + Code.E_SCHEMA_VERSION_MISSING: "does not say which format version it is", + Code.E_SCHEMA_VERSION_UNSUPPORTED: "is of a format version this release does not read", + Code.E_TYPE: "has a value of the wrong kind", + Code.E_UNKNOWN_FIELD: "has a field this release does not know", + Code.E_FORBIDDEN_FIELD: "has a field that is not allowed in it", + Code.E_MISSING_FIELD: "is missing a required field", + Code.E_EMPTY: "has an empty list or table", + Code.E_TEXT_EMPTY: "has an empty text", + Code.E_ENUM: "has a value that is not one of the allowed choices", + Code.E_DATE_FORMAT: "has a date that is not written as YYYY-MM-DD", + Code.E_VALUE_RANGE: "has a number out of its allowed range", + Code.E_REPEAT_UNCONFIRMED: "has a biological repeat that is not confirmed", + Code.E_UNKNOWN_CONDITION: "refers to a condition it does not define", + Code.E_UNKNOWN_CHANNEL: "refers to a channel it does not define", + Code.E_REFERENCE_UNKNOWN: "compares a condition against one it does not define", + Code.E_REFERENCE_SELF: "compares a condition against itself", + Code.E_REFERENCE_CYCLE: "has conditions compared against each other in a circle", } """What a reader code means, in plain words, after "The experiment description".""" @@ -211,11 +211,13 @@ def _meaning(code: str) -> str: """Say in plain words what a reader code means (a family's meaning for the others).""" if code in _MEANINGS: return _MEANINGS[code] - if code.startswith(("E_ID_", "E_SINGLE_")): + kind, _, rest = code.partition("_") # E_ID_SYNTAX: kind E, family ID + family = rest.partition("_")[0] + if kind == "E" and family in {"ID", "SINGLE"}: return "has an identifier that is not permitted" - if code.startswith("E_RGB_"): + if kind == "E" and family == "RGB": return "has colour (RGB) settings that do not agree" - if code.startswith("R_"): + if kind == "R": return "differs from what was published before in a way that is not allowed" return "breaks one of its rules" diff --git a/tests/test_calibrate_containment.py b/tests/test_calibrate_containment.py index be4b028b..91db1d87 100644 --- a/tests/test_calibrate_containment.py +++ b/tests/test_calibrate_containment.py @@ -82,7 +82,7 @@ def test_calibrate_writes_next_to_the_experiment(exp, tmp_path, capsys): assert read_calibration(output / CALIBRATION_FILENAME)[0].entries assert not (output / LOCK_FILENAME).exists() assert main(["calibrate", str(exp), *SIZE]) == 0 # the default output folder - assert "Written to" in capsys.readouterr().out + assert "Calibration saved to" in capsys.readouterr().out def test_calibrate_allows_a_prefix_sibling_of_the_experiment(exp, tmp_path, capsys): diff --git a/tests/test_description_write_types.py b/tests/test_description_write_types.py index 1a9b91cb..5bd2a429 100644 --- a/tests/test_description_write_types.py +++ b/tests/test_description_write_types.py @@ -189,7 +189,7 @@ def test_a_numpy_value_is_named_with_its_module_everywhere_the_type_is_shown( out.mkdir() build_experiment(root, _v01(), images=1) check = check_candidate(model, preflight(root, out), None) - assert f"of type {found})" in check.refusals[0].message + assert f"of type {found}, E_TYPE)" in check.refusals[0].message def _non_text_keys() -> list[tuple[Description, str]]: From 70e96492338ab494c3ffbc4e50e14fe688e2642c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 18:57:12 +0200 Subject: [PATCH 25/25] tissue-mask: import the H&E module only when the command runs #628 imported he_tissue_mask at the top of cli_tissue_mask, so a core-only install loaded morphobricks_normalization.stain and the H&E code on any CLI start (test_he_tissue_core_only failed). The import moves into _prerequisites. Co-Authored-By: Claude Opus 5.5 --- src/morphobricks_preprocessing/cli_tissue_mask.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/morphobricks_preprocessing/cli_tissue_mask.py b/src/morphobricks_preprocessing/cli_tissue_mask.py index fc9f0e62..1e471c5c 100644 --- a/src/morphobricks_preprocessing/cli_tissue_mask.py +++ b/src/morphobricks_preprocessing/cli_tissue_mask.py @@ -21,7 +21,6 @@ import argparse import shlex -from .he_tissue_mask import current_rule, resolved_fov from .plane_errors import PlaneReadError from .run_inputs import RunInputs from .run_inputs_tissue import ( @@ -175,8 +174,11 @@ def _prerequisites(run: RunInputs, images: tuple[str, ...], rule: str) -> str | Nothing is read or written: the images are checked from the run's records (declared rgb, 8-bit, three channels, one plane), the rule and the ``he-mask`` extra by - :func:`.he_tissue_mask.current_rule`. + :func:`.he_tissue_mask.current_rule`. That module is imported here, not at the top, so a + core-only install loads none of the H&E code until the command runs. """ + from .he_tissue_mask import current_rule, resolved_fov # noqa: PLC0415 + try: current_rule(rule) except (TypeError, ValueError, ImportError) as exc: