From 15d1e756d06bdc118e40dd83ef9080682279fc12 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:17:24 +0000 Subject: [PATCH 1/7] 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 2/7] 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 3/7] 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 4/7] 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 5/7] 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 6/7] 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 7/7] 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