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..7302b312 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,57 @@ 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, 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`, 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 (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 + `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`. 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: + `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/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. diff --git a/docs/user_guide.md b/docs/user_guide.md index 1d4ade7c..9e7e6a45 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1107,6 +1107,34 @@ 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`): 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 +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; 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 `--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`) Each image's pixel size (X and Y) and z-step (Z) come from its metadata. When the @@ -1193,6 +1221,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 +1383,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 +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) 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, 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 46f2fe5b..4db3a546 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,18 +316,34 @@ 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." ) - 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 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..61f83bbd 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. @@ -56,8 +59,8 @@ ) 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 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 from .metadata import inspect_images @@ -68,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, " @@ -76,6 +79,20 @@ "--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 " + "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 +161,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 +201,20 @@ 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 (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", ) - return describe def describe_command(args: argparse.Namespace) -> int: @@ -202,11 +239,16 @@ 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: # 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: return 0 @@ -245,12 +287,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 +305,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 +314,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 +335,48 @@ 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} + 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: + 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( @@ -310,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( @@ -342,8 +429,59 @@ 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) + 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. + + 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 +507,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 @@ -378,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/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..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 @@ -45,12 +46,21 @@ 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." ), } +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: @@ -69,7 +79,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 +100,11 @@ 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 + typed = shlex.quote(f"{issue.detail}=REPRESENTATION") + action = action.replace("TYPE=REPRESENTATION", typed) + return error(issue.code, _what(issue), paths, action) def fast_layout_issue(issues: Iterable[PhysicalIssue]) -> ValidationIssue: @@ -104,6 +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(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/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_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 2b5626c6..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,6 +101,21 @@ def layout_of( return Layout(count, tuple(meta.raw_channel_names), meta.rgb_samples or rgb, axes) +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: """Return the code and text of one image whose header contradicts its unit, else None. @@ -134,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/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..f14629cb --- /dev/null +++ b/tests/test_cli_usability.py @@ -0,0 +1,352 @@ +"""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 # 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"] + 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_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() + + +# --- 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 + 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): + 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 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 --------------- + + +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