diff --git a/AGENTS.md b/AGENTS.md index b513a96f..607d1dd1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -232,7 +232,8 @@ src/morphobricks_preprocessing/ 0011 settings file, Q10), folder_values (no pixel), settings_template entry_record.py morphobricks_entry.json: build_record, write_entry_record, check_entry_record, EntryResult, reuse_or_refuse (RE10); entry_identity.py brick_identity (every - file of the brick hashed against RECORD, libraries by RECORD digest); + file of the brick hashed against RECORD, libraries by RECORD digest; + pip, setuptools and wheel left out: INSTALL_TOOLS, v0.10.1); entry_publish.py default_output, check_output_place, staging_folder, publish (renameat2 RENAME_NOREPLACE, or an exclusive mkdir) notebook_entry_card.py the card "Run on a validated folder" of every brick (ADR 0007 Q6) @@ -297,7 +298,10 @@ src/morphobricks_preprocessing/ WindowLayoutError (shared by both); window_reader.py WindowReader (#304): many windows of one image through a bounded, thread-safe block_cache.BlockCache of decoded pieces (opt-in), - RunInputs.window_reader -> RunWindowReader by channel IDs; + RunInputs.window_reader -> RunWindowReader by channel IDs; it refuses at + open an OME-Zarr whose chunks leave no window within the limit (v0.10.1); + window_chunks.py check_window_chunks: check/run warn about such stores + (chunks_too_large_for_windows, e.g. one chunk per plane); window_map.py map_plan / map_windows / iter_windows: a function over windows in a bounded thread pool, results in window order, memory planned and checked against a budget before any read (lazy-windows §5); @@ -378,12 +382,20 @@ src/morphobricks_preprocessing/ he_tissue_mask.py the opt-in H&E tissue mask (Spec ADR 0005 BM15; RunInputs.he_tissue_mask and preview_he_tissue_mask through run_inputs_tissue.py's lazy mixin, the he-mask extra): the FOV resolved from the run, every refusal before any read, BM15's - lineage line and own retry comparator; he_tissue_rule.py the fixed rule - he_tissue_v1 (provisional) as one canonical record, computed from its record + lineage line and own retry comparator; he_tissue_rule.py the fixed rules + he_tissue_v1 and he_tissue_v2 (the default: v1 on the plane rescaled to its + white, estimate_white; both provisional) as canonical records, computed from + their record; he_tissue_run_facts.py the run facts of its lineage line + (the RGB header override item, the recorded pixel size) (SciPy clean-up, 8-connected, disks clipped by the border); code_identity.py the verified code identity (RECORD digest, PEP 610); lineage_schema.py the reader's dispatch by operation and the duplicate-key refusal; cli_tissue_mask.py the command tissue-mask + ignored_masks.py ignored_masks.toml (v0.10.1, owner 4 Dec 2026): the mask types and OME-Zarr label + images the runs skip; strict reader (read_ignored, parse_ignored), canonical text, + the manifest's optional ignored_masks entry (recorded_ignored); written by + mask_declare.ignore_masks (declare-masks --ignore, under the lock); preflight + passes the list to find_masks(ignore=); unrecorded.py leaves them out mask_declare.py declare_masks/with_declared_masks: declare mask types added after preprocessing in the published description (#587), the representation stated (no default) and the ID the folder name or given; published by publish_description (lock, base @@ -444,6 +456,11 @@ src/morphobricks_preprocessing/ moved from report.py in PP-10d discovery_report.py the run report (discovery_report.json and .txt, design v0.4 §4): status, manifest SHA-256, what was found, reused, recomputed and replaced + describe_ids.py describe --id FOLDER=ID (v0.10.1): apply_ids through Draft.confirm_id (the + notebook's rules), refusals naming the option; describe_questions.py the + draft's open questions and which options answer them (moved from cli_describe) + tissue_masks_folder.py create_masks_folder: tissue-mask on a run without a masks folder creates + _masks (or --masks) and records it by running preprocessing again cli.py, __main__ `morphobricks-preprocessing check|run|masks|calibrate|describe|convert|settings` (also `python -m morphobricks_preprocessing`); cli_run.py holds `run`'s options and output; cli_calibrate.py `calibrate`; cli_convert.py `convert`; log_target.py where `--log` may write (#99), @@ -585,7 +602,8 @@ src/morphobricks_preprocessing/ changed right there, the proposal the Axes step starts from notebook_zarr_copy.py the first screen's "Also save a copy as OME-Zarr" and the Axes step's card that writes it once the roles are confirmed; ome_zarr_copy.py - the writers (OME-NGFF 0.4, written directly) and the copy's name + the writers (OME-NGFF 0.4, written directly, chunks of at most + 1 x 1024 x 1024 since v0.10.1) and the copy's name notebook_projection.py the Axes step's card for Z-stacks: choose the projection, write the projected copies into the output folder (convert_experiment), open them as the experiment; the greyed 3-D option @@ -1033,7 +1051,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 @@ -1098,7 +1118,7 @@ Technical details go to `logging` (shown in the notebook's "Technical details" p | Histogram range (Q34, P6) | Step 3 **Settings**: the brick's `HistogramSettings` (`minmax` default, or `robust` with adjustable quantiles); recorded in the manifest's `settings.histogram`, any change recomputes every row. Every plane binned with `histogram_with_range_check` (memory estimate with `range_check=True`, through `planes._Binning`); `narrow_histogram_range` warnings from `range_check_issues`, one per channel, with the narrow planes recorded in the manifest's `narrow_histogram_ranges` so kept rows still report them. CSV schema 4 (underflow and overflow columns, zero with `minmax`); schema 3 tables recomputed. CLI `--histogram-range`, `--robust-quantiles`. Normalization brick pinned to v0.3.1 | | Position identity (Q20, D02) | `position_id` = image name without extension, in every CSV row and manifest file entry; FOV key = labels + `position_id`; duplicates in one leaf folder are the error `duplicate_position_id`. CSV columns and schema 2 unchanged; manifest version 1 with an optional key | | Masks (Q32) | Optional masks folder outside the experiment, one subfolder per mask type mirroring the experiment's folders, or the experiment's folders with `_.tif` (both may be mixed; `ambiguous_mask` when a name could fit two images or both layouts), paired by leaf folder + `position_id`; OME-Zarr label images are masks too. Header-only errors (`masks_folder_not_found`, `masks_inside_experiment`, `mask_names_differ_in_case`, `duplicate_mask`, `ambiguous_mask`, `unreadable_mask`, `mask_not_2d`, `mask_size_mismatch`, `mask_pixel_type`) and warnings (`mask_missing`, `mask_without_image`, `mask_outside_type_folder`) in `check`/`run`; manifest key `masks` (optional, version 1). Optional mask step (`masks` command, `scan_masks`): kinds, relations with evidence, direct-parent hierarchy, `mask_relationships.json` (report version 1); default thresholds the user may change (`thresholds=` keyword, one CLI option each, checked by `mask_thresholds`, written in the report); suggestions only, the user names and confirms. SciPy core dependency. Confirmed by the owner: 2D masks at the image's YX, integer/bool pixels, masks folder outside the experiment. Next: notebook step and a file of the user's answers; tag v0.2.0 proposed after merge. Plane identity (issue #36): masks may have Z and/or T named in their own metadata (never guessed: unnamed axes are `mask_not_2d`); the masks of an image share their planes (`mask_planes_differ`) and `run` checks them against the image's confirmed roles (`mask_planes_mismatch`, `mask_plane_issues`), so a 2D mask is refused for a Z-stack or time-lapse; manifest mask entries gain `axes` and `shape` (optional keys, version 1); `read_mask(z=, t=)` reads one plane; `scan_masks` scans plane by plane | -| H&E tissue mask (I1, BM15) | Opt-in only (`he-mask` extra; scikit-image, normalization's `stain` and the helper imported only when called). Fixed rule `he_tissue_v1`, provisional until its acceptance report is accepted; no per-call thresholds; sizes in pixels; colour maths from normalization only. One `uint8` region per image through BM12's publication with BM15's own line and comparator; an unverified code identity writes a mask never reused; freezing needs a new mask ID (design `docs/design/he-tissue-mask.md`, owner decisions of 16 November 2026) | +| H&E tissue mask (I1, BM15) | Opt-in only (`he-mask` extra; scikit-image, normalization's `stain` and the helper imported only when called). Fixed rules, provisional until an acceptance report is accepted: `he_tissue_v1` (white fixed at 255) and, the default since v0.10.1, `he_tissue_v2` (v1 on the plane rescaled to its white, the median of its brightest 0.1 %; v1 kept 0 % on grey-glass scans such as Zenodo 4550300); no per-call thresholds; sizes in pixels; colour maths from normalization only. One `uint8` region per image through BM12's publication with BM15's own line and comparator; an unverified code identity writes a mask never reused; freezing needs a new mask ID (design `docs/design/he-tissue-mask.md`, owner decisions of 16 November 2026) | | Settings (ADR 0011, Q89) | `defaults.toml` (package data) declares the run's (`common`) and Cellpose's (`cellpose`) settings with default, unit and help; `morphobricks_preprocessing.settings` loads, modifies, saves and passes them with the five shared names on the vendored `_brick_settings.py` (never edited; re-vendored from the Spec); the classes, CLI defaults and notebook widgets are copies held equal by `tests/test_settings.py`; no Cellpose CLI option | | Notebook style | Follow the lab's NucleiSky and LabChronicle notebooks (see §7) | | Widget widths | **99%**, never 100% | diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cca45e7..9b848d8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,228 @@ 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: the gaps a new user met before reaching the next brick in the clean-environment +test of the v0.10.0 wave (3 December 2026): reuse of entry outputs in conda environments, the +command line, and the H&E tissue mask; then the owner's follow-ups of 4 December 2026 +(`describe --id`, `tissue-mask` creating a masks folder, `declare-masks --ignore`, the +`A_DESCRIPTION_REQUIRED` fix). The histogram table, the description and the manifest version +are unchanged; one optional output-folder file (`ignored_masks.toml`) and one optional manifest +key (`ignored_masks`) are new. A v0.10.0 reader of a run that uses them ignores the key and so +refuses the skipped label images as unrecorded: refused, never silently wrong. + +### Changed + +- **Command-line wording (independent review of v0.10.1, owner answers of 4 December 2026).** + Every subcommand has a description and examples in `--help`; option help is rewritten in plain + language. Success lines say what was saved and where, then print the next commands with the + user's own options, shell-quoted (`describe --publish`, `check`, `run`, `convert`, + `calibrate`, `declare-masks`, `tissue-mask`, `masks`). Refusals say what was refused, why and + what to do, with commands on their own lines (`A_DESCRIPTION_REQUIRED`, ID reasons in + `describe --id`, undeclared mask types with each representation's meaning, an unreadable + `ignored_masks.toml`, projection, conversion and tissue-mask refusals); the `zarr` install line + names the installed release. Issue codes, severities and paths are unchanged. README and user + guide follow (complete workflow, both masks-folder layouts, `plane_histograms.parquet`). + `cli_run_options` and `cli_describe_options` hold option definitions moved out of `cli_run` + and `cli_describe` (line limit); `parse_size` and `add_describe_parser` are re-exported. + +### Fixed + +- **`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 + 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`). +- **`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** + (`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 + (fiberfeatures' `run.execution_route = "patch_window"`, through `RunInputs.window_reader`) + decodes a chunk whole for any window, so it refused the first patch of a large converted slide + (`WindowMemoryError`) after `check` had passed. Copies are now written in chunks of one plane by + at most 1024 x 1024 pixels (`1 x ... x min(Y, 1024) x min(X, 1024)`, bioformats2raw's default; + `ome_zarr_copy.CHUNK_SIDE`, `chunk_shape`), still uncompressed Zarr version 2 (OME-NGFF 0.4), + one level (no pyramid: the bricks read level 0 only). Each plane is written as it is read, + block by block within the memory limit, each block's part of each chunk written in place + (edge chunks at full size, zeros outside the image, as Zarr 2 stores them); a plane read in + blocks is never held whole. **Byte identity:** the pixels, the `.zattrs` and the conversion + record's other fields are unchanged, but a copy of an image larger than 1024 pixels along Y + or X is new bytes: its `0/.zarray` `chunks` and its chunk files (`0///`, + instead of one `0//0/0` per plane), so its `copy_sha256` differs. Copies of planes of at + most 1024 x 1024 pixels are byte for byte as before. A conversion into a folder that already + holds a copy written before keeps that copy (its plan and content are unchanged): convert + into a new folder to get the chunked copies. +- **`check` and `run` warn about an OME-Zarr image no window reader can serve** + (`chunks_too_large_for_windows`, new module `window_chunks`): from the header, the least a + window reader needs for a window of one pixel, through a cache of one chunk + (`window_chunks.window_chunk_need`, `windows.smallest_window_memory`), against the memory + limit; the warning names the images and says to convert the originals again into a new folder + (for a copy written before v0.10.1) or to save the image with chunks of at most 1024 x 1024 + pixels. `check` uses the default limit (1 GiB); `run` its `--memory-limit`. The same store is + refused when `WindowReader` / `RunInputs.window_reader` is opened on it with a cache that + leaves no room for one window (`WindowMemoryError`, naming the chunks and the fix), instead of + on its first window; a window refused for its memory names the chunks too. + `tests/test_ome_zarr_chunks.py`. +- **An entry output is reusable in a conda environment** (Spec ADR 0007 RE10). Conda installs + `setuptools` as an `.egg-info` with no `RECORD`, and `brick_identity` followed every + requirement of the brick, every extra included, down to it: every record written there was + `uncertain`, so every rerun and `check` of the output was refused with + `ENTRY_IDENTITY_UNCERTAIN: ... (setuptools: RECORD missing)`. The installers `pip`, + `setuptools` and `wheel` are now neither listed nor followed in the identity's closure + (`entry_identity.INSTALL_TOOLS`): no brick computes a value with them. Any other library + without a `RECORD`, or editable, still makes the identity uncertain (ADR 0007 (b)); a name a + brick passes in `libraries` is identified whatever it is. An output whose v0.10.0 record lists + one of them is another identity for v0.10.1 (`ENTRY_OUTPUT_EXISTS` naming it); upgrading + preprocessing changes every brick's identity anyway, preprocessing being one of its libraries + (plan §12 question 93). +- **A first run under an uncertain identity says so.** `write_entry_record` writes the record and + warns with `EntryIdentityWarning` (text from the new `identity_warning`, both re-exported) that + the output will never be reused, naming the reason and the fix, instead of only the next run + failing. +- **The refusal's fix names the actual cause.** When the brick is a released install and a + library is what is uncertain, the fix of `ENTRY_IDENTITY_UNCERTAIN` names that library (no + `RECORD`: reinstall it with `pip install --force-reinstall --no-deps "=="`; or + an editable install) and says the brick needs no change, instead of "Install a released + ``" (`entry_errors.uncertain_code_fix`, `entry_identity.uncertain_library`). +- **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, its heading naming only the + options that can answer them (owner, 4 December 2026): an ID with no proposal is answered by + `--id FOLDER=ID` alone, never offered `--accept-ids`. Counts use `plural`. +- **`tissue-mask` on a run without a masks folder** (owner, 4 December 2026) no longer stops + with "the run has no masks folder ... Run preprocessing with a masks folder first": it + creates `_masks` beside the experiment (or the new, empty folder `--masks FOLDER` + names), records it by running preprocessing again with it, as `run --masks` records one + (unchanged images are not read; `tissue_masks_folder.create_masks_folder`), and says so in one + line. A non-empty existing folder is never adopted. Its messages: a refusal names the image + once (it was repeated, "a.tif: no tissue mask written. a.tif is not an image of this run"); + the next steps print the `declare-masks --type ID=binary`, `run` and `masks` commands with + the folders, no longer `source_channels` (which `declare-masks` cannot set), and name the + region as a brick's settings do, `region_mask = ""`, not `MaskRequest(, 'region')` + (the notebook card's next steps too). +- **`A_DESCRIPTION_REQUIRED` names both routes** (owner, 4 December 2026): the notebook's + describe steps, and `describe ... --publish` with its fast-mode options; it named only the + notebook. +- **`R_MASK_TYPE_NOT_DECLARED`'s fix names `--ignore TYPE`** beside `--type TYPE=REPRESENTATION`. +- **The image-type suggestion of `check` and `run` follows the published description** when it + declares every acquisition `rgb` and RGB is possible (`image_type.declared_image_type`, + `review_image_type(..., declared=)`). An OME-Zarr copy written by + `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`. +- **The H&E tissue mask kept nothing on scans whose glass is not white.** On the Zenodo 4550300 + H&E TMA cores (glass near (127, 135, 145), photometric tag MINISBLACK read with + `rgb_header_override = true`), `tissue-mask` printed "kept 0.0 % (nothing kept: an empty + region)" for every core, so fiberfeatures measured `roi_area_px = 0` and NaN features. The + channel order, the override and the mask's polarity were correct: rule `he_tissue_v1` fixes the + white at 255, so against it every pixel of these scans has an optical density of at least 0.22, + the background never fires, `H >= 0.05` holds everywhere and the whole plane was "nuclei". + New rule **`he_tissue_v2`** (provisional), the default of `RunInputs.he_tissue_mask`, + `RunInputs.preview_he_tissue_mask`, `he_tissue_mask_array`, `tissue-mask --rule` and the + notebook card: v1 on the plane rescaled to its own white, estimated per channel as the median + of the brightest 0.1 % of pixels (by R + G + B) and applied with normalization's + `rescale_to_white`. v1's thresholds and sizes are unchanged; v1 itself is unchanged and still + offered (`rule="he_tissue_v1"`). Kept share on cores 1B_D9 and 2B_A6: 0.0 % -> 46.8 % and + 44.4 %; on white-glass slides (CMU-1) v2 is within 0.4 points of v1, and identical when the + brightest pixels are 255; blank slides keep nothing. A mask written under v1 is not reused under + v2 (another rule record): use a new output mask ID. `TissueMaskPreview.white` gives the white + used (`None` under v1). Regression fixture: a 320 x 320 crop of core 1B_D9 + (`tests/data/he_core_1B_D9_crop.npz`, CC-BY-4.0, with its generator). Design: + `docs/design/he-tissue-mask.md` ("`he_tissue_v2`"). +- **The two plane memory figures are named apart** (the owner's run of the formin OME-Zarr + mosaic, 30720 x 36864, 3 channels, `uint16`, chunks 1 x 1024 x 1024, 4 December 2026). `run` + warned that its planes "would need up to 38.0 GiB" while `xyc_plane_memory`, the bound + `RunInputs.read_plane` enforces and the next bricks check, gave about 14.8 GiB for the same + plane. Both figures are right and measure different things: the run's + (`PlaneLayout.memory_estimate`) is **one channel** read whole *and measured*: the chunks it + touches (2.1 GiB), the plane (2.1 GiB) and the histogram's working arrays (33.8 GiB: the + normalization brick's upper estimate of 32 bytes per pixel for an integer plane) with the + image QC sums; `xyc_plane_memory` is the pixels of **all three channels** in one + `(C, Y, X)` array with no histogram (4 planes and 3 copies of the chunks). No number + changes; the texts now say which is which: `planes_read_in_blocks` (and the notebook's run + plan) says "too large to measure whole ...: one channel and its histogram would need up to ..." + and that reading all channels without a histogram needs another amount; `read_plane`'s `PlaneMemoryError` says "the pixels + only: no histogram is computed". Tested on a lazily written OME-Zarr store of the mosaic's + size (metadata only, `tests/zarr_tree.Unwritten`). +- **`link_outside_folder` says why and what to do.** A link in the experiment (or masks) folder + to an image or OME-Zarr store kept elsewhere (`exp/ctrl/rep1/formin_mosaic.zarr -> + /data/formin_mosaic.zarr`) stays refused: the "contain" rule is the owner's decision of 2 + November 2026 (#81, plan §12 question 64; a run reads, fingerprints and records only what is + inside the selected folder). The message now says that the images behind the links are not + found and why, and the fix says to move (not copy) the data into the folder, instant on the + same drive, or to put the experiment's folders on the drive that holds the data, instead of + "Copy or move the files". Whether to offer an opt-in that follows such links is asked in plan + §12 question 95 (proposed, not decided). + +### Added + +- **`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. +- **`describe --id FOLDER=ID`** (fast mode, repeatable; owner, 4 December 2026) names the ID of + any condition, biological-repeat or technical-repeat folder, so a folder whose name cannot be + an ID (`control`, `files`: `E_FORBIDDEN_FIELD`) is no dead end on the command line. The ID is + adopted exactly as typed and checked with the notebook's rules (`Draft.confirm_id`: + forbidden names, case collisions, an ID used twice, `single`); a refusal names the option to + give again (`--id control=`) and nothing is written. A label used at two levels takes + `condition:`, `repeat:` or `technical:`. Without `--channels` it shows the draft with the IDs. + Refused for a published description or `--strict`. New modules `describe_ids` and + `describe_questions` (the question texts, moved from `cli_describe`). +- **`declare-masks --ignore TYPE`** (repeatable; owner, 4 December 2026) lets the runs skip an + OME-Zarr label image or mask type they do not use, instead of refusing it as undeclared. The + list is `ignored_masks.toml` beside `morphobricks.toml` (version 1, keys `version` and + `ignore`, read strictly; the description has no field for it), written under the output + folder's lock. `check` and `run` leave those types out of mask discovery + (`find_masks(..., ignore=)`); the run records the list and the file's SHA-256 in the manifest + (`ignored_masks`, optional), so `RunInputs.open` does not count them as unrecorded masks and + refuses a list changed, added or removed since the run (`RUN_FOLDER_STALE`). A declared type + cannot be ignored; declaring a type takes it off the list. An unreadable file is the error + `ignored_masks_invalid`. `--type` is no longer required (`--type` or `--ignore`). New module + `ignored_masks`. +- **`convert --store ome-zarr`** writes every image that is read as an OME-Zarr copy (OME-NGFF + 0.4, `.ome.zarr`), as `convert_experiment(..., store="ome-zarr")` and the notebook do; + RGB TIFFs included. Default `ome-tiff`, as before. The user guide (§5) shows the H&E route: + `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/README.md b/README.md index 4392d910..40240334 100644 --- a/README.md +++ b/README.md @@ -2,14 +2,20 @@ [![CI](https://github.com/CellMigrationLab/morphobricks-preprocessing/actions/workflows/ci.yml/badge.svg)](https://github.com/CellMigrationLab/morphobricks-preprocessing/actions/workflows/ci.yml) -The preprocessing brick of MorphoBricks. It reads an experiment folder of -microscopy TIFFs, computes one intensity histogram per channel of every plane, and writes -them, with each plane's experimental labels, to `plane_histograms.csv`: one row per plane -(an image at one time point), each channel in its own columns. MorphoBricks v1 analyses 2-D -planes: a Z-stack (more than one depth slice) is refused (`z_stack_not_supported`); make -recorded 2-D projected copies first with `convert --project max|mean|sum`, and use the copies. Later bricks -(for example patch extraction) use that table to calculate normalization -parameters for any group of images without rereading the pixels. +MorphoBricks preprocessing is the first step before analysing a microscopy experiment. It +records experimental conditions, repeats, channels, pixel sizes and masks, checks the images, +and prepares the files used by downstream MorphoBricks analysis tools. + +Its main output is `plane_histograms.parquet`: the intensity histograms of every image plane, +with its experimental labels and channel IDs. The table contains one row per plane and stores +each channel's histogram as lists of bin indices and counts. Later MorphoBricks tools read this +file to calculate normalisation parameters without rereading the image pixels. From v0.10.0, +this file replaces `plane_histograms.csv`. To update an older preprocessing run, run +preprocessing again. + +MorphoBricks v1 analyses 2-D planes: a Z-stack (more than one depth slice) is refused +(`z_stack_not_supported`); make recorded 2-D projected copies first with +`convert --project max|mean|sum`, and use the copies. The brick never modifies source images and never applies a normalization itself. The histograms, the table format, pooling and the normalization methods come from the @@ -50,16 +56,16 @@ Pre-alpha; the current release is v0.10.0 (what is planned next is in - A step-by-step notebook ([notebooks/MorphoBricks_Preprocessing.ipynb](notebooks/MorphoBricks_Preprocessing.ipynb)) and a command line (`morphobricks-preprocessing check` / `run` / `masks` / `calibrate` / `describe` / `convert`) -- **Every run is described** (v0.5.1): the output folder must hold a published experiment - description, `morphobricks.toml`, written by the notebook's describe steps (*Check and - save*). A run without one is refused with `A_DESCRIPTION_REQUIRED` on every route. +- **Every run is described:** publish the experiment description using `describe --publish` + or the notebook. Every preprocessing run requires a published description + (`morphobricks.toml`); a run without one is refused with `A_DESCRIPTION_REQUIRED`. Every feature, message code and output file is described in the [user guide](docs/user_guide.md). From the normalization brick (`morphobricks_normalization`, a required dependency, pinned -to its release v0.8.0): per-plane histograms with the robust range and the range check -(`histogram`, `ranges`), the histogram table (`csv_io`, schema version 5: channels by canonical -ID, so acquisitions may have different channels), pooled group statistics +to its release v0.10.0): per-plane histograms with the robust range and the range check +(`histogram`, `ranges`), the histogram table (`parquet_io`, `plane_histograms.parquet` schema +version 6: channels by canonical ID, so acquisitions may have different channels), pooled group statistics (`pooling`) and normalization parameters (`normalization`); import them from `morphobricks_normalization` (the deprecated paths through `morphobricks_preprocessing` were removed in v0.4.0). @@ -81,8 +87,17 @@ contract version 3 and an objects use with `RunInputs.read_objects`. See the ## Installation +You need Python 3.11 or newer, Git and an internet connection. We recommend installing into a +new Python virtual environment. JupyterLab is not required for command-line use. + ```bash -pip install "git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.0" +python -m pip install "morphobricks-preprocessing @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" +``` + +For OME-Zarr images or the H&E tissue mask, install the extras too: + +```bash +python -m pip install "morphobricks-preprocessing[zarr,he-mask] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" ``` For development, from a clone: @@ -92,15 +107,15 @@ pip install -e ".[dev]" ``` The optional `notebook` extra installs the widget dependencies for the notebook -(`pip install "morphobricks-preprocessing[notebook] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.0"`). +(`python -m pip install "morphobricks-preprocessing[notebook] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1"`). The notebook's first code cell (**1. Install**) can set this up automatically: it uses a nearby checkout or an installed package only when it is the pinned `RELEASE_REF` commit (never by version alone), and installs missing requirements into the active kernel. A standalone download installs from GitHub if needed (internet access and Git required). The optional `he-mask` extra installs scikit-image (through `morphobricks-normalization[histology]`) -for the opt-in H&E tissue mask (`tissue-mask`, `RunInputs.he_tissue_mask`; rule `he_tissue_v1`, -provisional); without it, nothing of that helper is imported. `he_tissue_mask_array(rgb)` computes +for the opt-in H&E tissue mask (`tissue-mask`, `RunInputs.he_tissue_mask`; rule `he_tissue_v2` +by default, provisional); without it, nothing of that helper is imported. `he_tissue_mask_array(rgb)` computes the same mask on a `uint8` `(Y, X, 3)` array with no run and writes nothing (no lineage; for runs, use `tissue-mask`); see the [user guide](docs/user_guide.md#an-he-tissue-mask-optional) and [contract §15.4](docs/contract.md#154-the-he-tissue-mask-of-an-array-with-no-run-roadmap-k3). @@ -143,12 +158,7 @@ LabConstrictor's JupyterLab/LabConstrictor before their release candidate is tagged; see [docs/colab-release-check.md](docs/colab-release-check.md). -From a terminal: - -```bash -morphobricks-preprocessing check /data/exp1 -morphobricks-preprocessing run /data/exp1 --axes ZCYX --image-type fluorescence -``` +From a terminal, see [Command line](#command-line) below. ## Running an experiment @@ -185,30 +195,57 @@ the [user guide](docs/user_guide.md) §9, "Settings". ## Command line +A complete workflow. This example assumes that every image contains collagen and fibronectin +in that order, that the image axes are named correctly, and that your biological repeats were +prepared and acquired comparably. Replace the channel names and date with your own. Review the +proposed IDs before accepting them. If these assumptions do not fit your experiment, use the +relevant instructions in the [user guide](docs/user_guide.md) §5. + +```bash +morphobricks-preprocessing describe my_experiment # preview: proposed IDs, open questions +morphobricks-preprocessing describe my_experiment --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +morphobricks-preprocessing check my_experiment +morphobricks-preprocessing run my_experiment +``` + +Your experiment is now described, checked and processed. The default output folder is +`my_experiment_MorphoBricks_Preprocessing`. Give this folder to the MorphoBricks tool that will +analyse your images. + +Fast publication from the command line creates a new description for an experiment with a +shared channel layout. Use the notebook to edit an existing description, change repeat pairing +or describe acquisitions with different channel lists or orders. Give `--comparable` only if +the samples of each biological repeat were prepared and acquired comparably; never give it +just to get past the question. + +Other commands: + ```bash -morphobricks-preprocessing describe /data/exp1 # the draft description, what is open -morphobricks-preprocessing check /data/exp1 # report, suggested --axes -morphobricks-preprocessing run /data/exp1 --axes ZCYX -morphobricks-preprocessing run --output /data/exp1_MorphoBricks_Preprocessing # later runs -morphobricks-preprocessing masks --output /data/exp1_MorphoBricks_Preprocessing # mask step -morphobricks-preprocessing calibrate --output /data/exp1_MorphoBricks_Preprocessing -morphobricks-preprocessing convert /data/exp1 --to /data/exp1_named_axes --axes ZXY # axis errors -morphobricks-preprocessing convert-mask --output /data/exp1_MorphoBricks_Preprocessing --mask TumorRegion --to-instances TumorObjects # new mask files -morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preprocessing --to HETissue # H&E tissue region (he-mask extra; provisional rule) +morphobricks-preprocessing run --output my_experiment_MorphoBricks_Preprocessing # later runs +morphobricks-preprocessing declare-masks --output my_experiment_MorphoBricks_Preprocessing \ + --masks my_masks --type Cells=instances # declare masks +morphobricks-preprocessing masks --output my_experiment_MorphoBricks_Preprocessing # check masks +morphobricks-preprocessing calibrate my_experiment --size . XY 0.65 um # pixel sizes +morphobricks-preprocessing convert my_experiment --to my_experiment_max --axes ZCYX --project max # 2-D projections +morphobricks-preprocessing convert-mask --output my_experiment_MorphoBricks_Preprocessing --mask TumorRegion --to-instances TumorObjects # new mask files +morphobricks-preprocessing tissue-mask --output my_experiment_MorphoBricks_Preprocessing --to HETissue # H&E tissue region (he-mask extra; provisional rule) ``` `check`, `run` and `masks` need the experiment description published in the output folder -(the notebook's describe steps); without it they stop with `A_DESCRIPTION_REQUIRED` and write -nothing. `describe` shows the draft and what is still to be answered. `check` writes the -report. `run` and `masks` reuse every input the run in the -output folder recorded. A run that stops writes its report and says so. Every output file -gets the permissions a file you save yourself would (your umask). `convert` saves the -images whose metadata name their axes wrongly or not at all as named-axis OME-TIFF copies -with your roles in a new folder (each plane bit for bit the plane read with those roles; -every other image copied as it is; a conversion record written last), then you run -preprocessing on that folder with the same output folder. The notebook offers the same -conversion in step 2, under the axis check, when it finds such images. Details in the -[user guide](docs/user_guide.md) §5. +(`describe --publish` or the notebook's describe steps); without it they stop with +`A_DESCRIPTION_REQUIRED` and write nothing. `check` inspects the folders, image headers and +supplied masks, and suggests axis roles; it does not measure image pixels or perform every +validation of the published description. `run` validates the description and confirmed axis +roles before processing. `run` and `masks` reuse every input the run in +the output folder recorded. External TIFF masks are stored in a separate masks folder, given +with `--masks`; OME-Zarr label images are discovered automatically. If your analysis uses +masks, run `masks` after preprocessing. After `calibrate`, run preprocessing again. Every +output file gets the permissions a file you save yourself would (your umask). `convert` writes +copies of the images in a new folder (named-axis OME-TIFF, OME-Zarr with `--store ome-zarr`, +or 2-D projections with `--project`); the copies are a new experiment folder, described and +published before `check` and `run`. Use the actual stored axis order of your images: RGB TIFFs store their colour samples +last (`YXC`). Details in the [user guide](docs/user_guide.md) §5. ## Example @@ -232,13 +269,14 @@ record = PlaneRecord( technical_repeat="tech_rep1", histograms=[compute_plane_histogram(plane)], # one per channel position_id="img_01", # required: the XY position within its technical repeat + channels=("DNA",), # the channel ID of each histogram, in order ) -write_plane_histograms([record], "plane_histograms.csv") +write_plane_histograms([record], "plane_histograms.parquet", channel_ids=["DNA"]) # In a later brick: pool one channel of any group and derive normalization parameters -records = read_plane_histograms("plane_histograms.csv") +records = read_plane_histograms("plane_histograms.parquet") for key, members in group_records(records, "condition").items(): - pooled = PooledHistogram(members, channel=0) + pooled = PooledHistogram(members, channel="DNA") params = percentile_range(pooled, low=1, high=99.8) normalized = params.apply(plane, clip=(0, 1)) ``` diff --git a/docs/contract.md b/docs/contract.md index 0a46176c..c7cf69f6 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -16,8 +16,9 @@ whole experiment; any change to them goes through the normalization brick. There is no backward compatibility before the first pipeline release (owner policy of 10 November 2026). **Every run needs a published experiment description** (`morphobricks.toml` in its output folder, experiment-v1). Without one every route refuses the run with the one code -`A_DESCRIPTION_REQUIRED`, before anything is read or written, naming the fix (the notebook's -describe steps and *Check and save*; the command line's `describe` shows what is still open): +`A_DESCRIPTION_REQUIRED`, before anything is read or written, naming the fix, both routes that publish one (owner, 4 December 2026): the notebook's describe +steps and *Check and save*, or the command line's `describe ... --publish` (fast mode; without +`--publish` it shows what is still open): | Route | Refusal | |---|---| @@ -53,7 +54,7 @@ identity alone. | Uniqueness | Folder names need only be unique among siblings, ignoring case. Two folder names of one level (condition, biological repeat or technical repeat) that differ only in case are the error `case_conflict`, whether siblings or anywhere in the experiment (`ctrl/Rep1` and `treated/rep1`; decision D-e, §16; siblings only before D86). | | Names | Every label and `position_id` passes `check_identity_text` (§16): no leading or trailing whitespace, and not `""`, `NA`, `nan`, `none`, `null`, `n/a` or `` in any case, which table readers turn into a missing value. A folder or image name that fails is the error `invalid_name` (decision D-e; accepted before D86). | | Depth | At most three folder levels below the root. A folder below the technical-repeat level is an error. | -| Links | Contain (issue #81, owner 2 November 2026): a symbolic link to a file or folder (on Windows also a directory junction, which Python 3.11 does not report as a link) is followed only when its real path (`os.path.realpath`) is inside the experiment folder, itself resolved. A link that leaves it is not followed and is the error `link_outside_folder`, naming each link and its target (a broken link too); a link to a folder on its own path (the folder holding it, or one above) is `link_loop`; one file reached by two paths (a link and its target, two links, a linked folder and its target, or two hard links: the same device and inode, from the one `stat` taken per image or mask; owner, 2 November 2026) is `linked_twice`, naming both. A broken link that stays inside is kept and reported by its reader (`unreadable_tiff`, `unreadable_mask`), never skipped. Hidden and system names (§1) are skipped before any link is looked at, so a hidden link is never followed; a contained link *to* a hidden folder is followed, because that folder is itself never walked, so its files are found once, under the link's name, which the user chose. The links inside an OME-Zarr store are held to the same rule, though the store is not entered as a folder level: its folders are listed and only its links resolved, about 84 ms per 20,000 store files on each discovery (accepted by the owner, 2 November 2026). The masks folder follows the same rule (§15), with `RunInputs` (§9.1) and `convert` (§17) refusing the same links; one helper, `links.LinkGuard`, walks both folders. | +| Links | Contain (issue #81, owner 2 November 2026): a symbolic link to a file or folder (on Windows also a directory junction, which Python 3.11 does not report as a link) is followed only when its real path (`os.path.realpath`) is inside the experiment folder, itself resolved. A link that leaves it is not followed and is the error `link_outside_folder`, naming each link and its target (a broken link too), saying that what is behind it is not found and why, and telling the user to move the data in (v0.10.1; an opt-in to follow such links is plan §12 question 95, not decided); a link to a folder on its own path (the folder holding it, or one above) is `link_loop`; one file reached by two paths (a link and its target, two links, a linked folder and its target, or two hard links: the same device and inode, from the one `stat` taken per image or mask; owner, 2 November 2026) is `linked_twice`, naming both. A broken link that stays inside is kept and reported by its reader (`unreadable_tiff`, `unreadable_mask`), never skipped. Hidden and system names (§1) are skipped before any link is looked at, so a hidden link is never followed; a contained link *to* a hidden folder is followed, because that folder is itself never walked, so its files are found once, under the link's name, which the user chose. The links inside an OME-Zarr store are held to the same rule, though the store is not entered as a folder level: its folders are listed and only its links resolved, about 84 ms per 20,000 store files on each discovery (accepted by the owner, 2 November 2026). The masks folder follows the same rule (§15), with `RunInputs` (§9.1) and `convert` (§17) refusing the same links; one helper, `links.LinkGuard`, walks both folders. | | Mount points | Refused (owner, 3 November 2026), as far as they can be seen: a folder (or file) below the experiment folder or the masks folder that is a mount point by the rules below is not entered and is the error `mounted_folder`, naming it. A mount point is a path listed in Linux's `/proc/self/mountinfo` (the only way to see a bind mount of the same file system, for which `os.path.ismount` and the device number report an ordinary folder), or a folder, image or mask file on another device (`st_dev`) than the selected folder: another file system or Windows volume, or a Btrfs subvolume (a file's device comes from the one `stat` taken per image or mask; review of rc5). The selected folder itself may be on any mount. The same rule holds inside OME-Zarr stores (their files are held to the mount table only: they are not `stat`ed), and `check`, `run`, `convert` and `RunInputs` refuse the same mount points (a refused run publishes no scientific outputs and leaves the sources untouched; its discovery report is written). **Not seen:** a mount created after the walk started (the table is read once per walk); and where no mount table can be read (macOS, BSD, Windows, a Linux without `/proc`), a mounted single file or a mount of the same device (BSD `nullfs`). macOS `bindfs` (FUSE) and Windows mounted folders have another device, and a Windows mounted folder is also a mount-point reparse point, held to the link rule. **Refused although not mounted:** on an overlay file system (`overlayfs`, as in many containers) whose layers are on different file systems, mounted with `xino=off`, files (not folders) may report another `st_dev` than the selected folder and are then `mounted_folder` (copy the experiment to an ordinary folder, or use `xino=on` or `auto`). | | Unlisted store folders | A folder inside an OME-Zarr store (in the experiment or the masks folder) that cannot be listed (permissions, a disconnected drive) is the error `store_unreadable` (#392), naming each such folder: its links and mount points are not known, so the store is not taken as checked. Before, it was only logged and the store passed. Like the link errors, `RunInputs` (§9.1) and `convert` (§17) refuse it too (`links.LINK_CODES`). | | Hard links | An image or mask whose link count is above 1 (`st_nlink`, from the one `stat` taken per image or mask; it has other names, perhaps outside the folder, through which it can change) is the warning `hard_linked_file`, naming it and its count (owner, 3 November 2026). It is read and fingerprinted as any other file; the files inside an OME-Zarr store are not counted. | @@ -297,6 +298,7 @@ interpretation. | `narrow_histogram_ranges` | The channel planes whose range check found the central range too narrow (§4), sorted by plane and channel: `relative_path`, `plane_id`, `channel` and the fields of the normalization brick's `RangeCheck` (`histogram_range`, `central_percentiles`, `central_bins`, `robust_quantiles`, `robust_limits`, `outside_robust_count`, `robust_central_bins`, `min_central_bins`). Empty when there are none; absent in manifests written before follow-up P6. Optional key: the manifest stays version 1. | | `conversion_record_sha256` | SHA-256 of the conversion record (`.morphobricks-conversion.json`) in the experiment root when the experiment is a tree of named-axis copies (design v0.4 §5, §17); null otherwise. `RunInputs` checks it (owner decision of 2 November 2026, plan question 59): a record changed or gone since the run is refused, as for `calibration_sha256`. A changed record changes no row (the copies are checked by their fingerprints like any image). | | `calibration_sha256` | SHA-256 of the output folder's `calibration.csv` as the run read it (§9.3); null when there was none (or absent in manifests written before PP-8). `RunInputs` checks it. | +| `ignored_masks` | Optional (v0.10.1; key left out when nothing is skipped): `{"types": [sorted names], "file_sha256": "..."}`, the mask types and OME-Zarr label images the run skipped as the output folder's `ignored_masks.toml` lists them (`declare-masks --ignore`, owner decision of 4 December 2026, plan §12 question 94) and that file's SHA-256. Those types are left out of mask discovery (no header check, no record, no `R_MASK_TYPE_NOT_DECLARED`); `RunInputs.open` does not count their files as unrecorded and refuses a list changed, removed or added since the run (`RUN_FOLDER_STALE`). The manifest version is unchanged: a reader without this key refuses the skipped files as unrecorded. | | `experiment_description` | Always present (v0.5.1: every run is described, §0; experiment-v1 §4.5a, §4.6, §9.3). An object: `sha256` (of the exact bytes the run read: provenance, never a cache key), `schema_version`, `section_digests` (`conditions`, `channels`, `repeats`, `masks`), `units` (one object per declared unit: its repeat, condition and technical repeat IDs and `image_type_header_verified`, false for a format whose header states no colour interpretation and for a unit whose header was overridden; only for a unit declared `rgb` with `rgb_header_override = true` whose TIFF header does not say RGB and whose images all have three interleaved samples (Spec experiment-v1 §4.4b, amendment RH1), `image_type_header_overridden` (true) and `header_photometric` (the header's photometric interpretation, for example `minisblack`; distinct ones joined by `, `); for every unit declared `rgb`, `rgb_header_override`: the declared key (`true` or `false`, absent in the file is `false`; owner answers of 14 November 2026: declared and effective are recorded separately); for a unit that declares it `true`, `rgb_header_override_images`: a list sorted by `image` (relative path) of objects `image`, `override` (`used`: it lifted a header that does not say RGB; `unused`: it did not) and `header_photometric` (that image's own header colour interpretation, kept as evidence; null for a format that states none), an `unused` item adding `unused_reason` (`header_already_rgb`: header-verified; `no_colour_interpretation`, for example OME-Zarr: not header-verified). Homogeneity (`R_UNIT_NOT_HOMOGENEOUS`) compares the effective image type, so images of an overridden unit that differ only in colour interpretation are one layout; `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` is reported before it. These keys are additive (optional on read, checked when present): the manifest version stays 5; and, only for a unit that has such images, `images_without_header_channel_names`: a list sorted by `image` (relative path) of objects `image`, `header_names` (`none` when the header names no channel, `partial` when only some) and `channel_positions` (the zero-based C positions without a header name). Such an image passes the header checks, needs no evidence and the confirmed layout is used (§4.3); it is listed, not warned about, and the key is omitted for a unit whose images are all fully named; RGB units list nothing), `masks` (per declared mask ID: `source_type`, `representation`, `status`, `images_with_masks`, `images` and each file with its fingerprint and its own `status`) and `records` (the lines of `morphobricks.records.jsonl`, copied unchanged). A mask file is `checked` only when the mask step recorded it in `mask_representation.json` with the same fingerprint, representation and source type; otherwise `not yet checked`. Each unit record also lists its `channels` in source order; in a fast-mode description (Spec ADR 0006, `channel_layout`) every unit record adds `channels_from` (`experiment` or `unit`, as published) and a unit with `channels_from = "experiment"` adds `fast_layout_images`: one object per checked image, sorted by `path`, with `path`, `fov_key` (an object: `condition`, `biological_repeat`, `technical_repeat`, `position_id`), `header_verified` (true exactly when every channel's evidence is `header`) and `channels`, one object per index of the list: `c`, `channel`, `header_name` (as read, never normalised: `""` for a stated empty name, null when the format states none) and `evidence` (`header`, or `statement`: no name, accepted under the user's statement); additive keys, checked when present (the manifest version stays 5), and `channel_coverage` (manifest version 5, Stage 3 S3.3) classifies every biological repeat for every declared channel ID: `status` `full` (every unit of the repeat lists it), `partial` (some do; also the warning `partial_channel_coverage`) or `unavailable`, with `units_with`, `units` and the units `lacking` it (`condition/technical repeat` IDs). A run refuses units of different image types (`R_HETEROGENEOUS_LAYOUT_NOT_ENABLED`); units with different channel lists are accepted. | | `projection` | Only for a run on a tree of Z-projected copies (the key is left out otherwise, so a run without projection is byte for byte as before; issue #176, run side). An object with exactly `method` (`max`, `mean` or `sum`), `z_range` (`[start, stop]` requested for the experiment, or null for every slice), `conversion_record` (`{file, sha256}`: the record these facts come from, the same SHA-256 as `conversion_record_sha256`), `source_root`, `images` (one per analysed image, unique and sorted by path, which `read_manifest` checks: `relative_path`, `source_relative_path`, `source_content_sha256`, `source_z_size`, `z_range` (the slices used), `source_dtype`, `output_dtype`, `dtype_rule`, `rounding`, `significant_bits_dropped`), `masks_paired` (the masks paired with projected images, sorted) and `warnings` (`["masks_on_projected_images"]` exactly when `masks_paired` is not empty). A reader that knows nothing of the key ignores it, but it also refuses the conversion record the run names (version 3 or later), so projected copies are never read by it as plain images; `manifest_version` is not changed. | | `lab_links` | Only for a run given lab-tool links (v0.5.1, PP-2; Spec experiment-v1 §9.3; owner decision of 9 November 2026); the key is left out otherwise, so a run without links is byte for byte as before. An object with exactly the keys the user gave, recorded verbatim: `repository_url`, `commit` and `experiment_path` (each non-empty text with no outer whitespace, control character (Unicode `Cc`) or bidi control (U+061C, U+200E, U+200F, U+202A–U+202E, U+2066–U+2069; #416), other format characters such as ZWNJ and ZWJ kept; `commit` a full lowercase hexadecimal SHA of 40 or 64 characters) and, when given, `repeat_codes` (each lab-tool repeat code to a canonical biological repeat ID, written sorted by code). Input: `run --lab-links FILE` (a UTF-8 JSON object; any other key, a value of another type, an empty value or a key given twice in one object is refused before anything is read, `lab_links_invalid`), or `run_experiment(mode=RunMode(lab_links=LabLinks(...)))` (`read_lab_links`, `LabLinks`, `LabLinksError`). Nothing is trimmed, guessed or filled in. A `repository_url` holding a credential (a password, `user:password@`, in any form; a user name before `@` in a URL whose scheme is not `ssh`, `git+ssh` or `ssh+git`, because `https://TOKEN@host/...` carries a token there), a query string or a fragment (`?` or `#`) is refused (`lab_links_invalid`), and the refusal does not repeat the URL: a credential is never written to the manifest. An SSH remote's login name (`git@host:lab/db.git`, `ssh://git@host/...`) is kept. `repeat_codes` are used only when the user confirmed them for this run (`--confirm-repeat-codes`, `LabLinks(repeat_codes_confirmed=True)`, `read_lab_links(confirmed=True)`; never read from the file): equal strings are not evidence. They must name every biological repeat of the published description exactly once and no other ID (compared exactly: a source folder or display name is not an ID). Each refusal is a run error reported together, before any pixel is read: `lab_links_repeat_codes_not_confirmed`, `lab_links_repeat_unknown`, `lab_links_repeat_twice`, `lab_links_repeat_missing`. **Provenance only:** the links are never written to `morphobricks.toml` (`labchronicle`, `provenance` and `source_database` stay `E_FORBIDDEN_FIELD`, `i99`), and they are in no section digest, description SHA-256, row key, staging key, mask-step check, design, table or report: a run with, without or with changed links publishes the same files apart from this key, and so the manifest's own SHA-256 (which the report records, and which later bricks that pin the manifest see change). Not a recorded input (§9.2): a run not given links records none. The reader checks the entry as the input is checked; a malformed one makes the manifest malformed. | @@ -377,7 +379,10 @@ It gives: names X before Y (for example `ZXY`) is returned Y before X, as the run read it; nothing else is reordered. The memory limit of `read_plane` (default 1 GiB) counts only reading the plane, not the histogram arrays a run needs (audit I2), and it counts reading **every - channel** (issue #344): the `(C, Y, X)` result is allocated once and filled straight from + channel** (issue #344). It is therefore another figure than the run's + (`PlaneLayout.memory_estimate`, named by `planes_read_in_blocks`: one channel read and + measured); the texts name them apart (v0.10.1: for the 30720 x 36864 x 3 `uint16` mosaic in + 1024 x 1024 chunks, 38.0 GiB for the run, 14.8 GiB for `read_plane`): the `(C, Y, X)` result is allocated once and filled straight from the decoded pages, a page holding several channels (interleaved RGB, planar samples) is decoded once for all of them, and only one page is held at a time. Before any pixel is read, `read_plane` raises `PlaneMemoryError` when the bound of that whole read @@ -430,7 +435,13 @@ It gives: decodes, hits, evictions and bytes held. The cache holds at most `cache_bytes` (a whole number above 0, below `memory_limit`; a piece larger is used once and not kept), counts in each window's memory estimate (a window whose own working memory and `cache_bytes` together are - over `memory_limit` is `WindowMemoryError`), and is safe to share between threads (a piece + over `memory_limit` is `WindowMemoryError`; an OME-Zarr image whose chunks are so large that + even a window of one pixel is over `memory_limit` with this cache is refused when the reader + is opened, `WindowMemoryError` naming the chunks and what to do, v0.10.1: a chunk is decoded + whole for any window; `check` and `run` warn about such an image first, + `chunks_too_large_for_windows`, from `window_chunks.check_window_chunks`, which counts a + cache of one chunk; `window_chunks.window_chunk_need(path, mapping)` gives that figure for a + consumer's own check), and is safe to share between threads (a piece asked by several at once is decoded once, and every thread that waited gets that decode, also when the piece is not kept; a kept piece is immutable, its bytes in a read-only buffer; the cache is per process, never shared). Pieces are kept under the image's path, the @@ -911,7 +922,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. | @@ -1220,11 +1231,11 @@ time. An opt-in helper, never run by default, computes a `binary` **region** mask from one declared RGB image with a named, versioned, fixed rule whose colour maths is normalization's (`docs/design/he-tissue-mask.md`). `RunInputs.he_tissue_mask(fov, *, output_mask_id, -rule="he_tissue_v1")` writes it and returns `TissueMaskResult` (`image`, `mask_id`, `path`, +rule="he_tissue_v2")` writes it and returns `TissueMaskResult` (`image`, `mask_id`, `path`, `line`, `published`, `reusable`, `fractions`); `RunInputs.preview_he_tissue_mask(fov, *, -rule="he_tissue_v1")` computes it in memory and returns `TissueMaskPreview` (`E`, `H`, `od`, -`od_floored` exactly as normalization returns them, the components, `fractions`, the rule record -and the code identities); it writes nothing. The command `tissue-mask` and the notebook card +rule="he_tissue_v2")` computes it in memory and returns `TissueMaskPreview` (`E`, `H`, `od`, +`od_floored` exactly as normalization returns them, the components, `fractions`, the rule record, +the code identities and `white`, the white the plane was rescaled to, `None` under v1); it writes nothing. The command `tissue-mask` and the notebook card **Make an H&E tissue mask** call them. scikit-image (the `he-mask` extra: `pip install "morphobricks-preprocessing[he-mask]"`, which installs `morphobricks-normalization[histology]`), normalization's `stain` module and the helper's module @@ -1245,6 +1256,20 @@ means fewer than N pixels, a disk is `x*x + y*y <= r*r`, the structuring element the image border (never padded or wrapped; the opening's erosion counts only pixels inside the image), and every size is in pixels: no pixel size is read or used. +**The rule `he_tissue_v2` (v0.10.1, the default; also provisional)** is `he_tissue_v1` on the plane +rescaled to its own white. v1's white is fixed at 255, so on a scan whose glass is grey (the +Zenodo 4550300 TMA cores, glass near (127, 135, 145)) every pixel reads as stained and v1 keeps +0 %. v2 estimates the white per channel as the median of the pixels whose `R + G + B` is at or +above the 99.9th percentile of `R + G + B` (NumPy, method `linear`), at least 1; rescales the plane +with normalization's `rescale_to_white` (`clip(rint(I * 255 / white), 0, 255)` as `uint8`); and +applies v1's components, thresholds and clean-up unchanged to the rescaled plane (`E`, `H` and +`od` are then the rescaled plane's). When the plane's brightest pixels are white (255) the +rescaling is the identity and v2 equals v1. The white is read from the plane, so a plane with no +glass or empty space takes its brightest tissue as white. The rule record (version 2, +`input.white` `"estimated"`, a `white` entry stating the estimate and the rescaling) is written in +the lineage like v1's; the white itself is not a lineage key (it follows from the source content +digest and the rule record). `he_tissue_v1` stays offered unchanged with `rule="he_tissue_v1"`. + **Inputs, refused before any pixel is read** (a `ValueError` naming the position): the position is resolved by its image path from `RunInputs.fovs()`, and a caller's `image_type`, axes, counts or dtype are ignored; an image that is not the run's (`RunInputsError`); a unit not declared @@ -1295,10 +1320,10 @@ object at any depth is refused in both schemas (it was kept silently before). ### 15.4 The H&E tissue mask of an array, with no run (roadmap K3) -`he_tissue_mask_array(rgb, *, rule="he_tissue_v1") -> TissueMaskArray` (owner decision of +`he_tissue_mask_array(rgb, *, rule="he_tissue_v2") -> TissueMaskArray` (owner decision of 17 November 2026: in preprocessing) computes §15.3's rule on one image array in memory, for users who have pixels but no MorphoBricks run (a script, another brick's folder command). **The -rule is the same provisional `he_tissue_v1`**, and the computation is the run route's own: the +rules are the same provisional `he_tissue_v2` (the default) and `he_tissue_v1`**, and the computation is the run route's own: the array is moved to `(3, Y, X)` and given to the one function `RunInputs.he_tissue_mask` and `preview_he_tissue_mask` call after their read (`he_tissue_mask.rule_on_plane`), never a copy, so the mask is bitwise equal to the file the run route writes for the same pixels (tested on the @@ -1319,11 +1344,12 @@ a pixel type other than `uint8`, or a shape other than `(Y, X, 3)` (R, G, B last (`ImportError` naming `pip install "morphobricks-preprocessing[he-mask]"`). The input checks import nothing of the extra; scikit-image, normalization's `stain` module and the helper's module are imported only past them, never by `import morphobricks_preprocessing`. Like the run -route it takes no pixel size (sizes are pixels), no white (fixed at 255) and no thresholds. +route it takes no pixel size (sizes are pixels), no white (fixed at 255 under v1, estimated from +the plane under v2) and no thresholds. **Result.** `TissueMaskArray` (frozen): `mask`, boolean `(Y, X)`, `True` kept (a region, BM3; being boolean, an in-memory consumer refuses it as an object set, BM4); and `record`, a frozen -`TissueMaskArrayRecord`: `rule_id` (`"he_tissue_v1"`), `operation` (`"he_tissue_mask"`), +`TissueMaskArrayRecord`: `rule_id` (`"he_tissue_v2"` by default), `operation` (`"he_tissue_mask"`), `rule_text` (the complete rule record in its canonical JSON, keys sorted and no spaces: exactly the text `rule_sha256` is the SHA-256 of, as UTF-8; `rule` returns it as a new dict, with `rule_version`, `status` `"provisional"` and `provisional`), `rule_sha256`, `code` (BM15's code @@ -1505,7 +1531,7 @@ exclude=, missing_as_singleton=, memory_limit=, progress=)` (`conversion`), the | Repeat | A copy already in the tree is reused when its source (fingerprint and axes), roles, copy axes, pixel sizes, unknown sizes (roles and reasons), channel names, significant bits, the copy's fingerprint and the copy's SHA-256 (read whole) are as recorded; a new image is added; when every copy is reused the record is kept as it was (same SHA-256). Anything else (a source changed, other roles, a copy changed, an image no longer in the experiment, another experiment's copy tree, a file at a new image's place that the record does not list) is `copy_differs`: nothing is overwritten. A conversion record that cannot be read, or of another version than 4, is `conversion_record_unreadable`. | | Conversion record | `.morphobricks-conversion.json` in the copy tree's root (a dot-file, so discovery skips it), record version 4: `source_root`, `mapping`, `projection` (null, or `{method, z_range}`: the method and slice range of a tree of Z-projected copies, see "Projected copies" below), `missing_as_singleton`, `written_at`, `versions`, and per image `relative_path`, `action` (`converted` or `copied`), `reason` (the axis code, `excluded`, or null), `source` and `copy` fingerprints (`size`, `mtime_ns`), `copy_sha256` (the copy's SHA-256, computed in one pass after it is written; an OME-Zarr copy's is the SHA-256 of its files' relative paths and SHA-256s in path order, its `labels` group left out as for fingerprints: `content_hash`), `source_axes`, `roles`, `copy_axes`, `pixel_sizes` (by role, as §9), `unknown_sizes` (role: why), `channel_names` (as the copy holds them; `[]` for none), `significant_bits` (or null), `projection` (null, or the projected copy's provenance, below) and, only for an image converted or projected into an OME-Zarr copy, `source_relative_path` (below). Sources keep the fingerprint rule (design v0.4 §1); the copies' SHA-256 is the owner's decision of 2 November 2026 (plan §12 question 59 (16)). Version 2 (PP-11c) added `copy_sha256`, `channel_names` and `significant_bits`; version 3 (issue #176) added the record-level `projection` and the entry's `projection`, and the action `projected`; version 4 (owner decision of 12 November 2026, before v0.5.2) added the entry's `source_relative_path` of an OME-Zarr copy, which a version 3 reader would ignore, looking for the source at the copy's path and warning `conversion_source_changed`. Only version 4 is read (SWEEP-PP: no backward compatibility, Spec ADR 0002 AR10): a record of any other version, 1 to 3 included, is refused everywhere it is read (`convert`, the run's `review_conversion`, `RunInputs`), never converted, with a message to convert the originals again into a new folder. `read_conversion_record(folder)` reads it with its SHA-256. | | Projected copies (issue #176, record version 3 and later) | A tree made with a Z projection holds, for every image, a 2-D copy of its Z-stack made with the record-level `projection` `{method, z_range}` (`max`, `mean` or `sum`; there is no default method; `z_range` is `[start, stop]`, zero-based, stop excluded, the same for every image, or null for every slice). An entry has the action `projected` and a `projection` object with exactly: `source_relative_path`, `source_content_sha256` (the source's content as read while writing), `source_z_axis` (`{letter, index}` of the header's Z axis, or null for an image without one, which is one slice), `source_z_size`, `z_range` (the slices actually used), `method`, `source_dtype`, `output_dtype`, `dtype_rule`, `rounding` (`none`, `float64, one division` or `float64 addition, z ascending`), `nan_policy` (`propagate`), `dropped_sizes` (`{"Z": {value, unit, source}}`, or `{"Z": null}` when the source gave no Z size: the Z size is never written to the copy) and `significant_bits_dropped` (a reason, or null: kept for `max`, dropped for `sum` and `mean`). Excluded images stay plain copies (`copied`, reason `excluded`). The output type depends only on the input type, the method and the slice count (never on the data): `max` keeps the type; `sum` of `uint8`/`uint16` is `uint32`, of `int8`/`int16` is `int32`, of `uint32`/`int32` is `float64` holding the exact integer, of floats is `float64`; `mean` is `float64`; 64-bit integers are refused (`cannot_convert_pixel_type`). A sum or mean whose worst case (the type's extreme times the slices) could not be held exactly is refused (`projection_cannot_be_exact`), never wrapped or clipped. A NaN makes its pixel NaN, infinities are kept. The reader refuses an entry whose output type or rounding is not the table's for its method, a projected entry in a record without a projection (and the reverse), and a method or range that is not the record's. The reuse key holds the projection (everything of it except the content SHA-256, which the write computes), so another method or range into the same tree is `copy_differs`. Masks are never projected: `convert_experiment(..., projection=Projection(...), masks_folder=)` scans the masks folder from the headers only and refuses, before writing anything, masks of the images to project that have depth slices (`projection_masks_3d`) or more than Y and X with axes that are not named (`projection_masks_axes_unknown`); 2-D masks are left alone. The other refusals, all before anything is written: `nothing_to_project` (no image has a Z role), `projection_z_range_outside`, `projection_cannot_be_exact`, `cannot_convert_pixel_type`, `projection_over_memory_limit` (one input plane, the running plane and, when it is another type, the output plane must fit `memory_limit`) and `projection_zarr_not_supported` (OME-Zarr images are not projected yet). The copy's OME-XML holds an `Image/Description` with the method, slices, source, source SHA-256 and types, and a UUID derived from it, so one projection of one source is the same bytes; the source's content SHA-256 is taken before and after the projection and the source fingerprint before and after, and a source that changed is refused. A sum that overflows to infinity (`projection_overflow`) or adds an infinity to its opposite (`projection_undefined`) stops the conversion and is never written. Excluded images are copied byte for byte. | -| OME-Zarr copies (v0.5.2, record version 4) | `convert_experiment(..., store="ome-zarr")` (the notebook's **Also save a copy as OME-Zarr**; default `"ome-tiff"`) writes every image that is read as an OME-Zarr image instead of an OME-TIFF: also the images whose headers name their axes as confirmed, which are otherwise copied byte for byte. Excluded images and OME-Zarr images are copied byte for byte as before. With `projection` the projected copies are OME-Zarr. A copy is named after its image with `.ome.zarr` in place of the TIFF extension, in the same folder, so its position ID is the same; two images that would get one copy name are refused (`copy_names_collide`). In the record the entry's `relative_path` is the copy's path and `source_relative_path` (a key written only for such an entry: required there and refused on any other entry, so a source is never looked for at a copy's path; other entries are written as before) is the source's path relative to `source_root`; `significant_bits` is null (OME-NGFF 0.4 has no field for it). The store is OME-NGFF 0.4 (Zarr version 2), written directly: one array `0`, uncompressed, little-endian, one chunk per plane (the whole Y and X), metadata as sorted JSON, so one copy of one source is the same bytes. Each plane is the plane read under the confirmed roles, bit for bit; the axes are the roles (`t`, `c`, `z`, `y`, `x`) with the units of the copy's sizes, the level-0 `scale` holds the sizes and 1 for an unknown one, which is named under the multiscale's `metadata.unknown_scale` and so read as unknown; channel names are under `omero.channels[].label`, each channel with the `color` (`FFFFFF`) and `window` (the pixel type's whole range as `min`, `max`, `start`, `end`) that OME-NGFF 0.4 requires, display only and never read from the pixels; a projected copy's description is under `morphobricks.description`. Reading the copies needs the `zarr` extra, as for any OME-Zarr image. Plan, lock, `.partial` writes, reuse, the copy's SHA-256 and the checks of the run on the copies are those of the other copies. | +| OME-Zarr copies (v0.5.2, record version 4) | `convert_experiment(..., store="ome-zarr")` (the notebook's **Also save a copy as OME-Zarr**; default `"ome-tiff"`) writes every image that is read as an OME-Zarr image instead of an OME-TIFF: also the images whose headers name their axes as confirmed, which are otherwise copied byte for byte. Excluded images and OME-Zarr images are copied byte for byte as before. With `projection` the projected copies are OME-Zarr. A copy is named after its image with `.ome.zarr` in place of the TIFF extension, in the same folder, so its position ID is the same; two images that would get one copy name are refused (`copy_names_collide`). In the record the entry's `relative_path` is the copy's path and `source_relative_path` (a key written only for such an entry: required there and refused on any other entry, so a source is never looked for at a copy's path; other entries are written as before) is the source's path relative to `source_root`; `significant_bits` is null (OME-NGFF 0.4 has no field for it). The store is OME-NGFF 0.4 (Zarr version 2), written directly: one array `0`, uncompressed, little-endian, in chunks of one plane by at most 1024 x 1024 pixels along Y and X (`1 x ... x min(Y, 1024) x min(X, 1024)`; v0.10.1, one chunk per plane before: see `chunks_too_large_for_windows`), written block by block as the planes are read, each edge chunk at full size with zeros (the `fill_value`) outside the image, one level only (no pyramid), metadata as sorted JSON, so one copy of one source is the same bytes. Each plane is the plane read under the confirmed roles, bit for bit; the axes are the roles (`t`, `c`, `z`, `y`, `x`) with the units of the copy's sizes, the level-0 `scale` holds the sizes and 1 for an unknown one, which is named under the multiscale's `metadata.unknown_scale` and so read as unknown; channel names are under `omero.channels[].label`, each channel with the `color` (`FFFFFF`) and `window` (the pixel type's whole range as `min`, `max`, `start`, `end`) that OME-NGFF 0.4 requires, display only and never read from the pixels; a projected copy's description is under `morphobricks.description`. Reading the copies needs the `zarr` extra, as for any OME-Zarr image. Plan, lock, `.partial` writes, reuse, the copy's SHA-256 and the checks of the run on the copies are those of the other copies. | | The run on the copies | The user runs preprocessing on the copy tree with the same output folder (`--output`): the recorded experiment root becomes the copy tree and the report says so (`experiment_root_changed`, and `conversion` with the record, its SHA-256 and `source_root`; the text says "named-axis copies of ..."); every row is recomputed (the row key includes the read path, §9); the design, image type and calibration are kept (same relative paths). The manifest records `conversion_record_sha256`, and for projected copies the `projection` summary (§9); the report says "max projections of slices 1:4 (2 images) of " (and `conversion.projection` in `discovery_report.json`). Masks are paired as usual (the image has no Z now, so 2-D masks fit; a mask with depth slices stays `mask_planes_mismatch` and stops the run), and the run warns `masks_on_projected_images`, naming the method, for masks paired with projections, in the report and the manifest's `projection.warnings`. The run and `check` warn when a source changed or went missing after the conversion (`conversion_source_changed`) and refuse a copy that changed (its fingerprint or its SHA-256: each copy is read whole, so `check` and `run` on a copy tree cost one more read of the copies), went missing or was added since (`copy_changed_after_conversion`: an error since PP-12, owner decision of 2 November 2026; the run stops after the header checks, before any pixel is read, writing only its report, since `RunInputs` would refuse the run; the message says to convert the originals again into a new folder); an unreadable record stops the run (`conversion_record_unreadable`). `check` and `run` also read the OME `Image/Description` header (first page's description tag only, no pixels) of every analysed TIFF the record does not list as `projected`: a description that begins "MorphoBricks Z projection:" in a tree with no record, or whose record does not list the image as projected, is refused as `projection_record_missing` (owner decision of 8 November 2026; plain images are unaffected). `RunInputs` reads the copies like any images, and refuses a run whose conversion record changed or went missing since (`conversion_record_sha256`), is of version 1, or whose recorded images' copies no longer have the recorded fingerprint and SHA-256 (§9.1). | | Notebook (PP-11b) | Step 2's **Make named-axis copies (optional)** card, under the axis check, shown only when it reports images with `axes_yx_swapped`, `axes_contradict_header`, `axes_x_before_y` or `axes_not_named` for the roles being edited (design v0.4 §5: offered only for files with errors), and not with `folder_step(show_output=False)`. The roles are the user's: those confirmed in step 2, or the roles shown once the preview is checked and the card's own question is answered; any change of a role or of the missing-axes answer takes it back. A required folder for the copies (Browse…, or pasted) checked with the command's rule (`copy_folder_issues`); `preview_conversion` (`conversion_plan`, headers only, writes nothing) gives what will be converted and copied byte for byte (the command's `plan_conversion`), the space needed and the free space; then `convert_experiment` with a progress bar, under the copy tree's lock. Refusals use the existing cards (the lock card with **Remove the lock of a stopped run**, the rule of `--remove-stale-lock`). After the copies: the record's path, and **Check the copies in step 1**, which sets the experiment folder to the copy tree, keeps the output folder and checks again; the card says that the missing-axes answer must be given again and lists the copies whose relabelled sizes are unknown (`ConversionResult.unknown_sizes`), to state under **Pixel sizes**. | @@ -1751,7 +1777,12 @@ no image of the run. **21.2 Entry refusals** (`entry_errors`). `EntryError` (`code`, `message`, `fix`, `subjects`; `as_json()` for the command line's stderr): `ENTRY_SETTING_MISSING`, `ENTRY_SETTING_INVALID`, `ENTRY_OUTPUT_PLACE`, `ENTRY_OUTPUT_EXISTS`, `ENTRY_OUTPUT_INCOMPLETE`, `ENTRY_IDENTITY_UNCERTAIN`, -one constructor each, with the ADR's texts under its revision R2 (choices are settings). +one constructor each, with the ADR's texts under its revision R2 (choices are settings). Ahead of +the ADR (v0.10.1, plan §12 question 93): when the brick is a released install and a library of +its identity is what is uncertain, the fix of `ENTRY_IDENTITY_UNCERTAIN` cases (a)-(c) names that +library and why (`uncertain_code_fix`: no `RECORD`, with the `pip install --force-reinstall +--no-deps "=="` that writes one, or an editable install) instead of telling the +user to reinstall the brick. **21.3 Settings** (`entry_settings`, `entry_declaration`). A brick declares its settings in its ADR 0011 `defaults.toml` plus a static `entry_settings.json` keyed `
.` (`type`, @@ -1768,7 +1799,13 @@ canonical JSON (sorted keys, UTF-8, LF), written last: `entry_version` (1), `bri `source`, `resolver`, `settings`, `execution`, `locations`, `outputs`, `identity` (the SHA-256 of the canonical JSON of `entry_version`, `brick`, `run_folder` without its path and the table's file SHA-256, `resolver`, and the settings with `affects_values`) and `written_at`. Reuse or refuse -(`reuse_or_refuse`) follows ADR 0007 RE10; publication is exclusive (`publish`). +(`reuse_or_refuse`) follows ADR 0007 RE10; publication is exclusive (`publish`). The libraries +of `brick` are the brick's requirements, directly or through another, every extra included, +**except the installers `pip`, `setuptools` and `wheel`** (`entry_identity.INSTALL_TOOLS`, v0.10.1, +plan §12 question 93), which are neither listed nor followed; a name the brick passes in +`libraries` is identified whatever it is. `write_entry_record` of a record whose `brick` is +`uncertain` writes it and warns (`EntryIdentityWarning`, text `identity_warning`) that the output +will never be reused, naming the reason and the fix. **21.5 Test helpers.** `testing_spy.decoder_spy` counts every pixel-decoding route; `testing_folder_states.derive_state` and `report_state` make the folder states of ADR 0007 row E2. diff --git a/docs/design/he-tissue-mask.md b/docs/design/he-tissue-mask.md index 753407da..9631ac0f 100644 --- a/docs/design/he-tissue-mask.md +++ b/docs/design/he-tissue-mask.md @@ -184,6 +184,65 @@ changes v1. The complete rule record (below) and its SHA-256 are written to the tuned per image, and nothing is tuned silently. The preview and the "% kept" figure are how the user judges whether the rule suits their slides. +### `he_tissue_v2`: the white estimated from the plane (v0.10.1) + +**Why (3 December 2026).** On the Zenodo 4550300 H&E TMA cores (set B of criterion 3; 2048 x 2048 +`uint8` RGB, photometric tag wrongly MINISBLACK, read with `rgb_header_override = true`), +`tissue-mask` kept **0.0 %** of every core, so fiberfeatures measured `roi_area_px = 0`. The +channels are R, G, B in order (the override is applied before the rule) and the mask is not +inverted: the scanner's glass is near **(127, 135, 145)**, not 255, and the brightest pixel of +1B_D9 is (138, 154, 154). Against v1's fixed white of 255 every pixel has `OD >= 0.22`, so the +background (`max(OD) < 0.08`) never fires and `H >= 0.05` holds everywhere: the whole plane was +"nuclei" (`fractions` `nuclei` 1.0). + +**The rule.** `he_tissue_v2` is v1 on the plane rescaled to its own white: + +1. the white, per channel: the median of the pixels whose `R + G + B` is at or above the 99.9th + percentile of `R + G + B` (NumPy `percentile`, method `linear`), raised to at least 1 + (`he_tissue_rule.estimate_white`; counting only, no colour maths); +2. the plane rescaled with normalization's `rescale_to_white` (N69: + `clip(rint(I * 255 / white), 0, 255)` as `uint8`, `rint` half to even); +3. v1's components, thresholds and clean-up, unchanged, on the rescaled plane (`E` and `H` from + `he_eosin`, `OD` against 255). + +No threshold or size of v1 changed (the record's `components` are v1's). The record is version 2, +`input.white` `"estimated"`, with a `white` entry stating steps 1 and 2; v1 is unchanged and +still offered (`rule="he_tissue_v1"`). v2 is the default of `RunInputs.he_tissue_mask`, +`preview_he_tissue_mask`, `he_tissue_mask_array`, `tissue-mask` and the notebook card. Both are +provisional; the acceptance criteria above apply to v2 as they did to v1. The estimated white is +in the preview (`TissueMaskPreview.white`), not in the lineage line, whose source digest and rule +record determine it (the BM15 line keys are unchanged). + +**Measured (3 December 2026, scikit-image 0.26.0, normalization v0.10.0).** Kept share: + +| Image | v1 kept | v2 white | v2 kept | v2 background | v2 nuclei | +| --- | --- | --- | --- | --- | --- | +| Zenodo `1B_D9_WB.tif` (SHA-256 `8c74cadd…`) | 0.00 % | (130, 138, 149) | 46.8 % | 41.9 % | 11.3 % | +| Zenodo `2B_A6_WB.tif` (SHA-256 `6e49f686…`) | 0.00 % | (127, 134, 142) | 44.4 % | 52.6 % | 2.9 % | +| Zenodo `1B_F3_WB.tif` | 0.00 % | (136, 147, 168) | 52.6 % | 28.4 % | 19.1 % | +| Zenodo `2B_G5_WB.tif` | 0.00 % | (141, 143, 153) | 40.6 % | 44.7 % | 14.8 % | +| Zenodo `2B_H2_WB.tif` | 0.00 % | (141, 142, 152) | 38.3 % | 44.7 % | 17.0 % | +| Zenodo `2B_G3_WB.tif` | 0.00 % | (141, 143, 152) | 29.8 % | 66.4 % | 3.8 % | +| Zenodo `2B_E9_WB.tif` (a thin strip of tissue) | 0.00 % | (127, 134, 143) | 7.2 % | 85.8 % | 7.0 % | + +(the seven cores of the record's `validation2.zip`, SHA-256 `f7eb874b…`). On CMU-1 (set A, white +glass), 33 tiles of 1024 x 1024 at level 1 with at least 5 % tissue: the estimated white is +251 to 255 in every channel and v2's kept share is within 0.4 points of v1's on every tile; the 12 +level-1 tiles of 512 x 512 with the least near-white (2 to 7 %): Dice of v1 and v2 masks 0.978 to +0.998. Blank slides (uniform 255, glass at 242 or at (127, 135, 145) with noise): 0 % kept under +both rules. The PI-1 to PI-4 images (owner's, not public) were not rerun; their v1 numbers above +stand, and v2 equals v1 on any plane whose brightest 0.1 % are white. + +**Limitation.** The white is read from the plane: a plane with no glass, lumen or fat (tissue +from edge to edge) takes its brightest tissue as white, and pale tissue then moves towards +background. The preview and the printed kept share show it; `rule="he_tissue_v1"` is the choice +for such planes on a white-balanced scanner. + +**Regression fixture.** `tests/data/he_core_1B_D9_crop.npz`: rows 500-819, columns 80-399 of +`1B_D9_WB.tif` (CC-BY-4.0, Eliceiri, Li, Keikhosravi 2021, doi 10.5281/zenodo.4550300), written by +`tests/data/make_he_core_crop.py` from the checked zip. v1 keeps 0 % of it, v2 35.0 % +(`tests/test_he_tissue_v2.py`, also through a run with the header override). + ### The canonical rule record The rule is defined once, as an immutable record in the helper's module, and written whole into diff --git a/docs/plan.md b/docs/plan.md index a391f787..affaaa31 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -1819,3 +1819,66 @@ Raised during review; to be decided before the milestones that need them: hashes is `RUN_FOLDER_CONTENT_NOT_RECORDED` (ahead of the ADR, Spec issue 84); masks stay `fingerprint` for now (the run records no mask hash; a separate issue). +93. Why was an entry output never reused in a conda environment, and what is left out of the + code identity? *Decided (3 December 2026, in the session fixing the v0.10.0 wave's + entry-identity gap; for the owner's review):* conda installs `setuptools` as an `.egg-info` + with no `RECORD`, and the identity's closure, every extra included, reached it, so every + record was `uncertain` (ADR 0007 (b)) and every rerun refused. The installers `pip`, + `setuptools` and `wheel` leave the closure (`entry_identity.INSTALL_TOOLS`): they install and + build distributions and no brick computes a value with them, so they are not libraries "the + brick may compute with". The smallest change the ADR allows: dropping extras would make the + identity weaker than MorphoFeature's `brick_cache` key (which takes every extra) and would not + remove `setuptools`, which some libraries require with no extra (torch on Python 3.12); + identifying an `.egg-info` by name and version would contradict ADR 0007 (b), which keeps + every other library without a `RECORD` uncertain. A first run under an uncertain identity now + warns that its output will never be reused (`EntryIdentityWarning`), and the refusal's fix + names an uncertain library rather than the brick. The ADR's record paragraph is to say that + the installers are not followed (a Spec note for the owner). + +94. How should the command line close the gaps a new user met before the next brick (v0.10.1, + pull request 620)? *Proposed by the session that built pull request 620 (3 December 2026), + pending the owner's review* (the owner did not decide these choices explicitly): the + image-type suggestion of `check` + and `run` follows the published description when it declares every acquisition `rgb` (no + marker is written into OME-Zarr copies: OME-NGFF 0.4 has no colour field); an image type + recorded by an earlier run still comes before the suggestion (`--image-type`, then the + 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. + *Decided (owner, 4 December 2026), folded into v0.10.1 before its release:* `describe --id + FOLDER=ID` (fast mode, repeatable) names any condition, biological-repeat or + technical-repeat folder's ID, checked with the notebook's rules (`Draft.confirm_id`), so a + folder named `control` (`E_FORBIDDEN_FIELD`) is no dead end; a refusal names the option, + and the open-question line offers only options that can answer it (never `--accept-ids` + for an ID with no proposal); a label used at two levels takes `condition:`, `repeat:` or + `technical:`. `tissue-mask` creates the run's masks folder when there is none + (`_masks` beside the experiment, or the empty folder `--masks` names), records + it by running preprocessing again with it, as `run --masks` records one, and says so in one + line; its refusals name the image once, and its next steps give the `declare-masks`, `run` + and `masks` commands and the region as `region_mask` in a brick's settings. + `A_DESCRIPTION_REQUIRED` names both routes that publish a description (the notebook, and + `describe --publish`). `declare-masks --ignore TYPE` (repeatable) lets runs skip an + OME-Zarr label image or mask type they do not use; undeclared types not listed are still + refused, and the refusal's fix names `--ignore` beside `--type`. Where the list lives was + asked the same day (the description is closed by the Spec): *Decided (owner, 4 December + 2026):* a TOML file beside `morphobricks.toml`, `ignored_masks.toml`, recorded in the run + manifest (`ignored_masks`, with its SHA-256); the owner also asked for a review of how many + files the output folder holds, and a consolidation if it gets out of hand (a follow-up). +95. Should an experiment folder be allowed to link to images kept elsewhere (the owner's run of + the formin OME-Zarr mosaic, 4 December 2026: `exp/ctrl/rep1/formin_mosaic.zarr -> + /data/formin_mosaic.zarr` was refused with `link_outside_folder` and no image was found)? + *Kept for v0.10.1 (pull request from `fix/symlink-and-plane-memory`, 4 December 2026), as + question 64 decided:* the rule stays "contain"; the message now says that the images + behind the links are not found and why (a run reads, fingerprints and records only what is + inside the selected folder; a file behind a link out can change or move through its other + path unseen), and the fix says to move the data in (instant on the same drive) or to put + the experiment's folders on the drive that holds it. *Proposed, pending the owner's + decision:* an explicit opt-in, for example `run --follow-links` / `describe + --follow-links` and a notebook tick, recorded in the run manifest so that the run's + identity and fingerprints cover the link targets (their real paths, sizes, modification + times and inventory digests, with the content SHA-256 under `--verify-content`), and that + `RunInputs.open` and the bricks refuse a folder whose links lead elsewhere than recorded. + The trade-off: no move or reorganisation of large data, against a run whose inputs live + outside the folder it names (another user or a sync tool can change them; `linked_twice` + and the mount-point rule still apply). Not built until decided. diff --git a/docs/user_guide.md b/docs/user_guide.md index 1d4ade7c..61660f26 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -3,16 +3,21 @@ The preprocessing brick reads an experiment folder of microscopy images (TIFF or OME-Zarr) and computes one intensity histogram for every 2D plane. The histograms, with each plane's labels, are -saved in `plane_histograms.csv`. Later MorphoBricks bricks (for example patch extraction) -use this table to normalise images per condition, repeat or image without reading the -pixels again. +saved in `plane_histograms.parquet`. Later MorphoBricks tools (for example patch extraction) +use this table to calculate normalisation parameters per condition, repeat or image without +reading the pixels again. + +New to the command line? Start with the [quick start](#quick-start-from-a-terminal) after +the installation section. The brick **never changes your images** and never normalises them itself. It writes only to its own output folder, which is never inside the experiment folder. ## 1. Installation -You need Python 3.11 or newer and JupyterLab (or Google Colab). Download +For the notebook, you need Python 3.11 or newer and JupyterLab (or Google Colab). For the +command line only, see [Installing for the command line](#installing-for-the-command-line) +below. Download [`notebooks/MorphoBricks_Preprocessing.ipynb`](../notebooks/MorphoBricks_Preprocessing.ipynb), open it and run its three code cells in order: @@ -64,12 +69,12 @@ To install everything manually instead, run these commands in the environment us your notebook kernel: ```bash -pip install "morphobricks-preprocessing[notebook] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git" -pip install jupyterlab +python -m pip install "morphobricks-preprocessing[notebook] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" +python -m pip install jupyterlab ``` To read OME-Zarr images, install the `zarr` extra too: -`pip install "morphobricks-preprocessing[notebook,zarr] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git"`. +`python -m pip install "morphobricks-preprocessing[notebook,zarr] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1"`. Start JupyterLab with `jupyter lab` and open the notebook. **Browse…** opens your computer's folder dialog; where no dialog can open (Google Colab, a remote server), it says so and you @@ -128,6 +133,48 @@ Google Drive is wiped when it disconnects (after some idle time, or after severa run. Untick it (CLI `--no-verify-content`) to compare size and time only; the manifest then records `verify_content: false`. An output folder keeps the choice of its earlier run. +### Installing for the command line + +You need Python 3.11 or newer, Git and an internet connection. We recommend installing into a +new Python virtual environment. JupyterLab is not required for command-line use. + +```bash +python -m pip install "morphobricks-preprocessing @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" +``` + +To read OME-Zarr images, or to make the optional H&E tissue mask (`tissue-mask`, §5), install +the extras too: + +```bash +python -m pip install "morphobricks-preprocessing[zarr,he-mask] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" +``` + +The package is installed from GitHub; it is not on a package index. + +## Quick start from a terminal + +This is the shortest route for an experiment whose images all have the same channels in the +same order. §5 explains each step and what to do when your experiment differs. + +```bash +morphobricks-preprocessing describe my_experiment +morphobricks-preprocessing describe my_experiment --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +morphobricks-preprocessing check my_experiment +morphobricks-preprocessing run my_experiment +``` + +1. The first `describe` shows the proposed IDs and the open questions. It writes nothing. +2. The second `describe` publishes the experiment description. Every preprocessing run needs + it. Give `--comparable` only if the samples of each biological repeat were prepared and + acquired comparably. +3. `check` inspects the folders, image headers and masks, and writes a report. +4. `run` computes the histograms and writes the output folder, + `my_experiment_MorphoBricks_Preprocessing`. + +If your analysis uses masks, declare them and run the `masks` command after preprocessing +(§5, "Declaring existing masks or adding new masks"). + ## 2. Organising the experiment folder The folder you select is the **experiment folder**. Below it, up to three levels of folders @@ -184,9 +231,12 @@ experiment/ `.DS_Store`, `Thumbs.db`, `desktop.ini` and `__MACOSX` are ignored without a message. - Links (symbolic links, and junctions on Windows) are followed only when they stay inside the experiment folder; the same holds for the masks folder. A link to a file or folder - outside it is an error (`link_outside_folder`) naming the link and its target: nothing - outside the folder you selected is read, so copy the data in or select a folder that - holds it. A link back to a folder above it is an error (`link_loop`), and so is one file + outside it is an error (`link_outside_folder`) naming the link and its target, and the + images behind it are not found: a run reads, fingerprints and records only what is inside + the folder you selected, so a file reached through a link out could change or move without + the run seeing it. Move (do not copy) the data into the folder: on the same drive a move is + instant, however large the image. Or put the experiment's folders on the drive that holds + the data and select that folder. A link back to a folder above it is an error (`link_loop`), and so is one file reached by two paths, a link and its target or two hard links (`linked_twice`): it would count twice. - A mounted folder inside the experiment or masks folder (another disk, a network share, or @@ -218,10 +268,34 @@ masks/ control/bio_rep1/tech_rep1/img_02.tif ``` -- Or keep the masks in the same folders as the experiment, each named after its image - followed by `_` and its kind (`img_01_cells.tif`, `img_01_nuclei.tif`), as many - segmentation tools write them; the kind is the part after the image name. Both ways may be - mixed in one masks folder. +- OME-Zarr label images are discovered automatically. External TIFF masks must be stored in a + separate masks folder. Give that folder with `--masks`, unless an earlier preprocessing run + already recorded it. +- Inside the masks folder, a mask type can be named in one of two ways. Both ways may be mixed + in one masks folder. + + **(a) One subfolder per mask type**, each mask named exactly as its image: + + ``` + my_experiment/ctrl/image_01.tif + my_masks/Cells/ctrl/image_01.tif + ``` + + Declare it with `--type Cells=instances` (§5, `declare-masks`). + + **(b) The mask type as the file-name ending**, after the image name and `_`, in the + experiment's folders. Cellpose names its masks this way: + + ``` + my_experiment/ctrl/image_01.tif + my_masks/ctrl/image_01_cp_masks.tif + ``` + + The mask type is `cp_masks`. Declare it with `--type cp_masks=instances:Cells`: the ending, + then the mask ID you want to use. + + Do not combine the two. A file `my_masks/Cells/ctrl/image_01_cp_masks.tif` matches no + image: the run warns and leaves it out. - A mask is a TIFF label image with the width and height of its image: background 0, each object its own whole number (or a true/false mask). The extension may differ from the image's (`img_01.tiff` for `img_01.ome.tif`). @@ -240,13 +314,16 @@ masks/ starts another's (`a.tif` and `a_b.tif`), a mask named `a_b_cells.tif` could belong to either and is refused: rename the masks or the images. - The label images stored inside an OME-Zarr image (its `labels` group) are used as masks - too, named after the label image. + too, named after the label image, except for mask types listed in `ignored_masks.toml` + (§5, `declare-masks --ignore`). - An image without a mask of one kind is reported; its objects of that kind cannot be measured. -Masks do not change `plane_histograms.csv`. They are checked and recorded for the bricks -that measure objects; the optional `masks` command (§5), or **Describe the masks** in the -notebook's step 3 (§4), also tells how they relate. +Masks do not change `plane_histograms.parquet`. They are checked and recorded for the bricks +that measure objects. If your analysis uses masks, run the `masks` command (§5), or +**Describe the masks** in the notebook's step 3 (§4), after preprocessing. It checks the mask +pixels against their declared representation and reports relationships between mask types. +Skip this step only if the downstream analysis does not use masks. ### Making masks with Cellpose (optional) @@ -451,10 +528,23 @@ run the experiment in the app of cell 3. Then: images must have their dimensions in the same order; the number of slices, time points and the size may differ. OME-Zarr images may store them in another order: they are matched by role, so z = 2, c = 1 means the same slice and channel in every image. -- **Channels:** all images of an experiment must have the same number of channels (an - image without a channel dimension has one). Split images with other channels into a - separate experiment, or exclude them. -- **RGB images:** the three colour samples are treated as channels (C). +- **Channels:** images within one acquisition folder must have a consistent channel layout + (an image without a channel dimension has one channel). Different acquisitions may have + different channel lists or orders when each is described separately in the notebook. The + simple command-line publication workflow requires one shared channel list and order for the + experiment. Later analysis tools may require the selected channel to be present in every + image being analysed. +- **RGB images:** RGB images must have exactly three colour channels containing red, green and + blue in that order, with an integer pixel type. Declare them using `--image-type rgb + --channels R,G,B`. TIFF files whose headers do not identify their interleaved colour samples + as RGB may need `--rgb-header-override`. OME-Zarr colour images must be declared RGB + explicitly. The three colour samples are treated as channels (C). The optional + `tissue-mask` command has narrower requirements: 8-bit RGB, one depth plane and one time + point. +- **Image type names:** the experiment description records separate-channel images as + `channels` and colour images as `rgb`. The `run` command's `--image-type` option uses the + older name `fluorescence` for separate-channel images. In the normal described workflow, use + the published description as the authoritative record of what your channels represent. - **Pyramidal images:** only the full-resolution level is read. - **Not supported yet:** files with several positions or scenes (several image series), and position or tile axes. Export each position as its own file. @@ -847,60 +937,99 @@ On Google Colab, cell 3 asks Colab not to put its output in a frame that scrolls ## 5. Command line -The same checks and computations are available from a terminal: - -```bash -morphobricks-preprocessing check /data/exp1 -``` +**Before you start.** Every preprocessing run needs a published experiment description +(`morphobricks.toml` in the output folder). `check`, `run` and `masks` refuse an experiment +without one: they print `A_DESCRIPTION_REQUIRED`, write nothing and exit with status 1. Publish +the description first, with `describe ... --publish` (below) or in the notebook's describe +steps. -prints what will be analysed, the label tree, the number of images per condition and -biological repeat (with `!` marking unbalanced ones), the problems found and the -suggested axis roles, for example `--axes ZCYX`. Then: +**A complete workflow.** This example assumes that every image contains collagen and +fibronectin in that order, that the image axes are named correctly, and that your biological +repeats were prepared and acquired comparably. Replace the channel names and date with your +own. Review the proposed IDs before accepting them. If these assumptions do not fit your +experiment, use the relevant instructions below. ```bash -morphobricks-preprocessing run /data/exp1 --axes ZCYX +# 1. Preview the draft description: proposed IDs and open questions (writes nothing) +morphobricks-preprocessing describe my_experiment +# 2. Publish the description +morphobricks-preprocessing describe my_experiment --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +# 3. Check the folders, image headers and masks +morphobricks-preprocessing check my_experiment +# 4. Compute the histograms +morphobricks-preprocessing run my_experiment ``` -`--axes` gives one role per dimension of the images, in their order: `X`, `Y`, `Z`, `C`, -`T`, or `-` for a length-1 dimension without a role. It is needed only when some images are +Your experiment is now described, checked and processed. The default output folder is +`my_experiment_MorphoBricks_Preprocessing`. Give this folder to the MorphoBricks tool that will +analyse your images. + +- Fast publication from the command line creates a new description for an experiment with a + shared channel layout. Use the notebook to edit an existing description, change repeat + pairing or describe acquisitions with different channel lists or orders. +- Give `--comparable` only if the samples of each biological repeat were prepared and acquired + comparably. Never give it just to get past the question. +- If `describe` refuses to publish because some image headers do not name their axes or state + their channel count, name the axes with the notebook or with `convert` (below). +- If your analysis uses masks, declare them, run preprocessing with them and run the `masks` + command ("Declaring existing masks or adding new masks", below). +- To state pixel sizes the images do not record, use `calibrate` (below), then run + preprocessing again. + +**What `check` does.** `check` inspects the folders, image headers and supplied masks, and +suggests axis roles. It does not measure image pixels or perform every validation of the +published description. `run` validates the description and confirmed axis roles before +processing. `check` prints what will be analysed, the label tree, the number of images per +condition and biological repeat (with `!` marking unbalanced ones), the problems found and the +suggested axis roles. + +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. To check other images or +masks than the earlier run used, give `check` the `--exclude`, `--masks` and `--mask-axes` +options you will give `run`. + +**Axis roles (`--axes`).** `--axes` gives one role per dimension of the images, in their +stored order: `X`, `Y`, `Z`, `C`, `T`, or `-` for a length-1 dimension without a role. For +example, `--axes CYX` is for images stored as channels, then rows, then columns. A Z axis is +allowed only with one slice: multi-slice Z-stacks are refused in this release (make 2-D +projections with `convert --project`, below). `--axes` is needed only when some images are plain stacks, whose metadata do not name their axes: when every image names all its axes, -`run` uses those roles without `--axes` (it prints **Axis roles (as every image names -them)**; design v0.4 §3), and they are still checked as below. A later `run` in the same output folder needs neither the roles nor -the experiment folder again, unless plain stacks were added or changed: +`run` uses those roles without `--axes` (design v0.4 §3), and they are still checked as below. +A later `run` in the same output folder needs neither the roles nor the experiment folder +again, unless plain stacks were added or changed: ```bash -morphobricks-preprocessing run --output /data/exp1_MorphoBricks_Preprocessing +morphobricks-preprocessing run --output my_experiment_MorphoBricks_Preprocessing ``` -uses the experiment folder and everything else the earlier run recorded there. Without an -experiment folder and without an output folder of a v0.4.0 run, `run` stops with -`experiment_not_recorded`, naming what is missing. Giving an experiment folder other than +uses the experiment folder and everything else the earlier run recorded there. If no +experiment folder has been recorded, give the experiment folder explicitly (otherwise `run` +stops with `experiment_not_recorded`). Giving an experiment folder other than the recorded one (for example after moving it) is reported as a change: every row is read again from the new place, and images that do not name their axes (plain stacks) must be confirmed again with `--axes`. Both commands check the axes (§4, step 2): `check` with the suggested roles, which are the headers' own, so only the `axes_not_named` warning of plain stacks can appear there; `run` -with the roles given in `--axes`. They print **Axes checked: every image names its axes in -its metadata, and the roles agree with them** when all is well (and name the plain stacks -whose roles are recorded as confirmed), or the errors naming the images, the likely cause -and the two fixes, and `run` stops (exit status 1). - -`--image-type fluorescence` or `--image-type rgb` gives the image type (§4, step 3). -Without it, `run` uses the type suggested from the image headers and prints it, with why it -was suggested and how to choose the other one; `check` prints the suggestion too. `rgb` -for images that are not three channels of a whole-number pixel type stops the run -(`rgb_not_possible`). - -`check`, `run` and `masks` need the experiment description published in the output folder -(`morphobricks.toml`, v0.5.1): the conditions, which biological repeats pair across conditions -and that they are comparable, the channels and the masks, answered in the notebook's describe -steps and saved with *Check and save*. Without it they print `A_DESCRIPTION_REQUIRED` with what -to do, write nothing and exit with status 1. `describe` shows the draft description of the -folders and every question still open. The run writes `experiment_design.csv`, derived from the -description (an output for later bricks; nothing reads it back). `check` and `run` write the -report, `discovery_report.json` and `discovery_report.txt`, to the output folder; `run` writes -it on every run, also one that stops (`status` `stopped` or `written`, with the SHA-256 of the +with the roles given in `--axes`. When all is well they say that every image names its axes +and the roles agree (and name the plain stacks whose roles are recorded as confirmed); +otherwise they print the errors naming the images, the likely cause and the two fixes, and +`run` stops (exit status 1). + +**Image type.** The experiment description records separate-channel images as `channels` and +colour images as `rgb`. The `run` command's `--image-type` option uses the older name +`fluorescence` for separate-channel images. In the normal described workflow, use the +published description as the authoritative record of what your channels represent. Without +`--image-type`, `run` uses the earlier run's type, else the type suggested from the published +description and the image headers, and prints it; `check` prints the suggestion too. `rgb` for images that are not three +channels of a whole-number pixel type stops the run (`rgb_not_possible`). + +**Reports.** `describe` shows the draft description of the folders and every question still +open. The run writes `experiment_design.csv`, derived from the description (an output for +later tools; nothing reads it back). `check` and `run` write the report, +`discovery_report.json` and `discovery_report.txt`, to the output folder; `run` writes it on +every run, also one that stops (`status` `stopped` or `written`, with the SHA-256 of the manifest it describes). A run that stops says so, says that no table or manifest was written, and names what it did write: the report. Only a run refused before it starts (another run holds the lock, or no description is published) writes nothing. @@ -924,20 +1053,39 @@ the same bytes in every file except that time (and the manifest SHA-256 the repo | `--memory-limit SIZE` | Working-memory limit per plane, e.g. `2GiB` or `1.5GiB`: a whole number of bytes above 0 (`1.5` or `0.5B` are refused before anything is read) | | `--workers N\|auto` | How many images are read at once, each in its own thread (default 1: one after another). `auto`: at most the number of CPUs, and with `--max-ram` as many as the largest image's estimated working memory fits. The results are exactly the same with any value; it is not recorded and changes nothing on the next run | | `--max-ram SIZE` | With `--workers auto`: the memory the run may use, e.g. `8GiB` (256 MiB of it kept for the run itself). An image that alone needs more stops the run before any pixel is read (`image_over_max_ram`) | -| `--missing-as-singleton`, `--no-missing-as-singleton` | Confirm that images lacking some dimensions have one plane along them (`check` and `run`; default: the earlier run's answer, else no). `check` then reports what `run` will: an experiment of 2D images and Z-stacks passes `check` once confirmed, and the suggested option says `--axes ZCYX --missing-as-singleton` | +| `--missing-as-singleton`, `--no-missing-as-singleton` | Confirm that images lacking some dimensions have one plane along them (`check` and `run`; default: the earlier run's answer, else no). Confirm that a dimension absent from an image has size 1. This can reconcile missing length-1 dimensions, but does not permit multi-slice Z-stacks. Project Z-stacks to 2-D before preprocessing (`convert --project`) | | `--image-type fluorescence\|rgb` | The image type (default: the earlier run's, else the suggested one, printed) | | `--mode restart\|full` | `restart` (default) reuses the rows of unchanged images; `full` recomputes every row and check. Both keep your confirmations and replace the results only when the run succeeds | | `--verify-content`, `--no-verify-content` | Reuse rows (earlier or staged) only when each image's content SHA-256 is the one recorded with them, not only its size and modification time; every image is read once more. Default: the earlier run's choice, else on; `--no-verify-content` opts out and the manifest records it. Turning it on or off recomputes every row. With `masks`: also compare each mask's content SHA-256 before and after it is read (same default) | -| `--lab-links FILE` | A JSON file of lab-tool links (for example LabChronicle), recorded in `run_manifest.json` only (`lab_links`): exactly the keys `repository_url`, `commit` (the full 40- or 64-character lowercase SHA) and `experiment_path`, as non-empty text, and optionally `repeat_codes`, which maps each lab-tool repeat code to a biological repeat ID of the description (for example `{"R001": "rep1"}`). Any other key, a value of another type, an empty value, spaces around a value, or a key given twice is refused before anything is read (`lab_links_invalid`). A `repository_url` holding a credential (a password, `user:password@`, in any form; a user name before `@` in a URL whose scheme is not `ssh`, `git+ssh` or `ssh+git`, because `https://TOKEN@host/...` carries a token there), a query string or a fragment (`?` or `#`) is refused (`lab_links_invalid`), and the refusal does not repeat the URL: a credential is never written to the manifest. An SSH remote's login name (`git@host:lab/db.git`, `ssh://git@host/...`) is kept. The links change no result: no row, digest, cache or other file. They are not taken over by the next run: give the file to each run it belongs to. Not offered by the notebook | +| `--lab-links FILE` | Record optional lab-tool provenance from a JSON file. See "The lab-links file" below the table for its format. Does not change the image measurements. | | `--confirm-repeat-codes` | Confirm the `repeat_codes` of `--lab-links` for this run. The run prints each pair; without this option a file with repeat codes is refused (`lab_links_repeat_codes_not_confirmed`), also when a code is spelled like the ID: the lab tool's codes and the description's IDs are separate names | | `--no-masks` | Drop the masks folder an earlier run recorded, with the mask axes stated for its masks (those of OME-Zarr label images are kept) | | `--no-exclude` | Clear the exclusions an earlier run recorded, so every image is analysed again (not together with `--exclude`) | | `--remove-stale-lock` | Remove the lock left by a run that was stopped or whose computer restarted (`check`, `run`, `masks` and `calibrate`); give it only when no other run uses the output folder, on any computer (only Linux and macOS can tell whether a process on this computer still runs) | | `--outlier-limit N`, `--saturation-limit FRACTION`, `--min-images N` | Limits of the intensity checks printed after the run (default 3, 0.01 and 5) | -| `--log FILE` | Write technical details to a file (`run`, `masks`, `convert`). It is checked before anything is written and opened only once the other options are checked: a file inside the experiment or masks folder (given or recorded by the earlier run), inside the folder of the copies (`convert`), or named as one of the run's files in the output folder (`plane_histograms.csv`, `run_manifest.json`, the reports, `experiment_design.csv`, `calibration.csv`, `mask_relationships.json`, the lock) is refused and nothing is written; so is a file that is a hard link (it has another name). Any other name in the output folder is fine, for example `run.log` | +| `--log FILE` | Write technical details to a file (`run`, `masks`, `convert`). It is checked before anything is written and opened only once the other options are checked: a file inside the experiment or masks folder (given or recorded by the earlier run), inside the folder of the copies (`convert`), or named as one of the run's files in the output folder (`plane_histograms.parquet`, `run_manifest.json`, the reports, `experiment_design.csv`, `calibration.csv`, `mask_relationships.json`, the lock) is refused and nothing is written; so is a file that is a hard link (it has another name). Any other name in the output folder is fine, for example `run.log` | | `--masks FOLDER` | The masks folder (§2). `check` lists the mask types found and checks every mask from its header; `run` stops on a mask error and records the masks in `run_manifest.json`. A masks folder other than the one an earlier run recorded does not reuse the mask axes stated for that folder's masks (`--mask-axes`): state them again for the new folder (those of OME-Zarr label images are kept) | | `--mask-axes TYPE=ROLES` | The axes of a mask type, one role (Y, X, Z or T) per axis as stored, stated once per type: `Cells=TYX` for plain stacks of time points whose files do not name their axes; a 2D mask needs none, and `Cells=YX` (the removed shared 2D mask) is the error `shared_mask_not_supported` (repeatable; `check`, `run`, `masks`). Masks are never reordered. | +**The lab-links file.** `--lab-links` takes a JSON file of lab-tool links (for example +LabChronicle). It is recorded in `run_manifest.json` only (`lab_links`), and is not offered by +the notebook. + +- It holds exactly the keys `repository_url`, `commit` (the full 40- or 64-character lowercase + SHA) and `experiment_path`, as non-empty text. It may also hold `repeat_codes`, which maps + each lab-tool repeat code to a biological repeat ID of the description (for example + `{"R001": "rep1"}`). +- Any other key, a value of another type, an empty value, spaces around a value, or a key given + twice is refused before anything is read (`lab_links_invalid`). +- A `repository_url` holding a credential (a password, `user:password@`, in any form; a user + name before `@` in a URL whose scheme is not `ssh`, `git+ssh` or `ssh+git`, because + `https://TOKEN@host/...` carries a token there), a query string or a fragment (`?` or `#`) is + refused (`lab_links_invalid`). The refusal does not repeat the URL: a credential is never + written to the manifest. An SSH remote's login name (`git@host:lab/db.git`, + `ssh://git@host/...`) is kept. +- The links change no result: no row, digest, cache or other file. They are not taken over by + the next run: give the file to each run it belongs to. + After writing, `run` prints the intensity checks of the table, grouped by kind, each with the channel, the image or biological repeat and the values compared, and what to do once per kind; it draws no plots (the notebook does). Then it prints the channel check: each @@ -964,16 +1112,16 @@ stored as 8-bit do not. The same experiment in 16 bits and as 0-1 floats gives t findings only while the channel's high percentile is above about 333 counts; below that, the whole-number files have a floor that floats do not. -**Exit status.** Every command (`check`, `run`, `masks`, `calibrate`, `describe` and -`convert`) exits with status 1 when it prints an error, and with 0 otherwise: warnings, -intensity warnings included, never change it. So `check` exits with 1 on every error it -reports, `A_DESCRIPTION_REQUIRED` included. Options that cannot be read exit with 2. Scripts can therefore stop on any -non-zero status. +**Exit status.** Commands use exit status 0 for successful completion and 1 for a refused +operation. Invalid command-line arguments normally return 2. Read the command's final status +message before proceeding. Warnings, intensity warnings included, never change the status. -The optional `masks` command reads the masks and tells how they relate: +If your analysis uses masks, run the `masks` command after preprocessing. It checks the mask +pixels against their declared representation and reports relationships between mask types. +Skip this step only if the downstream analysis does not use masks. ```bash -morphobricks-preprocessing masks /data/exp1 --masks /data/exp1_masks +morphobricks-preprocessing masks my_experiment --masks my_masks ``` It reads every image's masks, one image at a time, and prints for each kind of mask @@ -1080,7 +1228,10 @@ 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); 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. @@ -1107,6 +1258,55 @@ 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, each heading naming only the options that can answer what is left +(`--id`, `--accept-ids`, `--comparable` and `--confirmed-on`), and the output says when your +options answer them all. + +**Naming an ID yourself (`--id FOLDER=ID`).** A folder whose name cannot be an ID gets no +proposal: `control` and `files` are reserved words of the description (`E_FORBIDDEN_FIELD`), +and `--accept-ids` cannot accept a proposal that does not exist. Name it with `--id` +(repeatable), for a condition, biological-repeat or technical-repeat folder: + +```bash +morphobricks-preprocessing describe /data/exp1 --channels DNA,ACTIN --image-type channels \ + --id control=ctrl --accept-ids --comparable --confirmed-on 2026-12-04 --publish +``` + +The ID is used exactly as you type it and checked with the notebook's rules: a forbidden word, +an ID already used by another folder (also in another upper/lower case) or `single` for a +folder that is not `single` is refused, the line naming the option to give again (`--id +control=`), and nothing is written. The folder keeps its name; only the description's ID +differs. A folder name used at two levels (a condition and a technical repeat both called `a`) +needs the level: `--id condition:a=A1`, `--id repeat:a=...` or `--id technical:a=...`. When +`--id` names every ID, `--accept-ids` is not needed. Without `--channels`, `describe --id` +shows the draft with your IDs. `--id` is for a new fast-mode description; a published one, or +the strict mode, names IDs in the notebook. + +**Colour scanner files whose header does not say colour.** Some scanners (and some public H&E +datasets) store red, green and blue as three interleaved samples per pixel under the TIFF +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 @@ -1114,6 +1314,17 @@ metadata give none, or the wrong one, state them in `calibration.csv` in the out folder. Nothing is ever guessed: an image with neither is *uncalibrated*, and the report says so. +The most common case, 0.65 µm pixels in X and Y for the whole experiment, then a run that +records them: + +```bash +morphobricks-preprocessing calibrate my_experiment --size . XY 0.65 um +morphobricks-preprocessing run my_experiment +``` + +Run preprocessing again after every change made with `calibrate`: the sizes are recorded only +by the next run. More examples: + ```bash # 0.65 um pixels for the whole experiment; a 2 um z-step for one condition morphobricks-preprocessing calibrate /data/exp1 --size . XY 0.65 um --size treated Z 2 um @@ -1174,14 +1385,37 @@ exit status; it is not printed when the experiment is given or recorded. When the metadata of some images name their axes wrongly (the errors `axes_yx_swapped`, `axes_contradict_header`, `axes_x_before_y`) or do not name them at all (the warning `axes_not_named`), and you are sure of the roles, save the images again as named-axis -copies with your roles, then run preprocessing on the copies: +copies with your roles, then run preprocessing on the copies. `convert` has three common uses: + +```bash +# Correct axis metadata: write copies whose metadata name your roles +morphobricks-preprocessing convert my_experiment --to my_experiment_named --axes CYX +# Save a large fluorescence mosaic as OME-Zarr, so later tools can read it in windows +morphobricks-preprocessing convert my_slides --to my_slides_zarr --axes CYX --store ome-zarr +# Make maximum projections of Z-stacks (2-D copies) +morphobricks-preprocessing convert my_experiment --to my_experiment_max --axes ZCYX --project max +``` + +These axis orders are examples. Use the actual stored order of your images. RGB TIFFs store +their colour samples last, so use `YXC` rather than `CYX`; `convert` does not check the order +against the file, so look at a copy. + +**The copies are a new experiment folder.** Describe and publish the copies before `check` and +`run`, for example for the projections: ```bash -morphobricks-preprocessing convert /data/exp1 --to /data/exp1_named_axes --axes ZXY --output /data/exp1_MorphoBricks_Preprocessing -morphobricks-preprocessing check /data/exp1_named_axes --output /data/exp1_MorphoBricks_Preprocessing -morphobricks-preprocessing run /data/exp1_named_axes --output /data/exp1_MorphoBricks_Preprocessing --axes ZYX +morphobricks-preprocessing describe my_experiment_max +morphobricks-preprocessing describe my_experiment_max --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +morphobricks-preprocessing check my_experiment_max +morphobricks-preprocessing run my_experiment_max ``` +The same applies to `my_experiment_named` and `my_slides_zarr`. Projected copies always need +their own description and output folder. Named-axis and OME-Zarr copies are the one +exception: if the originals already have a published description in an output folder, give +that folder to `check` and `run` on the copies with `--output` instead (see below). + `--axes` gives your roles for the original images, exactly as for `run`; they are never taken from the metadata. `convert` writes a new folder (`--to`, outside the experiment) with the experiment's folders and file names: the images with axis problems as OME-TIFF @@ -1193,6 +1427,29 @@ 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. +The copies are stored in chunks of one plane by at most 1024 x 1024 pixels (since v0.10.1; +before, one chunk per plane), so a later brick can read a large slide in windows; `check` +warns about an OME-Zarr image whose chunks are too large for that +(`chunks_too_large_for_windows`). Copies written before v0.10.1 are not rewritten by a new +conversion into the same folder: convert into a new folder. + +```bash +morphobricks-preprocessing convert /data/he --to /data/he_zarr --axes YXC --store ome-zarr +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, @@ -1261,7 +1518,8 @@ make a projected copy first: default method; `--z-range 2:10` uses only those slices of every image, zero-based with the end excluded, `4:5` is the single slice 4, and every image must have them), or in Python `convert_experiment(EXP, mapping, FOLDER, projection=Projection("max", (2, 10)))`. -Every image of the experiment is written as a 2-D OME-TIFF of the same folders and names: +Every image of the experiment is written as a 2-D OME-TIFF (or a 2-D OME-Zarr image with +`--store ome-zarr`) of the same folders and names: its axes are your roles without Z (`ZCYX` becomes `CYX`), each (t, c) is projected on its own, and the Z size is not written to the copy (it is recorded in the conversion record as dropped). Your originals are only read. The pixel type is decided by the input type and the @@ -1273,8 +1531,8 @@ to infinity is refused (`projection_overflow`). The copy's OME-XML says how it w the conversion record (version 4) holds the method, the slices used, the source's SHA-256, the types, the rounding and the dropped Z size for every image. Masks are never projected: masks with depth slices stop the projection (`projection_masks_3d`); 2-D masks stay where -they are. OME-Zarr images are not projected yet (`projection_zarr_not_supported`; exclude -them). One folder holds one method and one slice range (`copy_differs` otherwise). The command prints the next commands with a +they are. OME-Zarr source images are not projected in this release (`projection_zarr_not_supported`; +export TIFF copies of them first, or process the TIFF images separately). One folder holds one method and one slice range (`copy_differs` otherwise). The command prints the next commands with a new output folder (by default the copy folder's name with `_MorphoBricks_Preprocessing`): the projected copies are a different source, so the description starts again there (the design and the stated pixel sizes are entered again). A run on the copies records the projection in its manifest (`projection`: the method, the slices used, the source SHA-256 of every image) and the report says "max projections of slices 1:4". Masks next to projected images are used as they are, with the warning `masks_on_projected_images`: check that they were made on, or for, the projection. A run on projected copies reads the conversion record strictly: a record that is missing or does not match the run is refused, never read as a plain image. The notebook card follows. @@ -1312,31 +1570,56 @@ copies (optional)** card appears under it, calling the same functions as the com The card is not shown when another brick embeds step 1 without the output folder (`folder_step(show_output=False)`). -### Declaring masks added after preprocessing (`declare-masks`) +### Declaring existing masks or adding new masks (`declare-masks`) -Masks you make after preprocessing (a segmentation of the output, for example) must be declared -in the published description before `run --masks` accepts them; otherwise the run refuses them -(`R_MASK_TYPE_NOT_DECLARED`). The notebook declares them on its *Masks* question or in its -Register step. On the command line, say what each mask type is: +Declare each mask type before running preprocessing with those masks. You can do this +immediately after publishing the experiment description, or add masks to an existing +preprocessing run later. An undeclared mask type is refused (`R_MASK_TYPE_NOT_DECLARED`). The +notebook declares masks on its *Masks* question or in its Register step. On the command line, +say what each mask type is: ```bash -morphobricks-preprocessing declare-masks --output /data/exp1_MorphoBricks_Preprocessing \ - --masks /data/exp1_masks --type Cells=instances --type Nuclei=instances -morphobricks-preprocessing run --output /data/exp1_MorphoBricks_Preprocessing --masks /data/exp1_masks -morphobricks-preprocessing masks --output /data/exp1_MorphoBricks_Preprocessing --masks /data/exp1_masks +morphobricks-preprocessing describe my_experiment --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +morphobricks-preprocessing declare-masks --output my_experiment_MorphoBricks_Preprocessing \ + --masks my_masks --type Cells=instances +morphobricks-preprocessing run my_experiment --masks my_masks +morphobricks-preprocessing masks --output my_experiment_MorphoBricks_Preprocessing ``` -- `TYPE` is the mask type's folder name. `REPRESENTATION` is `instances` (each object has its +The last command checks the mask pixels and reports their properties and relationships. Run it +before using the masks in another MorphoBricks tool. + +- `TYPE` is the mask type: its folder name, or the file-name ending of masks such as + `image_01_cp_masks.tif` (§2, "Masks"). `REPRESENTATION` is `instances` (each object has its own number: Cellpose output), `binary` (foreground / background) or `parent_labels` (each non-zero value one group). There is no default; nothing is guessed from the files. -- The mask ID is the folder name. When that is not a valid mask ID (`nuclei-mask`), give one: - `--type nuclei-mask=binary:nuclei`. -- The description is published as the notebook publishes it: under the output folder's lock and - against the version it was read from. Running the command again with the same answers changes - nothing. A mask type already declared otherwise is refused: change it in the notebook's - describe steps. +- The mask ID is the mask type unless you give another after a colon. Give one when the type is + not a valid mask ID (`--type nuclei-mask=binary:nuclei`), or to give a file-name ending a + clearer name (`--type cp_masks=instances:Cells`). +- The command updates the saved experiment description safely. Repeating an identical + declaration makes no change. A mask type already declared otherwise is refused: change it in + the notebook's describe steps. - `--masks` also checks each mask type against the masks folder (no folder there that differs only in upper/lower case). +- OME-Zarr label images (`.zarr/labels/`) need no `--masks`: the command then + prints the next commands without it (`run EXPERIMENT --output FOLDER`, the experiment folder + left out when a run of the output folder records it). +- `check` reports a mask type the description does not declare exactly as `run` refuses it + (`R_MASK_TYPE_NOT_DECLARED`, naming the type), so you see it before the run. Its fix names + both ways out: `--type TYPE=instances` (or `binary`, `parent_labels`, each with what it + means; none is guessed) to use it, `--ignore TYPE` to skip it. +- **Skipping a mask type you do not use (`--ignore TYPE`, repeatable).** Ignored mask types are + recorded in `ignored_masks.toml`. Preprocessing skips them. Declare a previously ignored type + with `--type` to use it again. Run preprocessing after changing the list. For example: + + ```bash + morphobricks-preprocessing declare-masks --output my_experiment_MorphoBricks_Preprocessing \ + --type Cells=instances --ignore OtherLabels + ``` + +- Do not declare and ignore the same mask type. If the ignore operation fails after new + declarations have been saved, those declarations remain saved. - In Python: `morphobricks_preprocessing.mask_declare.declare_masks(output, {"Cells": "instances"})`. ### Converting a mask (`convert-mask`) @@ -1376,17 +1659,24 @@ masks** does the same. ### An H&E tissue mask (optional) -For H&E images (a unit declared `image_type = "rgb"`), `tissue-mask` writes a **new** region mask -that leaves out nuclei, red blood cells and empty space, so that a brick such as fiberfeatures -measures the tissue between them. It needs the `he-mask` extra: +For H&E images (a unit declared `image_type = "rgb"`), `tissue-mask` writes a binary region +mask designed to exclude nuclei, red blood cells and empty background, so that a tool such as +fiberfeatures measures the tissue between them. The images must be 8-bit RGB, with three colour +channels, one depth plane and one time point. It needs the `he-mask` extra (see +[Installing for the command line](#installing-for-the-command-line)): ```bash -pip install "morphobricks-preprocessing[he-mask]" -morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preprocessing --to HETissue +morphobricks-preprocessing tissue-mask --output my_experiment_MorphoBricks_Preprocessing --to HETissue ``` -- It is a **fixed rule**, `he_tissue_v1`, and it is **provisional**: its numbers are not frozen - until an acceptance report is accepted. It is not a trained segmentation. Its colour maths is +Inspect the masks (the notebook's preview, or the printed "kept" share) before declaring them. + +- It is a **fixed rule**, `he_tissue_v2` by default. The rule is provisional and may change in a + later version. The rule version is recorded with each mask. `he_tissue_v2` first measures each image's + white from its brightest pixels (the glass), so scans whose glass is grey rather than white + work; `--rule he_tissue_v1` keeps the white fixed at 255 (it keeps nothing on such scans). An + image with no glass or empty space at all takes its brightest tissue as white: check the + "kept" share. It is not a trained segmentation. Its colour maths is the normalization brick's (the eosin and hematoxylin maps of the `he_eosin` preset and the optical density per channel), and all its sizes are **in pixels**: the same rule on images of another magnification leaves out pieces of another physical size. Look at the preview (in the @@ -1398,22 +1688,51 @@ morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preproce to `mask_lineage.jsonl`, which records the image, the complete rule and its digest, the exact installed code that computed it and the library versions. An image where nothing is kept gives an all-zero mask: a valid, empty region. -- Running the same command again changes nothing. If the printed line says **this mask will not - be reused on retry**, the installed code could not be verified (for example a development - install, `pip install -e`): the mask is written, but a second run with the same ID is refused; - use a new ID. -- Then declare it, run preprocessing and the masks step again, and use it **as a region**: - - ```toml - [masks.HETissue] - source_type = "HETissue" - representation = "binary" - source_channels = ["R", "G", "B"] - display_name = "H&E tissue (he_tissue_v1)" +- Before declaring the generated mask, an identical retry can reuse existing files when their + contents and the software identity can be verified. Once the mask ID is declared, + `tissue-mask` refuses to write under that ID. To generate another version, choose a new ID + with `--to`. If the command says the mask will not be reused on retry, the installed code + could not be verified (for example a development install, `pip install -e`): the mask is + written, but a second run with the same ID is refused; use a new ID. +- **A run without a masks folder** (scanner images often have no masks) gets one first: + `tissue-mask` creates `_masks` beside the experiment folder (or the new, empty + folder `--masks FOLDER` names), records it by running preprocessing again on the output folder + with that masks folder, exactly as `run --masks FOLDER` records one, and says so in one line. + Histograms of verified unchanged images are reused; content verification may still reread + the source files. A folder that exists and is not empty is never adopted: + give another, or run preprocessing with `--masks` yourself if it is your masks folder. +- A refusal names the image once, then what to do. +- Then declare it, run preprocessing and the masks step again; the command prints these commands + with your folders: + + ```bash + morphobricks-preprocessing declare-masks --output /data/exp1_MorphoBricks_Preprocessing \ + --type HETissue=binary --masks /data/exp1_masks + morphobricks-preprocessing run --output /data/exp1_MorphoBricks_Preprocessing + morphobricks-preprocessing masks --output /data/exp1_MorphoBricks_Preprocessing ``` - For example fiberfeatures `MaskRequest("HETissue", "region")`. It is never a set of cells: do - not pass it as cell-mode labels. + Use it **as a region**: in the next brick's settings, `region_mask = "HETissue"` (for example + fiberfeatures). It is never a set of cells: do not pass it as cell-mode labels. + +**The whole H&E route on the command line**, for scanner TIFFs with no masks (here a condition +folder named `control`, which cannot be an ID, and a header that does not say colour): + +```bash +morphobricks-preprocessing describe /data/he --channels R,G,B --image-type rgb --id control=ctrl \ + --accept-ids --comparable --confirmed-on 2026-12-04 --rgb-header-override --publish +morphobricks-preprocessing run /data/he +morphobricks-preprocessing tissue-mask --output /data/he_MorphoBricks_Preprocessing --to HETissue +morphobricks-preprocessing declare-masks --output /data/he_MorphoBricks_Preprocessing \ + --type HETissue=binary --masks /data/he_masks +morphobricks-preprocessing run --output /data/he_MorphoBricks_Preprocessing +morphobricks-preprocessing masks --output /data/he_MorphoBricks_Preprocessing +``` + +`tissue-mask` creates and records `/data/he_masks` (the run had none) and prints the last three +commands with your folders; then set `region_mask = "HETissue"` in the next brick's settings. +If the images are OME-Zarr with label images you will not use, skip them first with +`declare-masks --output ... --ignore LABEL`. In the notebook, the card **Make an H&E tissue mask (optional)** beside **Convert a mask** does the same: choose the RGB positions (or **Choose all of this unit**), **Preview** one image (the @@ -1442,21 +1761,15 @@ it has no lineage file and cannot be declared as a mask of a run: for a MorphoBr The default output folder is next to the experiment folder: `/data/exp1` → `/data/exp1_MorphoBricks_Preprocessing`. -- **`plane_histograms.csv`:** one row per plane (every channel of an image at one depth - slice and time point) with the position (`position_id`, the file name without its - extension), the file name, the zero-based plane coordinates `z` and `t` (0 when the - image has no such dimension), the three labels, the pixel type and the number of - channels; then, for each channel, its exact minimum and maximum, pixel counts and - histogram, in columns ending in the channel number (`Intensity_MinIntensity_C0`, - `Histogram_Count_C1_00042`, …). The table is very wide (one column per bin and channel), - so spreadsheet programs may not open it completely; read it in Python with - `read_plane_histograms()`. The columns are defined in the [normalization brick's - contract](https://github.com/CellMigrationLab/morphobricks-normalization/blob/main/docs/contract.md) - §6.2 (schema version 5: the columns are named by channel ID, for example - `Histogram_Count_DNA_00042`; a `channels` column lists the stains of each plane, and a stain - the image does not have is blank; each channel also has its underflow and overflow, zero - unless the robust range is used). A table written by an earlier version is recomputed on the next - run; later bricks ask you to run this brick again on it. +- **`plane_histograms.parquet`:** the intensity histograms of every image plane, with its + experimental labels and channel IDs. The table contains one row per plane and stores each + channel's histogram as lists of bin indices and counts. Later MorphoBricks tools read this + file to calculate normalisation parameters without rereading the image pixels. Read it in + Python with `read_plane_histograms()` (from `morphobricks_normalization`). The format + (schema version 6) is defined in the [normalization brick's + contract](https://github.com/CellMigrationLab/morphobricks-normalization/blob/main/docs/contract.md). + From v0.10.0, this file replaces `plane_histograms.csv`. To update an older preprocessing + run, run preprocessing again. - **`image_qc.csv`:** one row per plane and channel with image QC metrics measured while the histograms are computed (no extra read): the share of the plane above its Otsu threshold (`foreground_fraction`; `otsu_separation` is about 0.64 for noise and for any dense field @@ -1500,6 +1813,10 @@ The default output folder is next to the experiment folder: cache: delete it and the next restore reads every header; later bricks never read it. - **`calibration.csv`** (only when you state pixel sizes): your statements (§5, Stating pixel sizes). Runs read it and never change it. +- **`ignored_masks.toml`** (only when you skip mask types, v0.10.1): the mask types and + OME-Zarr label images the runs leave out (`declare-masks --ignore`, §5). Runs read it and + never change it; the manifest records it (`ignored_masks`), and a list changed after a run + makes that run stale for later bricks until preprocessing runs again. - **`ome_zarr/`**: written only by v0.3 runs that converted TIFF images to OME-Zarr. That option was removed in v0.4.0; such a folder is left as it is, and may be deleted. @@ -1590,9 +1907,14 @@ Run the notebook or `run` again after adding, changing or removing images: types, and only the manifest records the new type. **After upgrading from an earlier version (v0.5.1 or before):** its run manifest is not read -(only version 5 is, since v0.5.2), so the first run recomputes every row and reuses no recorded +(only versions 5 and 6 are), so the first run recomputes every row and reuses no recorded input: give the axis roles, masks and exclusions again. Later bricks refuse such older runs until they are run again. +**After upgrading from v0.5.2 to v0.9.x:** those runs wrote `plane_histograms.csv`. From v0.10.0, +`plane_histograms.parquet` replaces it, and later tools refuse the old table. To update an +older preprocessing run, run preprocessing again: every row is recomputed and the CSV file is +removed. + Run the brick again after adding images or masks before using a later brick: later bricks read the images and masks this brick's run recorded, and refuse an experiment holding images or masks the run did not record (they name them). @@ -1614,8 +1936,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), save the description and run again. When the contradiction is an `image_type` of colour scanner files whose header does not say colour (three interleaved samples), the suggested action names the RGB header override instead (`rgb_header_override = true`, the notebook's Image type card), once; while a new description is published from the command line, `describe` also names `--rgb-header-override [FOLDER]` (§5). An image whose header gives no channel names (or an empty name) needs no evidence and follows the list; the manifest records each image of a fast acquisition in `fast_layout_images` (`header_verified` true only when every channel was confirmed by its header name). In such acquisitions this one code replaces `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER` and `R_UNIT_NOT_HOMOGENEOUS` (which stays for the other axes); `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` keeps its priority. An acquisition tagged on its own is checked as in a description without fast mode. Experiments with extra channels in some acquisitions are refused here: tag those acquisitions on their own. | | `folder_and_id_changed` | Error | *Check and save* (and publication) found an ID changed in the same save as a folder change of the same entity: for example a repeat ID `Day1 -> DayX` while one of its folders was renamed or removed, a condition ID changed while its folder was renamed, or a removed folder's ID typed for the new folder. Neither change is guessed from the other, so the message names the entity, its saved ID and its folders. Undo the ID edit: put the saved ID back (the folder change then saves on its own). A removed folder's ID stays used and is not given to another folder (experiment-v1 4.9). Nothing was published. | | `R_DRAFT_CHANGED` | Error | Notebook: `morphobricks.draft.json` was changed since this notebook read or saved it (another notebook, or a program, saved its own answers in the same output folder). Nothing was saved or published, and the answers saved there are kept. Press **Check folder** in step 1 to read them, then give your change again. | | `R_DRAFT_EXISTS` | Error | Command line (`describe --publish`): the output folder holds `morphobricks.draft.json`, answers saved in the notebook that the command does not read. Nothing was published or written. Finish those answers and publish them in the notebook (step 1, **Check folder**, then **Check and save**), or, if they are not wanted, remove or archive that file yourself and run the command again. | @@ -1625,7 +1947,7 @@ continues. | `description_unreadable` | Error | `morphobricks.toml` or `morphobricks.records.jsonl` cannot be read. A description the reader refuses is reported with its own code (`E_*`, `R_FILE_SYMLINK`) and table path. | | `unreadable_folder` | Error | A folder could not be opened. Check permissions. | | `store_unreadable` | Error | A folder inside an OME-Zarr image could not be listed, so whether it holds links or mount points leading outside the selected folder is not known. Check the folder's permissions (and that the drive is connected), then check again. | -| `link_outside_folder` | Error | A link in the experiment or masks folder leads outside it (the message names each link and its target), and nothing outside the selected folder is read. Copy or move the files in, or select a folder that holds them, then remove the link. | +| `link_outside_folder` | Error | A link in the experiment or masks folder leads outside it (the message names each link and its target), so the images or masks behind it are not found: a run reads, fingerprints and records only what is inside the selected folder. Move (do not copy) the data in, instant on the same drive, or put the experiment's folders on the drive that holds the data and select that folder; then remove the link. | | `link_loop` | Error | A link leads back to a folder that holds it. Remove it. | | `mounted_folder` | Error | A folder (or file) in the experiment or masks folder is a mount point: another disk or share, or a bind mount of another folder, so its files come from outside the selected folder. It is named and not entered. Copy the files in, or select the mounted folder itself. Where the system's mount table cannot be read (macOS, Windows), only a mount of another device is seen. | | `hard_linked_file` | Warning | An image or mask has other names (hard links; the message gives the number), perhaps outside the folder, so it can change through a name the run does not see. It is read as usual. Replace the hard link with a copy if it may change. | @@ -1659,7 +1981,7 @@ continues. | `plane_over_memory_limit` | Error | A plane cannot be read within the memory limit, not even in blocks (for example, it is stored compressed in one piece). Raise the limit, or save the images again as tiled or uncompressed TIFF files or as OME-Zarr with smaller chunks. | | `compression_not_bounded` | Error | Planes too large to read whole within the memory limit are stored with a TIFF compression whose decoding memory has not been measured (old-style JPEG, PackBits, Zstandard, WebP, JPEG 2000, ..., or JPEG in another form than 8-bit greyscale, RGB or YCbCr), so they are not read in blocks: only uncompressed, deflate (zlib), LZW, LZMA and 8-bit greyscale, RGB or YCbCr JPEG TIFF images are (decoded by imagecodecs, a required dependency: an image is also refused when the installed imagecodecs is missing, older than 2024.12.30 or, for JPEG, not built on libjpeg-turbo 3, and the message says so). The message names the compression. Save the images again as uncompressed, deflate, LZW or LZMA TIFF files (tiled, for large images) or as OME-Zarr, or raise the memory limit so that their planes are read whole. The same refusal, from the header and before any pixel is read, stops window reads and `RunInputs.read_plane` of such an image whatever its size. | | `unsupported_layout` | Error | The image cannot be read one plane at a time. Check the axis roles or export again. | -| `unreadable_planes` | Error | Pixel data cannot be decoded. The message names each plane that failed (its T, Z and C index and the channel ID) and why, at most 20 per image followed by "and N more"; the run report lists every one (`unreadable_planes`; in the notebook's run report, under *Unreadable planes*, one folded list per image); no `plane_histograms.csv` is written, since one channel that cannot be measured fails the whole table. Export again, or exclude the image. | +| `unreadable_planes` | Error | Pixel data cannot be decoded. The message names each plane that failed (its T, Z and C index and the channel ID) and why, at most 20 per image followed by "and N more"; the run report lists every one (`unreadable_planes`; in the notebook's run report, under *Unreadable planes*, one folded list per image); no `plane_histograms.parquet` is written, since one channel that cannot be measured fails the whole table. Export again, or exclude the image. | | `image_over_max_ram` | Error | `--workers auto --max-ram`: an image needs more working memory to read than the budget leaves (estimated from its header). Nothing was read. Raise `--max-ram`, or lower `--memory-limit` so its planes are read in smaller blocks. | | `invalid_bin_count` | Error | Bin count outside the allowed range. Use the default or a value in range. | | `experiment_not_recorded` | Error | `run` was given no experiment folder, and the output folder holds no v0.4.0 run that records one (or no output folder was given). Give the experiment folder. | @@ -1669,6 +1991,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. | @@ -1678,15 +2001,15 @@ continues. | `copy_folder_not_empty` | Error | `convert`: the folder for the copies holds files and no conversion record. Nothing is overwritten; choose a new or empty folder. When the folder also holds the work folder of a stopped conversion, the message says the files named may be copies it had moved into place when it was interrupted: remove them, then convert again. | | `copy_differs` | Error | `convert`: images in the folder of copies differ from the copies this conversion would write (an original changed, other roles, a copy changed, an image no longer in the experiment), or the folder holds copies of another experiment. Nothing is overwritten; convert into a new folder, or remove those copies first. | | `cannot_convert_pixel_type` | Error | `convert`: images of 64-bit integers cannot be saved as OME-TIFF, and pixel values are never changed to fit. Save them again with named axes in a 32-bit type if their values fit, or correct the roles. | -| `nothing_to_project` | Error | `convert` with a projection: no image has a depth axis (Z) under the roles you gave. Check the roles; nothing was written. | +| `nothing_to_project` | Error | `convert` with a projection: no image has a depth axis (Z) under the roles you gave. Check the stored axis order: Z must be the axis of the slices of a stack. If these images have no depth dimension, omit `--project`. Nothing was written. | | `projection_z_range_outside` | Error | `convert` with a projection: the slice range does not fit every image; the shorter images are named. Give a range every image has, or leave it out. | | `projection_cannot_be_exact` | Error | `convert` with a projection: a sum or mean of that many slices of that pixel type could not be held exactly. Use max or mean, or a shorter slice range. | | `projection_overflow` | Error | `convert` with a projection: a sum overflows to infinity (float64) at the pixels named. Use max, or mean if the values allow it. | | `projection_undefined` | Error | `convert` with a projection: a sum adds an infinity to its opposite at the pixels named, which is undefined. Use max. | -| `projection_over_memory_limit` | Error | `convert` with a projection: one input plane and its running total do not fit the memory limit. Raise `--memory-limit`. | -| `projection_masks_3d` | Error | `convert` with a projection: masks of the images have depth slices (Z), and masks are never projected. Make 2-D masks on the projected images, or move these masks out of the masks folder. | -| `projection_masks_axes_unknown` | Error | `convert` with a projection: masks have more than Y and X and their axes are not named, so it is not known whether they have depth slices. Name the axes in the masks' metadata, or move them out. | -| `projection_zarr_not_supported` | Error | `convert` with a projection: OME-Zarr images are not projected yet. Exclude them. | +| `projection_over_memory_limit` | Error | `convert` with a projection: one input plane and its running total do not fit the memory limit. Increase `--memory-limit` only if sufficient RAM is available, or export smaller images for projection. | +| `projection_masks_3d` | Error | `convert` with a projection: masks of the images have depth slices (Z), and masks are never projected. Keep the original masks separately, outside the masks folder, then convert the images without those 3-D masks; create new 2-D masks from the projected images and register them with the new experiment. | +| `projection_masks_axes_unknown` | Error | `convert` with a projection: masks have more than Y and X and their axes are not named, so it is not known whether they have depth slices. Check and export the mask axes correctly. If these masks belong to the original 3-D images, keep them separate from the projected experiment. | +| `projection_zarr_not_supported` | Error | `convert` with a projection: projection of OME-Zarr source images is not supported in this release, and no projected copies were written. Export suitable TIFF copies of these images before projection, or process the TIFF images separately. | | `source_changed_during_check` | Error | `convert`: an original changed while its metadata was read, so the metadata may not describe the file that would be copied. Nothing was written; convert again when nothing writes into the experiment. | | `conversion_failed` | Error | `convert`: an image could not be copied (unreadable, changed while copied, or the folder cannot be written). The copies written by this conversion were removed; fix the cause and convert again, or exclude the image. | | `not_enough_space` | Error | `convert`: the copies would not fit on the drive. Free space or choose another drive. | @@ -1706,7 +2029,8 @@ continues. | `non_tiff_file`, `empty_folder` | Warning | Files or folders that are skipped. | | `image_named_as_mask` | Error | An image is named like a mask of another image (`f1_mask.tif` beside `f1.tif`; the endings `_mask`, `_masks`, `_cp_masks`, `_labels`, `_label`, `_seg`, `_segmentation`), and a mask is never analysed as an image. If it is a mask, move it into a masks folder outside the experiment, or exclude it; if it is an image, rename it. | | `mask_folder_in_experiment` | Warning | A folder inside the experiment is named like a masks folder (`masks`, `ctrl_masks`, `CellLabels`) and holds files named like masks of the images; they would be analysed as images. Move it out of the experiment and give it as the masks folder, or rename it if these are images. | -| `planes_read_in_blocks` | Warning | Planes too large for the memory limit are read in blocks. The results are the same; nothing to do. Raise the limit to read them whole, which is faster. | +| `planes_read_in_blocks` | Warning | Planes too large to measure whole within the memory limit are read and measured in blocks. The figure is the run's own need: one channel read and its histogram computed at once (mostly the histogram's working arrays). Reading every channel of a plane without a histogram, as `RunInputs.read_plane` and later bricks do, needs another amount (`xyc_plane_memory`), checked when they read; for a 30720 x 36864 x 3 `uint16` OME-Zarr mosaic about 38.0 GiB here and 14.8 GiB there. The results are the same; nothing to do. Raise the limit to read them whole, which is faster. | +| `chunks_too_large_for_windows` | Warning | `check` and `run`: an OME-Zarr image is stored in chunks so large that a later brick reading it in windows (a patch-window route, through `RunInputs.window_reader`) cannot read even one window within the memory limit: a chunk is decoded whole for any window it holds, so a store in one chunk per plane is decoded whole for every window. Preprocessing itself reads it (in blocks). The same image is refused when a window reader is opened on it, with the same advice. If it is an OME-Zarr copy written by `convert --store ome-zarr` or the notebook before v0.10.1 (one chunk per plane), convert the original images again into a new folder (copies are now written in chunks of 1024 x 1024 pixels); otherwise save it again with chunks of at most 1024 x 1024 pixels along Y and X. | | `different_sizes` | Warning | Images have different widths or heights. Usually expected; otherwise check the camera settings. For a plain stack (no axes in its file), the sizes are compared once you confirm its axis roles, with those roles. | | `different_plane_counts` | Warning | Images have different numbers of depth slices, time points or other planes. Images with more planes weigh more in pooled statistics. Check the acquisition if this is not expected. For a plain stack, compared with its confirmed axis roles, as `different_sizes`. | | `different_pixel_sizes` | Warning | The physical pixel size or z-step (from the metadata or `calibration.csv`) differs between images by more than 0.1 % (for example different objectives). Images outside the largest group of matching sizes are listed; when sizes only change by small steps from image to image, none is listed. Check the microscope settings if this is not intended. | @@ -1728,7 +2052,7 @@ continues. | `lab_links_repeat_unknown` | Error | A lab-tool repeat code names a biological repeat the description does not declare (IDs are compared exactly; a folder name or display name is not an ID). Correct the file. | | `lab_links_repeat_twice` | Error | Two lab-tool repeat codes name the same biological repeat; each repeat has exactly one code. Correct the file. | | `lab_links_repeat_missing` | Error | The lab-tool repeat codes leave out a biological repeat of the description; a mapping names every repeat. Add its code, or leave `repeat_codes` out. | -| `rgb_not_possible` | Error | The image type RGB was chosen, but the images are not three channels of a whole-number pixel type. Choose fluorescence, or check the axis roles: the RGB samples must have the role C. | +| `rgb_not_possible` | Error | The image type RGB was chosen, but the images are not three channels of a whole-number pixel type. If the images are separate stains, describe them as separate channels. If they are genuinely RGB, verify that the stored colour-sample count and axis roles are correct. | | `repeat_group_conflict` | Error | A repeat group holds two folders of the same condition. Move one into another replicate on the *Replicates* page and save the description again (*Check and save*). | | `invalid_experiment_design` | Error | A repeat group has no usable name (empty, `NA`, `nan`, `none`, `null`, `n/a`, ``, or spaces around it), two repeat groups are spelled the same apart from upper and lower case, or a confirmation date is not written `YYYY-MM-DD`. It comes from a description edited by hand or rows built in code; correct the description (the message names the folder). | | `image_intensity_outlier` | Warning (intensity check) | An image's median or high percentile in a channel is far from the other images of its condition and biological repeat. Look at it: it may be out of focus, contain debris or bubbles, or have been acquired differently. Exclude it if it is faulty. | @@ -1749,6 +2073,7 @@ continues. | `manifest_channel_coverage_mismatch` | Error (other bricks) | `RunInputs.open` found a `channel_coverage` in the run manifest that is not the channel coverage of the published `morphobricks.toml` the run read (`ChannelCoverageMismatchError`); the message names `experiment_description.channel_coverage` and each biological repeat that differs. The manifest was changed after the run, so the run is refused, never corrected. Run preprocessing again. | | `manifest_unit_record_malformed` | Error (other bricks) | A record of the run manifest's `experiment_description.units` is not an object with `repeat`, `condition`, `technical_repeat`, `channels` and `image_type_header_verified` of their types, or holds a field the run does not write (`ManifestUnitRecordError`, when the manifest is read). The manifest was changed after the run, or was written by a newer release that records a unit field this one does not know (refused, never ignored); the message names the unit record and the field. Nothing is filled in: run preprocessing again. A manifest written before v0.5.2 never reaches this check: its version is refused first. | | `manifest_unit_record_mismatch` | Error (other bricks) | `RunInputs.open` found a unit record in the run manifest that is not a unit of the published `morphobricks.toml` the run read: an unknown repeat, condition or technical repeat, a unit recorded twice or not at all, other channels, or a declared `rgb_header_override` that the description does not declare (`UnitRecordMismatchError`); the message names the unit record and the field. Run preprocessing again. | +| `ignored_masks_invalid` | Error | `ignored_masks.toml` in the output folder cannot be read as `declare-masks --ignore` writes it (other keys, another version, a name twice or with a `/`, a link). `declare-masks` reads the list before changing it, so it cannot rewrite an unreadable one: move the file out of the output folder (keep it as a backup), recreate the list with `declare-masks --output FOLDER --ignore TYPE` for every mask type you still intend to skip, and run preprocessing again. | | `masks_folder_not_found` | Error | The masks folder does not exist. Select the folder that holds one folder per kind of mask. Later bricks opening a run (`RunInputs.open(..., masks_root=...)`) refuse a masks folder given that does not exist or is a file with the same code (`MasksFolderNotFoundError`); it is never read as a folder without masks. Give the folder that holds the masks, or leave `masks_root` out to use the one the run recorded. | | `masks_folder_unreadable` | Error | A masks folder given to a later brick (`RunInputs.open(..., masks_root=...)`) cannot be listed, for example for lack of permission, so its masks cannot be checked against the run (`MasksFolderUnreadableError`); the message names the folder and the reason. Check its permissions, or give another folder. | | `output_inside_masks` | Error | The output folder is inside the masks folder, where the run's files would be read as masks. Choose another output folder. | @@ -1862,8 +2187,8 @@ write_mask_report(report, "/data/exp1_MorphoBricks_Preprocessing/mask_relationsh ``` `scan_masks(..., thresholds={"inside_object_share": 0.8})` changes a threshold (the others -keep their defaults, `DEFAULT_THRESHOLDS`). The label images of OME-Zarr images are always -used, with or without a masks folder; `preflight(..., mask_axes={"Cells": "TYX"})` states +keep their defaults, `DEFAULT_THRESHOLDS`). OME-Zarr label images are discovered +automatically, except for mask types explicitly listed in `ignored_masks.toml`; `preflight(..., mask_axes={"Cells": "TYX"})` states the axes of a mask type whose files do not name them; `read_mask` reads one mask's pixels (a `ValueError` for a negative label or a label above 2,147,483,647, the int32 limit of every MorphoBricks brick, as in `piece_counts`, `pair_counts` and `scan_masks`; `check_labels` diff --git a/pyproject.toml b/pyproject.toml index ffde5b95..2d1673e0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -283,9 +283,11 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.preview_render" = "pure" "morphobricks_preprocessing.cli" = "ui" "morphobricks_preprocessing.cli_run" = "ui" +"morphobricks_preprocessing.cli_run_options" = "ui" "morphobricks_preprocessing.cli_calibrate" = "ui" "morphobricks_preprocessing.cli_masks" = "ui" "morphobricks_preprocessing.cli_describe" = "ui" +"morphobricks_preprocessing.cli_describe_options" = "ui" "morphobricks_preprocessing.cli_convert" = "ui" "morphobricks_preprocessing.cli_convert_mask" = "ui" "morphobricks_preprocessing.cli_declare_masks" = "ui" @@ -347,6 +349,8 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.fast_layout" = "pure" "morphobricks_preprocessing.fast_statement" = "pure" "morphobricks_preprocessing.fast_answers" = "pure" +"morphobricks_preprocessing.describe_ids" = "pure" +"morphobricks_preprocessing.describe_questions" = "pure" "morphobricks_preprocessing.description" = "pure" "morphobricks_preprocessing.description_write" = "pure" "morphobricks_preprocessing.fov_identity" = "pure" @@ -435,14 +439,17 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.lock_file" = "io" "morphobricks_preprocessing.mask_conversion" = "orchestration" "morphobricks_preprocessing.mask_declare" = "orchestration" +"morphobricks_preprocessing.ignored_masks" = "io" "morphobricks_preprocessing.mask_conversion_ids" = "pure" "morphobricks_preprocessing.lineage_schema" = "pure" "morphobricks_preprocessing.code_identity" = "io" "morphobricks_preprocessing.he_tissue_rule" = "pure" "morphobricks_preprocessing.he_tissue_mask" = "orchestration" +"morphobricks_preprocessing.he_tissue_run_facts" = "orchestration" "morphobricks_preprocessing.he_tissue_array" = "orchestration" "morphobricks_preprocessing.run_inputs_tissue" = "orchestration" "morphobricks_preprocessing.cli_tissue_mask" = "ui" +"morphobricks_preprocessing.tissue_masks_folder" = "orchestration" "morphobricks_preprocessing.notebook_tissue_mask" = "ui" "morphobricks_preprocessing.mask_requests" = "pure" "morphobricks_preprocessing.masks.layout" = "io" @@ -472,6 +479,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.codec_bounds" = "io" "morphobricks_preprocessing.window_memory" = "pure" "morphobricks_preprocessing.window_reader" = "io" +"morphobricks_preprocessing.window_chunks" = "io" "morphobricks_preprocessing.block_cache" = "pure" "morphobricks_preprocessing.window_map" = "orchestration" "morphobricks_preprocessing.report" = "pure" diff --git a/src/morphobricks_preprocessing/__init__.py b/src/morphobricks_preprocessing/__init__.py index 31457c35..a0daf251 100644 --- a/src/morphobricks_preprocessing/__init__.py +++ b/src/morphobricks_preprocessing/__init__.py @@ -99,12 +99,14 @@ ) from .entry_record import ( ENTRY_FILENAME, + EntryIdentityWarning, EntryResult, brick_identity, build_record, check_entry_record, check_output_place, default_output, + identity_warning, publish, reuse_or_refuse, staging_folder, @@ -372,6 +374,7 @@ "DiscoveryResult", "EntryDeclaration", "EntryError", + "EntryIdentityWarning", "EntryResult", "EntrySettings", "FileEntry", @@ -510,6 +513,7 @@ "he_tissue_mask_array", "header_axes", "header_axis_issue", + "identity_warning", "image_type_issues", "inspect_experiment", "inspect_image", diff --git a/src/morphobricks_preprocessing/cli.py b/src/morphobricks_preprocessing/cli.py index 46f2fe5b..48056453 100644 --- a/src/morphobricks_preprocessing/cli.py +++ b/src/morphobricks_preprocessing/cli.py @@ -37,10 +37,12 @@ import argparse import logging +import shlex import sys from collections.abc import Sequence from pathlib import Path +from .axes import AxisReview from .cli_calibrate import add_calibrate_parser, calibrate_command, calibration_summary from .cli_convert import add_convert_parser, convert_command from .cli_convert_mask import add_convert_mask_parser, convert_mask_command @@ -51,6 +53,7 @@ add_missing_as_singleton, add_run_arguments, command_preflight, + declared_type, description_refusal, missing_as_singleton, parse_size, @@ -61,11 +64,14 @@ ) 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 .manifest import RunManifest 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,9 +85,55 @@ 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 +from .window_chunks import check_window_chunks __all__ = ["build_parser", "main", "parse_size"] +_CHECK_DESCRIPTION = """\ +Check a described experiment without measuring image pixels: the folders, the +image headers and any masks folder you give. Write a report and suggest the +image axis roles. + +Requires: a published experiment description (describe --publish). +check does not perform every validation of the description that run performs, +and it does not reuse the recorded --exclude, --masks and --mask-axes choices: +give the same options as your intended run.""" + +_CHECK_EXAMPLE = """\ +Example: + morphobricks-preprocessing check my_experiment + +If the check passes, run preprocessing next (run).""" + +_RUN_DESCRIPTION = """\ +Process a described experiment: validate the description and the axis roles, +then compute one intensity histogram per channel of every image plane +(plane_histograms.parquet). A rerun reads only new or changed images and reuses +the recorded exclusions and masks folder. + +Requires: a published experiment description (describe --publish).""" + +_RUN_EXAMPLE = """\ +Example: + morphobricks-preprocessing run my_experiment + +Then, if your analysis uses masks, check them (masks). Give the output folder +(my_experiment_MorphoBricks_Preprocessing) to the next MorphoBricks tool.""" + +_MASKS_DESCRIPTION = """\ +Check the mask pixels of a preprocessing run against their declared +representation, and report how the mask types relate. Run it after run when +your analysis uses masks; skip it otherwise. + +Requires: a preprocessing run whose masks are declared (declare-masks).""" + +_MASKS_EXAMPLE = """\ +Example: + morphobricks-preprocessing masks --output my_experiment_MorphoBricks_Preprocessing""" + def build_parser() -> argparse.ArgumentParser: """Build the argument parser.""" @@ -94,18 +146,31 @@ def build_parser() -> argparse.ArgumentParser: check = commands.add_parser( "check", - help="check the folder and image headers, suggest axis roles and write the report", + help="check a described experiment without measuring image pixels; write a report " + "and suggest the image axis roles", + description=_CHECK_DESCRIPTION, + epilog=_CHECK_EXAMPLE, + formatter_class=argparse.RawDescriptionHelpFormatter, ) _common(check) add_missing_as_singleton(check) - run = commands.add_parser("run", help="compute or update the histogram table") + run = commands.add_parser( + "run", + help="process a described experiment: compute or update the histogram table", + description=_RUN_DESCRIPTION, + epilog=_RUN_EXAMPLE, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) _common(run, recorded=True) add_run_arguments(run) masks = commands.add_parser( "masks", - help="find every image's masks, describe them and how they relate (reads the masks)", + help="check the mask pixels of a preprocessing run and how the mask types relate", + description=_MASKS_DESCRIPTION, + epilog=_MASKS_EXAMPLE, + formatter_class=argparse.RawDescriptionHelpFormatter, ) _common(masks, recorded=True) add_masks_arguments(masks) @@ -190,11 +255,16 @@ def _common(parser: argparse.ArgumentParser, *, recorded: bool = False) -> None: help="the experiment folder (default: the one the run in --output recorded)", ) else: - parser.add_argument("experiment", help="the experiment folder") + parser.add_argument( + "experiment", + help="folder containing your original experiment images, organised by condition " + "and repeat", + ) parser.add_argument( "--output", metavar="FOLDER", - help="output folder (default: next to the experiment, _MorphoBricks_Preprocessing)", + help="folder containing the published experiment description and preprocessing " + "results (default: EXPERIMENT_MorphoBricks_Preprocessing beside the images folder)", ) parser.add_argument( "--exclude", @@ -206,8 +276,9 @@ def _common(parser: argparse.ArgumentParser, *, recorded: bool = False) -> None: parser.add_argument( "--masks", metavar="FOLDER", - help="masks folder: one subfolder per mask type, each mirroring the experiment's " - "folders, outside the experiment; the label images of OME-Zarr images are added", + help="external masks folder, separate from the experiment folder: one subfolder per " + "mask type, or the mask type as an ending of each file name (image_01_cp_masks.tif); " + "OME-Zarr label images are also found automatically", ) _mask_axes_option(parser) _remove_stale_lock_option(parser) @@ -259,6 +330,18 @@ def _remove_stale_lock(args: argparse.Namespace) -> bool: return True +def _window_chunks(pre: Preflight, review: AxisReview) -> list[ValidationIssue]: + """Print and return the warning naming OME-Zarr chunks too large for windows (v0.10.1). + + Named by ``check``, before a later brick's windowed reads refuse them. + """ + chunks = check_window_chunks(pre.discovery.root, review) + if chunks: + print() + print(format_issues(chunks)) + return chunks + + def _check(args: argparse.Namespace) -> int: """Print what the preflight found and the suggested roles, and write the report.""" refusal = description_refusal(args) @@ -267,25 +350,24 @@ 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)) - axis_errors = () + undeclared = undeclared_mask_issues(args, pre) + if undeclared: # as 'run' refuses them, with its words + print() + print(format_issues(undeclared)) + axis_errors, chunks = (), [] if review is not None: # The suggested roles are the header's own, so they never contradict it; 'run' # checks the roles given with --axes. @@ -298,6 +380,7 @@ def _check(args: argparse.Namespace) -> int: if review.axis_check: print() print(format_issues(review.axis_check)) + chunks = _window_chunks(pre, review) print() # Suggested only where an image lacks some of the axes and is read with one plane. lacking = any(found.singleton_roles for found in review.file_mappings.values()) @@ -306,18 +389,107 @@ 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) - 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) - 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 + _print_image_type(args, pre, review) + path, refusal = write_check_report(pre, args.output, review, extra=[*undeclared, *chunks]) + if refusal is not None: + print("\n" + format_issues([refusal])) + blocked = not pre.ok or axis_errors or undeclared or refusal is not None + roles = None if review is None else pre.suggested_mapping.roles_string + print("\n" + check_status(args, path, blocked=bool(blocked), roles=roles, missing=missing)) return 1 if blocked else 0 # every error printed exits with 1, as 'run' does +def _print_image_type(args: argparse.Namespace, pre: Preflight, review: AxisReview) -> None: + """Print the image type the headers suggest, to compare with the published description.""" + type_review = review_image_type(pre.metadata, review, declared=declared_type(args, pre)) + print( + f"Suggested image type: {type_review.suggested}, because {type_review.reason}. " + "Confirm that it agrees with the published experiment description." + ) + + +def check_status( + args: argparse.Namespace, + path: Path | None, + *, + blocked: bool, + roles: str | None, + missing: bool, +) -> str: + """Return the final line of ``check``: passed (with the run command) or failed (P1.8). + + The run command keeps the experiment, ``--output``, ``--exclude``, ``--masks`` and + ``--mask-axes`` given to ``check``, and adds the suggested ``--axes``; paths are quoted. + """ + saved = f" Report saved to {path}." if path else "" + if blocked: + return f"Header check failed.{saved} Correct the errors above, then repeat the check." + words = ["morphobricks-preprocessing run", shlex.quote(args.experiment)] + if args.output: + words.append(f"--output {shlex.quote(args.output)}") + words += [f"--exclude {shlex.quote(item)}" for item in args.exclude] + if args.masks: + words.append(f"--masks {shlex.quote(args.masks)}") + stated = args.mask_axes or {} # read by main into {type: roles} + words += [f"--mask-axes {shlex.quote(f'{kind}={value}')}" for kind, value in stated.items()] + if roles: + words.append(f"--axes {roles}") + if missing: + words.append("--missing-as-singleton") + return ( + f"Header check passed.{saved} Review the warnings and axis roles above, then run " + f"preprocessing:\n {' '.join(words)}" + ) + + +def _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. + + ``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_calibrate.py b/src/morphobricks_preprocessing/cli_calibrate.py index 9356a290..5e724fdb 100644 --- a/src/morphobricks_preprocessing/cli_calibrate.py +++ b/src/morphobricks_preprocessing/cli_calibrate.py @@ -36,7 +36,19 @@ def add_calibrate_parser(commands: argparse._SubParsersAction) -> argparse.Argum """Add the ``calibrate`` command and its options; return its parser.""" parser = commands.add_parser( "calibrate", - help="show or state the pixel sizes in calibration.csv in the output folder", + help="show or state the physical pixel sizes of the images", + description="""\ +Show or state the physical pixel sizes of the images (calibration.csv in the +output folder). A stated size replaces what the image metadata say; images +without a stated size keep the sizes in their metadata, or stay uncalibrated. +The image pixels are never changed.""", + epilog="""\ +Example (every image: 0.65 micrometres along X and Y): + morphobricks-preprocessing calibrate my_experiment --size . XY 0.65 um + morphobricks-preprocessing run my_experiment + +Run preprocessing again afterwards to record the sizes.""", + formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( "experiment", @@ -50,9 +62,9 @@ def add_calibrate_parser(commands: argparse._SubParsersAction) -> argparse.Argum action="append", default=[], metavar=("TARGET", "AXES", "SIZE", "UNIT"), - help="state a size: TARGET is . for the whole experiment, or a folder or image " - "relative to the experiment folder; AXES are X, Y and/or Z (XY: the same size for " - "both); UNIT is a length unit such as um or nm (repeatable)", + help="state the physical pixel size: TARGET is . for every image, or a folder or image " + "path relative to the experiment; AXES are X, Y and/or Z (XY: the same size for both); " + "UNIT is a length unit such as um or nm. Example: --size . XY 0.65 um (repeatable)", ) parser.add_argument( "--pixels", @@ -60,7 +72,8 @@ def add_calibrate_parser(commands: argparse._SubParsersAction) -> argparse.Argum action="append", default=[], metavar=("TARGET", "AXES"), - help="state that these axes are measured in pixels: deliberately uncalibrated (repeatable)", + help="use pixel units rather than physical lengths for these axes; does not rescale or " + "modify the image pixels (repeatable)", ) parser.add_argument( "--remove", @@ -114,7 +127,10 @@ def calibrate_command(args: argparse.Namespace) -> int: print(f"Nothing was changed: {exc}") return 1 if written is not None: - print(f"Written to {written}. The next run records these sizes; no row is recomputed.") + print( + f"Calibration saved to {written}. Run preprocessing again to record these pixel " + "sizes; existing verified histograms can be reused." + ) print(calibration_summary(changed)) return 0 @@ -143,7 +159,10 @@ def _axes(text: str) -> tuple[str, ...]: def calibration_summary(calibration: Calibration) -> str: """Describe the statements, one per line, or say there are none.""" if not calibration.entries: - return "No pixel size is stated: every image uses the sizes in its metadata." + return ( + "No pixel sizes have been stated. Pixel sizes are taken from the image metadata " + "where available; otherwise the images remain uncalibrated." + ) lines = ["Stated pixel sizes (calibration.csv):"] lines.extend( f" {entry.target} {entry.axis}: {entry.describe()}" for entry in calibration.entries diff --git a/src/morphobricks_preprocessing/cli_convert.py b/src/morphobricks_preprocessing/cli_convert.py index 347c6cbf..c55aa98b 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, @@ -19,13 +26,16 @@ from __future__ import annotations import argparse +import shlex import sys +from dataclasses import dataclass from pathlib import Path from .cli_run import mapping_option, parse_size, print_progress 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 @@ -49,10 +59,29 @@ def add_convert_parser(commands: argparse._SubParsersAction) -> argparse.Argumen """ convert = commands.add_parser( "convert", - help="save the images whose axes are wrong or not named as named-axis OME-TIFF copies " - "with your roles, in a new folder (the originals are only read)", + help="write image copies with corrected axis metadata, convert images to OME-Zarr, or " + "project Z-stacks to 2-D; the original images are unchanged", + description="""\ +Write image copies in a new folder: with corrected axis metadata (OME-TIFF), as +OME-Zarr (--store ome-zarr), or as 2-D projections of Z-stacks (--project). +The original images are only read. The copies are an experiment of their own: +describe and publish it before you check and run preprocessing on it.""", + epilog="""\ +Examples (the axis orders are examples: give the stored order of your images; +an RGB TIFF stores its colours last, YXC): + morphobricks-preprocessing convert my_experiment --to my_experiment_named --axes CYX + morphobricks-preprocessing convert my_slides --to my_slides_zarr --axes CYX \\ + --store ome-zarr + morphobricks-preprocessing convert my_experiment --to my_experiment_max \\ + --axes ZCYX --project max + +convert does not check the axis order against the image: look at a copy.""", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + convert.add_argument( + "experiment", + help="folder containing your original experiment images, organised by condition and repeat", ) - convert.add_argument("experiment", help="the experiment folder") convert.add_argument( "--to", metavar="FOLDER", @@ -64,22 +93,33 @@ def add_convert_parser(commands: argparse._SubParsersAction) -> argparse.Argumen "--axes", metavar="ROLES", required=True, - help="the role of each axis of the images, in the order of their axes (X, Y, Z, C, T, " - "or - for none): the roles the copies are written with", + help="roles of the stored dimensions, in their stored order: Y and X are image height " + "and width, C is channel, Z is depth, T is time, - an unused length-1 dimension; for " + "example CYX (an RGB TIFF: YXC). The copies are written with these roles", ) convert.add_argument( "--exclude", action="append", default=[], metavar="PATH", - help="image to leave unread, relative to the experiment folder; it is copied as it " - "is (repeatable)", + help="copy this image unchanged instead of converting it, relative to the experiment " + "folder (repeatable). The next commands printed keep it excluded; give the same " + "exclusion whenever you describe, check or run the copies", ) convert.add_argument( "--missing-as-singleton", action="store_true", - help="confirm that images lacking some axes have one plane along them", + help="confirm that an image without a particular dimension has size 1 along it; " + "this does not enable analysis of multi-slice Z-stacks", ) + _add_folder_options(convert) + _add_projection_options(convert) + _add_store_options(convert) + return convert + + +def _add_store_options(convert: argparse.ArgumentParser) -> None: + """Add the memory, lock, store and log options of ``convert``.""" convert.add_argument( "--memory-limit", type=parse_size, @@ -93,10 +133,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", ) - _add_folder_options(convert) - _add_projection_options(convert) + convert.add_argument( + "--store", + choices=STORES, + default=OME_TIFF, + help="ome-tiff (default): correct the axis metadata where needed and copy the other " + "images unchanged; ome-zarr: convert every selected image to OME-Zarr (OME-NGFF 0.4), " + "RGB images included. Writing and reading OME-Zarr needs the zarr extra", + ) convert.add_argument("--log", metavar="FILE", help="write technical details to this file") - return convert def _add_folder_options(convert: argparse.ArgumentParser) -> None: @@ -104,14 +149,16 @@ def _add_folder_options(convert: argparse.ArgumentParser) -> None: convert.add_argument( "--output", metavar="FOLDER", - help="the output folder of your runs on the originals, named in the next commands " - "(default: the experiment folder's name with _MorphoBricks_Preprocessing)", + help="preprocessing output folder of the original experiment (default: " + "EXPERIMENT_MorphoBricks_Preprocessing); --to says where the copies go. Projected " + "copies get a new output folder of their own", ) convert.add_argument( "--masks", metavar="FOLDER", - help="the masks folder of your runs, which the copies may not be inside; by default " - "the one recorded by the run in the output folder (--output)", + help="masks folder of the original experiment, used to check that the copies are not " + "written inside it and that projection can proceed; masks are not converted " + "(default: the one recorded in --output)", ) @@ -123,19 +170,19 @@ def _add_projection_options(convert: argparse.ArgumentParser) -> None: const="", type=_method, metavar="METHOD", - help="write every image as a recorded 2-D projection of its Z-stack: max, mean or " - "sum (there is no default). Z must be among the roles in --axes. The copies are " - "named-axis OME-TIFFs without Z; a 16-bit sum is written in 32 bits, a mean in 64-bit " - "floats, a maximum keeps the type; the Z size is not written but recorded. Masks " - "are never projected: masks with depth slices stop the projection", + help="project the Z slices of each selected image with max, mean or sum (no " + "default); Z must be among the roles in --axes. The output has no Z dimension and is " + "OME-TIFF by default, OME-Zarr with --store ome-zarr. A maximum keeps the pixel type; " + "a 16-bit sum uses 32-bit values, a mean 64-bit floats. Masks are not projected: " + "masks with depth slices stop the projection", ) convert.add_argument( "--z-range", type=_z_range, metavar="START:STOP", - help="with --project: use only these slices of every image (zero-based, STOP " - "excluded, for example 2:10; 4:5 is the single slice 4). Every image must have " - "them. Default: all slices", + help="with --project: the Z slices to project; 2:10 uses slices 2 to 9, counting the " + "first slice as 0 (4:5 is slice 4 alone). Every selected image must contain that " + "range. Default: all slices", ) @@ -188,17 +235,52 @@ 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)) + after = _NextOptions(tuple(args.exclude), args.missing_as_singleton) + print(conversion_text(result, output, given=given, store=args.store, after=after)) return 0 if result.written else 1 -def conversion_text(result: ConversionResult, output: Path, *, given: bool = True) -> str: +@dataclass(frozen=True) +class _NextOptions: + """The options of a conversion the next commands on the copies keep (review P0.2, P1.18).""" + + exclude: tuple[str, ...] = () + missing_as_singleton: bool = False + + def arguments(self) -> str: + """Return the options as command-line text, each path quoted for the shell.""" + words = [f" --exclude {shlex.quote(path)}" for path in self.exclude] + return "".join(words) + (" --missing-as-singleton" if self.missing_as_singleton else "") + + +def _next_commands(dest: Path, output: Path, axes: str, after: _NextOptions) -> list[str]: + """Return the describe, check and run lines for the copies in ``dest`` (paths quoted).""" + folder, out, keep = shlex.quote(str(dest)), shlex.quote(str(output)), after.arguments() + exclude = "".join(f" --exclude {shlex.quote(path)}" for path in after.exclude) + return [ + f" morphobricks-preprocessing describe {folder} --output {out}{exclude}", + "Publish the description with describe --publish and your confirmed channel and " + "design options (or in the notebook). Once it is published, run:", + f" morphobricks-preprocessing check {folder} --output {out}{keep}", + f" morphobricks-preprocessing run {folder} --output {out}{axes}{keep}", + ] + + +def conversion_text( + result: ConversionResult, + output: Path, + *, + given: bool = True, + store: str = OME_TIFF, + after: _NextOptions | None = None, +) -> str: """Say what a conversion wrote and what to run next, in plain ASCII-safe words. Parameters @@ -210,36 +292,51 @@ 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. + after + The exclusions and ``--missing-as-singleton`` of the conversion, kept in the next + commands (default: none). Returns ------- str """ + after = after or _NextOptions() dest = result.destination + fmt = "OME-Zarr" if store == OME_ZARR else "OME-TIFF" if not result.written: return f"No copies were written in {dest}: read the messages above." if result.projection is not None: - return projection_text(result, output) + return projection_text(result, output, store=store, after=after) # Cross-brick test F8: the next commands name the output folder of the user's runs, # given with --output; a default one may hold no run (the user then gives theirs). where = "" if given else f" (by default {output}; if your runs used another one, give it)" 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})", + f"Conversion details saved to {dest / RECORD_FILENAME}.", "", - "Next, run preprocessing on the copies with the output folder of your runs on the " - f"originals{where}:", - f" morphobricks-preprocessing check {dest} --output {output}", + f"Next, preprocess the copies with the output folder of your runs on the originals" + f"{where}. If it already holds a published description that matches these copies, " + "keep using it and skip describe. Otherwise describe the copied experiment first:", ] axes = f" --axes {result.suggested_axes}" if result.suggested_axes else " --axes ROLES" - lines.append(f" morphobricks-preprocessing run {dest} --output {output}{axes}") + lines += _next_commands(dest, output, axes, after) + if not result.suggested_axes: + lines.append("Replace ROLES with the roles of the copies' stored dimensions.") return "\n".join(lines) -def projection_text(result: ConversionResult, output: Path) -> str: +def projection_text( + result: ConversionResult, + output: Path, + *, + store: str = OME_TIFF, + after: _NextOptions | None = None, +) -> str: """Say what a projection wrote and what to run next (a new output folder, a new source). Parameters @@ -249,11 +346,17 @@ 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. + after + The exclusions and ``--missing-as-singleton`` of the conversion, kept in the next + commands (default: none). Returns ------- str """ + after = after or _NextOptions() dest, projection = result.destination, result.projection bounds = projection.z_range slices = "all slices" if bounds is None else f"slices {bounds[0]}:{bounds[1]}" @@ -261,19 +364,19 @@ 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')}", " The Z size is not written to the copies; the record keeps it, the slices used " "and the SHA-256 of every source.", - f"Conversion record: {dest / RECORD_FILENAME} (SHA-256 {result.record_sha256})", + f"Conversion details saved to {dest / RECORD_FILENAME}.", "", - "The projected copies are a different source: run preprocessing on them with a new " - f"output folder ({output}), which starts a new description; the design and the " - "pixel sizes are then entered again. Masks are never projected: 2-D masks pair " - "with the projected images as usual.", - f" morphobricks-preprocessing check {dest} --output {output}", - f" morphobricks-preprocessing run {dest} --output {output}{axes}", + f"Projected images were saved in {dest}. Describe them as a new experiment before " + f"running preprocessing, with a new output folder ({output}). Review the channel " + "names, experimental design and pixel sizes. Masks are not projected: make 2-D " + "masks for the projected images.", + *_next_commands(dest, output, axes, after), ] ) diff --git a/src/morphobricks_preprocessing/cli_declare_masks.py b/src/morphobricks_preprocessing/cli_declare_masks.py index 729654ae..4bd36937 100644 --- a/src/morphobricks_preprocessing/cli_declare_masks.py +++ b/src/morphobricks_preprocessing/cli_declare_masks.py @@ -7,17 +7,40 @@ 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 -nothing written, else 0 (also when every mask type was declared as asked already). +commands that follow (``run``, then ``masks``): with ``--masks`` they name that folder; without +it they name none, because OME-Zarr label images are found without a masks folder (other masks are +always in a separate masks folder), and say when to add one. The experiment folder is +named only when no run of the output folder records it. ``--ignore TYPE`` (repeatable; owner, +4 December 2026) lists a mask type or OME-Zarr label image the runs do not use in +``ignored_masks.toml`` (:mod:`.ignored_masks`): ``check`` and ``run`` skip it instead of +refusing it as undeclared. Exit status 1 for a refusal, with nothing written, else 0 (also when +every mask type was declared as asked already). """ from __future__ import annotations import argparse import shlex +from pathlib import Path from .description_rules import REPRESENTATIONS -from .mask_declare import MaskDeclaration, MaskDeclarationRefused, declare_masks +from .ignored_masks import IGNORED_FILENAME +from .mask_declare import ( + MaskDeclaration, + MaskDeclarationRefused, + check_ignore, + declare_masks, + declared_types, + ignore_masks, +) +from .run.lock import OutputLockedError +from .run.reuse import recorded_experiment_root + +NO_MASKS_FOLDER = ( + "OME-Zarr label images are discovered automatically. External TIFF masks must be stored " + "in a separate masks folder: add --masks FOLDER to both commands, unless an earlier " + "preprocessing run already recorded it." +) def add_declare_masks_parser(commands: argparse._SubParsersAction) -> argparse.ArgumentParser: @@ -35,25 +58,63 @@ def add_declare_masks_parser(commands: argparse._SubParsersAction) -> argparse.A """ declare = commands.add_parser( "declare-masks", - help="declare mask types (added after preprocessing) in the published description, " - "so run --masks accepts them", + help="declare mask types (existing masks, or masks added later) in the published " + "description, so preprocessing accepts them", + description="""\ +Declare each mask type before running preprocessing with those masks: right +after publishing the experiment description, or later for masks added to an +existing preprocessing run. Then run preprocessing, and check the mask pixels +with the masks command. + +Mask representations: + instances one positive label per object (for example a Cellpose mask) + binary foreground and background (a region) + parent_labels one label per group of objects""", + epilog="""\ +Examples: + morphobricks-preprocessing declare-masks \\ + --output my_experiment_MorphoBricks_Preprocessing \\ + --masks my_masks --type Cells=instances + morphobricks-preprocessing declare-masks \\ + --output my_experiment_MorphoBricks_Preprocessing \\ + --masks my_masks --type cp_masks=instances:Cells + +The second declares masks named like image_01_cp_masks.tif (the mask type as a +file-name ending) with the mask ID Cells. Do not declare and ignore the same +mask type.""", + formatter_class=argparse.RawDescriptionHelpFormatter, ) declare.add_argument( - "--output", metavar="FOLDER", required=True, help="the output folder of the run" + "--output", + metavar="FOLDER", + required=True, + help="the preprocessing output folder containing morphobricks.toml", ) declare.add_argument( "--type", dest="types", action="append", - required=True, + default=[], metavar="TYPE=REPRESENTATION[:ID]", - help=f"a mask type (its folder name) and what it is: {', '.join(REPRESENTATIONS)}; " - "optionally its ID (default: the folder name). Repeatable", + help="mask type and representation: instances (one positive label per object), " + "binary (foreground and background) or parent_labels (one label per group of " + "objects); optionally a different mask ID after a colon. Example: Cells=instances " + f"(representations: {', '.join(REPRESENTATIONS)}; repeatable)", + ) + declare.add_argument( + "--ignore", + action="append", + default=[], + metavar="TYPE", + help="skip a mask type you do not want to analyse: give its exact folder name, " + "file-name ending or OME-Zarr label name (repeatable). A declared type cannot be " + "ignored; declaring an ignored type with --type uses it again", ) declare.add_argument( "--masks", metavar="FOLDER", - help="the masks folder: each mask type is also checked against it", + help="external masks folder, used to check the mask-type names; the mask pixels are " + "checked later by the masks command", ) return declare @@ -77,22 +138,79 @@ def parse_type(text: str) -> MaskDeclaration: def declare_masks_command(args: argparse.Namespace) -> int: - """Declare the mask types; print what was declared and the next commands.""" + """Declare the mask types and the ignored ones; print what changed and the next commands.""" + if not args.types and not args.ignore: + print("Give at least one --type TYPE=REPRESENTATION or --ignore TYPE. Nothing was written.") + return 1 try: declarations = [parse_type(text) for text in args.types] - done = declare_masks(args.output, declarations, masks_folder=args.masks) - except (ValueError, MaskDeclarationRefused) as exc: - codes = f" ({', '.join(exc.codes)})" if getattr(exc, "codes", ()) else "" - print(f"Not declared{codes}: {exc}") - print("Nothing was written.") - return 1 - if done.publication is None: + 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, OutputLockedError, OSError) as exc: + return _refused(exc, "Nothing was written.") + try: + ignored, changed = ignore_masks( + args.output, args.ignore, declared=declared_types(args.output) + ) + except (ValueError, OutputLockedError, OSError) as exc: + if done is not None and done.publication is not None: + saved = ( + f"Mask declarations saved to {done.publication.path}: {', '.join(done.added)}. " + "The ignore list was not updated. The saved declarations remain in place." + ) + else: + saved = "No mask declaration changed. The ignore list was not updated." + return _refused(exc, saved, ignore=True) + if done is not None and done.publication is None: print("Every mask type is declared as asked already; nothing was written.") - else: + elif done is not None: 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}") + if changed: + listed = ", ".join(ignored) if ignored else "none (the file was removed)" + print(f"Mask types the runs skip ({IGNORED_FILENAME}): {listed}.") + elif args.ignore: + print(f"Already skipped ({IGNORED_FILENAME}): {', '.join(ignored)}; nothing was written.") + for line in next_commands(args.output, args.masks): + print(line) return 0 + + +def _refused(exc: Exception, written: str, *, ignore: bool = False) -> int: + """Print a refusal with its codes and what was (not) written; return exit status 1.""" + codes = f" ({', '.join(exc.codes)})" if getattr(exc, "codes", ()) else "" + print(f"{'Mask settings not updated' if ignore else 'Not declared'}{codes}: {exc}") + print(written[0].upper() + written[1:]) + return 1 + + +def next_commands(output: str, masks: str | None) -> list[str]: + """Return the lines naming the commands that follow a declaration. + + ``masks`` is the masks folder given, or None: the masks may then be OME-Zarr label images + or a masks folder the run already records, which ``run`` finds without ``--masks``, so no + placeholder folder is named. The experiment folder is named (``EXPERIMENT``) unless a run + of the output folder records it, and the text then says to replace it. + """ + recorded, _ = recorded_experiment_root(Path(output).resolve()) + target = ("" if recorded is not None else "EXPERIMENT ") + f"--output {shlex.quote(output)}" + if masks is not None: + option = f" --masks {shlex.quote(masks)}" + lines = ["Next, run preprocessing with the masks folder, then check the masks:"] + else: + option = "" + lines = ["Next, run preprocessing again, then check the masks:"] + if recorded is None: + lines.append("Replace EXPERIMENT below with the folder containing your original images.") + lines += [ + f" morphobricks-preprocessing run {target}{option}", + f" morphobricks-preprocessing masks {target}{option}", + ] + 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..45673a3d 100644 --- a/src/morphobricks_preprocessing/cli_describe.py +++ b/src/morphobricks_preprocessing/cli_describe.py @@ -27,10 +27,14 @@ **Fast mode (Spec ADR 0006, owner decision FC1) is the default for a new description.** With ``--channels`` (the tagged unit's channel IDs in order), ``--image-type``, ``--accept-ids``, -``--comparable`` and ``--confirmed-on``, every answer is the user's, stated in the command -(:mod:`.fast_answers`), and ``--publish`` publishes a fast-mode file in one command after every -image's header was checked against the list (a contradiction lists every image, -``R_FAST_LAYOUT_CONTRADICTION``, and nothing is written). ``--strict`` keeps the per-unit +``--comparable`` and ``--confirmed-on``, every answer is the user's (``--id FOLDER=ID`` names +the ID of a folder that has no proposal, such as ``control``: :mod:`.describe_ids`), stated in +the command (:mod:`.fast_answers`), and ``--publish`` publishes a fast-mode file in one command +after every image's header was checked against the list (a contradiction lists every image, +``R_FAST_LAYOUT_CONTRADICTION``, and nothing is written). ``--rgb-header-override [FOLDER]`` +states that colour scanner TIFFs whose header does not say colour are R, G and B (recorded as +``rgb_header_override = true`` on those units, as the notebook records it). The open questions +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. @@ -41,8 +45,12 @@ from __future__ import annotations import argparse +import shlex from pathlib import Path +from .cli_describe_options import add_describe_parser as add_describe_parser +from .describe_ids import apply_ids +from .describe_questions import fast_question_lines, proposal, question_blockers, question_lines from .description import Description, DescriptionError from .description_reconcile import ( CHANNELS_CHANGED, @@ -57,8 +65,7 @@ from .description_run_text import physical_issues from .discovery import DiscoveryResult, default_output_folder, discover_experiment from .draft import Draft, DraftError, draft_from_discovery -from .draft_answers import DraftAnswers, description_from_draft -from .draft_ids import IdKind, id_problems +from .draft_answers import DraftAnswers, description_from_draft, valid_day from .fast_answers import fast_answers, tagged_unit from .metadata import inspect_images from .name_issues import non_nfc_folders_issue @@ -76,16 +83,30 @@ "--comparable, --confirmed-on and --publish; --strict tags each acquisition on its own in " "the notebook." ) -QUESTION_TEXT = { - "id_pending": "choose the ID of {subject} (accept the proposal or type another)", - "repeat_not_confirmed": ( - "confirm that the folders of {subject} were prepared and acquired under the same " - "circumstances, so they are comparable" - ), - "confirmed_on_missing": "{subject} is confirmed but has no date: confirm it again", -} -"""What the user must do for each open question of a draft, in plain words.""" - +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." +) +ID_ONLY_NEW = ( + "--id names the IDs of a new fast-mode description; a published description, or the " + "strict mode, names them in the notebook. Nothing was written." +) +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, use the notebook's step 1 (Check and save); 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 " @@ -116,68 +137,18 @@ def _confirm_again(rec: Reconciliation) -> dict[str, tuple[str, ...]]: return {repeat: reasons for repeat, reasons in found.items() if reasons} -def add_describe_parser(commands: argparse._SubParsersAction) -> argparse.ArgumentParser: - """Add the ``describe`` command and its options; return its parser.""" - describe = commands.add_parser( - "describe", - help="show the draft experiment description (proposals, open questions) in plain " - "language; writes nothing, and confirms nothing", - ) - describe.add_argument("experiment", help="the experiment folder") - describe.add_argument( - "--output", - metavar="FOLDER", - help="output folder holding morphobricks.toml " - "(default: next to the experiment, _MorphoBricks_Preprocessing)", - ) - describe.add_argument( - "--exclude", - action="append", - default=[], - metavar="PATH", - help="image to leave out, relative to the experiment folder (repeatable)", - ) - describe.add_argument( - "--strict", - action="store_true", - help="describe in the strict per-unit mode: each acquisition's channels confirmed on " - "its own (in the notebook). Default: fast mode, one channel list for the experiment " - "(Spec ADR 0006)", - ) - describe.add_argument( - "--channels", - metavar="ID,ID,...", - help="fast mode: the channel IDs of the first acquisition in folder order (the tagged " - "unit, named in the output), in source order C0, C1, ...; its header names are " - "confirmed as their header names. Every acquisition is stated to have them", - ) - describe.add_argument( - "--image-type", - choices=("channels", "rgb"), - help="fast mode: the image type of the list (never inferred)", - ) - describe.add_argument( - "--accept-ids", action="store_true", help="fast mode: accept every proposed ID" - ) - describe.add_argument( - "--comparable", - action="store_true", - help="fast mode: every biological repeat's folders were prepared and acquired under " - "the same circumstances (your answer, dated --confirmed-on)", - ) - describe.add_argument( - "--confirmed-on", - metavar="YYYY-MM-DD", - help="fast mode: the day of your statements (never read from the clock)", - ) - describe.add_argument( - "--publish", - action="store_true", - help="publish the description only when no question is open and every decision is " - "confirmed; otherwise exit with status 1 and list what is missing. Nothing is " - "confirmed for you", - ) - return describe +PREVIEW_NOTE = ( + "Preview only. No description has been saved. Your options are reflected above; the " + "channel list and the image headers are validated when you publish (--publish)." +) +"""Said after a preview of a new description (review P1.3).""" + +PUBLISHED_NOTE = ( + "This experiment already has a published description. The command displays it but does " + "not change its channel list or experimental design. To edit it, open the existing " + "description in the notebook and use Check and save." +) +"""Said whenever describe shows an existing description (review P1.4).""" def describe_command(args: argparse.Namespace) -> int: @@ -201,22 +172,36 @@ def describe_command(args: argparse.Namespace) -> int: if found is not None: lines, blockers = _published(found.description, discovery, excluded, output) else: - draft = draft_from_discovery(discovery, excluded) - lines, blockers = draft_lines(draft, root), draft_blockers(draft) + draft = _named(args, draft_from_discovery(discovery, excluded)) + if draft is None: + return 1 if not args.strict and args.channels is not None: + lines = draft_lines(draft, root, questions=False) return describe_fast(args, draft, discovery, excluded, output, lines) + lines, blockers = draft_lines(draft, root), draft_blockers(draft) if not args.strict: lines.append(FAST_HINT) + ignored = _ignored_options(args, published=found is not None, output=output) + if ignored is not None: + print(ignored) + return 1 print("\n".join(lines)) + if found is not None: + print() + print(PUBLISHED_NOTE) if not args.publish: + if found is None: + print() + print(PREVIEW_NOTE) return 0 print() if not blockers and any(line.startswith(" headers changed:") for line in lines): print( - "Nothing to publish: no answer is missing. The run stops until the image headers " - "fit the published description (headers changed, above)." + "The published description no longer matches the image headers. It was not " + "changed. Correct the channel names or order in the notebook, save the " + "description, then run preprocessing again." ) - return 0 + 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 @@ -225,6 +210,32 @@ def describe_command(args: argparse.Namespace) -> int: return 1 +def _ignored_options(args: argparse.Namespace, *, published: bool, output: Path) -> str | None: + """Return the refusal of an option describe would ignore, or None: never silently ignored.""" + given = _fast_options_given(args) + if published and given: # review of v0.10.1 + return PUBLISHED_UNCHANGED.format(options=", ".join(given), output=output) + if published and args.id: + return ID_ONLY_NEW + if args.rgb_header_override: + new_fast = not published and not args.strict + return OVERRIDE_NEEDS_CHANNELS if new_fast else OVERRIDE_ONLY_FAST + return None + + +def _named(args: argparse.Namespace, draft: Draft) -> Draft | None: + """Return the draft with the IDs ``--id`` names, or None after printing every refusal.""" + if args.id and args.strict: + print(ID_ONLY_NEW) + return None + named, refusals = apply_ids(draft, args.id) + if refusals: + print("Nothing was written. These IDs cannot be used:") + print("\n".join(f" - {item}" for item in refusals)) + return None + return named + + def describe_fast( args: argparse.Namespace, draft: Draft, @@ -245,12 +256,20 @@ 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, + accept_ids=args.accept_ids, + comparable=args.comparable, + dated=args.confirmed_on is not None and valid_day(args.confirmed_on), + named=bool(args.id), + ), "", "Fast mode (the default; --strict for the per-unit mode): one channel list for the " "experiment, the order of the tagged unit " @@ -258,9 +277,12 @@ def describe_fast( ] print("\n".join(lines)) if not args.publish: + print() + print(PREVIEW_NOTE) return 0 print() channels = [c for c in (args.channels or "").split(",") if c] + override, unknown = override_units(args.rgb_header_override, discovery, draft) answers, blockers = fast_answers( draft, channels, @@ -269,7 +291,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: @@ -285,13 +309,82 @@ def describe_fast( print("Not published: some images cannot be checked against the channel list.") print(format_issues(refused)) return 1 - return _publish_fast(draft, answers, discovery, headers, output) + if not _publish_fast(draft, answers, discovery, headers, output): + return 1 + print("\n".join(next_steps(args, excluded))) + return 0 + + +def override_units( + 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 next_steps(args: argparse.Namespace, excluded: list[str]) -> list[str]: + """Return the check and run commands after a publication (review P1.2), paths quoted. + + The experiment folder is the one given; ``--output`` and ``--exclude`` are kept when given. + """ + options = f" --output {shlex.quote(args.output)}" if args.output else "" + options += "".join(f" --exclude {shlex.quote(path)}" for path in excluded) + experiment = shlex.quote(args.experiment) + return [ + "Next, check the experiment and run preprocessing:", + f" morphobricks-preprocessing check {experiment}{options}", + f" morphobricks-preprocessing run {experiment}{options}", + "If check suggests an --axes value, review it and give it to run.", + ] -def _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 _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( @@ -300,17 +393,19 @@ def _publish_fast( discovery: DiscoveryResult, headers: list, output: Path, -) -> int: - """Check every image against the list, then publish; nothing is written on any refusal.""" +) -> bool: + """Check every image against the list, then publish; False (nothing written) on a refusal.""" try: candidate = description_from_draft(draft, answers) except DraftError as exc: print(f"Not published: {exc}") - return 1 + return False report = check_physical(candidate, discovery, headers) if report.issues: print(format_issues(physical_issues(report.issues))) - return 1 + if any(issue.override_fits for issue in report.issues): + print(OVERRIDE_CLI) + return False if report.unchecked: # every image's count and type checked, never a guessed count print( "Not published: these images could not be checked against the channel list (their " @@ -318,7 +413,7 @@ def _publish_fast( "example with the notebook or convert, and describe again):" ) print("\n".join(f" - {path}" for path in report.unchecked)) - return 1 + return False output.mkdir(parents=True, exist_ok=True) try: publication = publish_description( @@ -326,24 +421,21 @@ def _publish_fast( ) except (PublicationRefused, DescriptionError, ValueError) as exc: print(f"Not published: {exc}") - return 1 + return False print( - f"Published {publication.path} in fast mode (channel list " - f"{list(candidate.channel_layout.channels)})." + f"Experiment description saved to {publication.path}. Channels, in their stored " + f"order: {', '.join(candidate.channel_layout.channels)}. The channel list agrees " + "with the image headers checked during publication." ) - return 0 - + return True -def _proposal(kind: IdKind, folder: str, slot_proposed: str | None) -> str: - """Say what is proposed for a folder, or why nothing is.""" - if slot_proposed is not None: - return f"proposed ID {slot_proposed!r}" - why = ", ".join(id_problems(kind, folder)) - return f"no ID can be proposed ({why or 'in use'}): you name it" +def draft_lines(draft: Draft, root: Path, *, questions: bool = True) -> list[str]: + """Return the plain-language report of a draft. -def draft_lines(draft: Draft, root: Path) -> 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.", @@ -351,42 +443,33 @@ def draft_lines(draft: Draft, root: Path) -> list[str]: "Conditions (folder: proposal)", ] out += [ - f" {folder}: {_proposal('conditions', folder, slot.proposed)}" + f" {folder}: {proposal('conditions', folder, slot.proposed, slot.confirmed)}" for folder, slot in sorted(draft.conditions.items()) ] out += ["", "Technical repeats (folder: proposal)"] out += [ - f" {folder}: {_proposal('technical_repeats', folder, slot.proposed)}" + f" {folder}: {proposal('technical_repeats', folder, slot.proposed, slot.confirmed)}" for folder, slot in sorted(draft.technical_repeats.items()) ] out += ["", "Biological repeats"] for group, repeat in sorted(draft.repeats.items()): state = f"confirmed on {repeat.confirmed_on}" if repeat.confirmed else "not confirmed" - out.append(f" {group}: {_proposal('repeats', group, repeat.id.proposed)}; {state}") + said = proposal("repeats", group, repeat.id.proposed, repeat.id.confirmed) + out.append(f" {group}: {said}; {state}") out += [ f" {m.condition} / {m.source_repeat}: {m.image_count} images" for m in repeat.members ] 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) - return out - - -def _question_lines(draft: Draft) -> list[str]: - """Return what the user still has to answer, one line each.""" - questions = draft.open_questions() - if not questions: - return ["", "No question is open."] - out = ["", f"{len(questions)} open questions (answered by you, in the notebook):"] - out += [f" - {QUESTION_TEXT[q.code].format(subject=q.subject)}" for q in questions] + if questions: + out += question_lines(draft) return out def draft_blockers(draft: Draft) -> list[str]: """Return everything that stops this draft from being published, in plain words.""" - blockers = [QUESTION_TEXT[q.code].format(subject=q.subject) for q in draft.open_questions()] - return blockers or [NOT_IN_DRAFT] + return question_blockers(draft) or [NOT_IN_DRAFT] def _published( diff --git a/src/morphobricks_preprocessing/cli_describe_options.py b/src/morphobricks_preprocessing/cli_describe_options.py new file mode 100644 index 00000000..b04ed175 --- /dev/null +++ b/src/morphobricks_preprocessing/cli_describe_options.py @@ -0,0 +1,127 @@ +"""The ``describe`` command's options: its parser, help texts and fast-mode options. + +Moved from :mod:`.cli_describe` (which re-exports :func:`add_describe_parser`) to keep that +module within the line limit. What the options mean is in :mod:`.cli_describe`. +""" + +from __future__ import annotations + +import argparse + +__all__ = ["add_describe_parser"] + + +def add_describe_parser(commands: argparse._SubParsersAction) -> argparse.ArgumentParser: + """Add the ``describe`` command and its options; return its parser.""" + describe = commands.add_parser( + "describe", + help="preview an experiment description or publish it with --publish", + description="""\ +Preview an experiment description: the proposed IDs of conditions and repeats, +and the questions still open. With --publish and the options below, validate +and save it (morphobricks.toml in the output folder); every check, run and masks +command needs a published description. + +Fast publication from the command line creates a new description for an +experiment with one shared channel list. Use the notebook to edit an existing +description, change repeat pairing or describe acquisitions with different +channel lists or orders.""", + epilog="""\ +Example (two fluorescence channels stored in the order collagen, fibronectin): + morphobricks-preprocessing describe my_experiment + morphobricks-preprocessing describe my_experiment \\ + --channels COL,FN --image-type channels \\ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish + +Review the proposed IDs before accepting them. Give --comparable only if it is +true. Then check and run preprocessing.""", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + describe.add_argument( + "experiment", + help="folder containing your original experiment images, organised by condition and repeat", + ) + describe.add_argument( + "--output", + metavar="FOLDER", + help="folder that holds (or will hold) the published description, morphobricks.toml " + "(default: EXPERIMENT_MorphoBricks_Preprocessing beside the images folder)", + ) + describe.add_argument( + "--exclude", + action="append", + default=[], + metavar="PATH", + help="image to leave out, relative to the experiment folder (repeatable)", + ) + describe.add_argument( + "--strict", + action="store_true", + help="use separate channel descriptions for each acquisition; complete and publish " + "them in the notebook. By default, one channel list is used for the whole experiment", + ) + _add_fast_options(describe) + describe.add_argument( + "--publish", + action="store_true", + help="validate and save the description; without --publish, show a preview only. " + "When a question is still open, exit with status 1 and list it", + ) + return describe + + +def _add_fast_options(describe: argparse.ArgumentParser) -> None: + """Add the fast-mode statements of ``describe`` (Spec ADR 0006, :mod:`.fast_answers`).""" + describe.add_argument( + "--channels", + metavar="ID,ID,...", + help="channel names separated by commas, in the order stored in the images (C0, C1, " + "...), for example COL,FN; give it only when all acquisitions have the same channels " + "in the same order", + ) + describe.add_argument( + "--image-type", + choices=("channels", "rgb"), + help="channels: separate stains or markers, such as fluorescence; rgb: red, green " + "and blue colour images (use --channels R,G,B). Never inferred", + ) + describe.add_argument( + "--accept-ids", + action="store_true", + help="accept the proposed identifiers of conditions and repeats; review them with " + "describe first, and give --id for folders without a valid proposed ID", + ) + describe.add_argument( + "--id", + action="append", + default=[], + metavar="FOLDER=ID", + help="assign a folder an identifier without renaming it, for example " + "--id control=ctrl (repeatable). If a name occurs at more than one folder level, " + "write condition:NAME=ID, repeat:NAME=ID or technical:NAME=ID", + ) + describe.add_argument( + "--comparable", + action="store_true", + help="confirm that the samples of each biological repeat were prepared and acquired " + "under comparable conditions; give this option only if that statement is true", + ) + describe.add_argument( + "--confirmed-on", + metavar="YYYY-MM-DD", + help="the date on which you confirm the description, written YYYY-MM-DD", + ) + describe.add_argument( + "--rgb-header-override", + action="append", + nargs="?", + const=True, + default=[], + metavar="FOLDER", + help="with --image-type rgb: use only for images known to store red, green and " + "blue as three interleaved samples per pixel although their TIFF headers do not say " + "RGB. Without a folder, applies to all acquisitions; otherwise give an acquisition " + "folder relative to the experiment, for example CTRL/rep1 (repeatable). Place the " + "experiment folder before this option. An image that is not three interleaved " + "samples is still refused", + ) diff --git a/src/morphobricks_preprocessing/cli_masks.py b/src/morphobricks_preprocessing/cli_masks.py index ccfcb7b7..43608b88 100644 --- a/src/morphobricks_preprocessing/cli_masks.py +++ b/src/morphobricks_preprocessing/cli_masks.py @@ -21,14 +21,15 @@ from .mask_scan import DEFAULT_THRESHOLDS, mask_thresholds from .mask_text import mask_report_summary, mask_summary from .report import format_issues -from .run.mask_step import describe_masks, prepare_mask_step +from .run.mask_step import MaskStepResult, describe_masks, prepare_mask_step from .validation import has_errors THRESHOLD_HELP = { "inside_pixel_share": "share of a child's pixels in one parent for it to be inside", "inside_object_share": "share of the children inside for a mask to be inside another", "parent_larger_share": "share of the inside children whose parent is larger", - "same_objects_iou": "intersection over union for two objects to match one to one", + "same_objects_iou": "minimum overlap of two objects, divided by their combined area, for " + "them to count as a match", "same_objects_share": "share of the objects of both masks matched for the same objects", "grouped_label_share": "share of a grouped mask's pixels carrying the parent's label", "grouped_median_pieces": "median pieces per label above which a mask is grouped", @@ -56,7 +57,9 @@ def add_masks_arguments(masks: argparse.ArgumentParser) -> None: "each mask whole twice more; default: as in the earlier run, else no)", ) limits = masks.add_argument_group( - "relationship thresholds", "change the defaults (contract §15.1); shares are 0 to 1" + "relationship thresholds", + "optional thresholds for identifying mask relationships; fractions range from 0 to 1 " + "(0.8 means 80 percent)", ) for name, text in THRESHOLD_HELP.items(): limits.add_argument( @@ -96,7 +99,10 @@ def masks_command(args: argparse.Namespace) -> int: if has_errors(step.issues): return 1 if not step.masks.types: - print("Give the masks folder with --masks, or use OME-Zarr images with label images.") + print( + "No masks were found. If you have external masks, give their folder with --masks. " + "If you do not intend to analyse masks, skip this command." + ) return 1 def progress(done: int, total: int, path: str) -> None: @@ -118,11 +124,26 @@ def progress(done: int, total: int, path: str) -> None: if result.report is None: # the description is gone or unreadable: nothing read (#418) print(format_issues(result.issues)) return 1 + return _report(result) + + +def _report(result: MaskStepResult) -> int: + """Print the mask report, its issues and the closing line; return the exit status.""" print() print(mask_report_summary(result.report)) - print() - print(f"Report written to {result.path}") if result.issues: print() print(format_issues(result.issues)) - return 1 if has_errors(result.issues) else 0 + print() + if has_errors(result.issues): + print( + f"Mask check failed. A report was saved to {result.path}, but some masks did not " + "pass validation. Correct the errors above and repeat the mask check before using " + "those masks." + ) + return 1 + print( + f"Mask check completed. Relationships saved to {result.path}. The checked masks can " + "now be used in the next MorphoBricks analysis." + ) + return 0 diff --git a/src/morphobricks_preprocessing/cli_run.py b/src/morphobricks_preprocessing/cli_run.py index 4292e5f6..eaa65577 100644 --- a/src/morphobricks_preprocessing/cli_run.py +++ b/src/morphobricks_preprocessing/cli_run.py @@ -9,28 +9,28 @@ uses the recorded experiment folder (``experiment_not_recorded`` without one). ``--lab-links FILE`` gives lab-tool links, recorded in the run manifest only (never taken over by a later run), and ``--confirm-repeat-codes`` confirms their repeat codes (:mod:`.lab_links`). -Also the helpers every command shares: :func:`parse_size` and :func:`command_preflight`. +Also the helper every command shares, :func:`command_preflight`; :func:`parse_size` is in +:mod:`.cli_run_options` (re-exported here). """ from __future__ import annotations import argparse -import re +import shlex from dataclasses import replace -from fractions import Fraction from pathlib import Path from typing import Literal from morphobricks_normalization.checks import IntensityCheckSettings from morphobricks_normalization.ranges import ( - DEFAULT_ROBUST_QUANTILES, - HISTOGRAM_RANGES, HistogramSettings, ) from .axes import AxisMapping, reference_axes from .axis_review import review_axes from .channel_identity import channel_identity_text +from .cli_run_options import INTENSITY_HELP, add_run_settings +from .cli_run_options import parse_size as parse_size from .discovery import default_output_folder from .image_type import IMAGE_TYPES, RGB, ImageTypeReview, review_image_type from .intensity import intensity_text @@ -38,7 +38,6 @@ from .lab_links_file import read_lab_links from .manifest import RunManifest from .metadata import header_axes -from .planes import DEFAULT_MEMORY_LIMIT from .report import ( axis_check_summary, format_issues, @@ -47,64 +46,11 @@ ) 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 -_UNITS = { - "": 1, - "B": 1, - "KIB": 2**10, - "MIB": 2**20, - "GIB": 2**30, - "KB": 10**3, - "MB": 10**6, - "GB": 10**9, -} - - -def parse_size(text: str) -> int: - """Parse a memory size such as ``"1GiB"``, ``"1.5 GiB"`` or ``"1073741824"``. - - The size must be an exact whole number of bytes above 0, computed without rounding - (``"1.5GiB"`` is 1610612736 bytes; ``"1.5"`` and ``"0.5B"`` are refused, issue #80). - ``argparse`` calls it while reading the command line, so a refused size stops the - command before anything is read. - - Raises - ------ - argparse.ArgumentTypeError - If the text is not a whole positive number of bytes. - """ - match = re.fullmatch(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([A-Za-z]*)\s*", text, flags=re.ASCII) - unit = match.group(2).upper() if match else None - if not match or unit not in _UNITS: - raise argparse.ArgumentTypeError( - f"{text!r} is not a memory size; use for example 1GiB, 512MiB or a number of bytes." - ) - size = Fraction(match.group(1)) * _UNITS[unit] - if size.denominator != 1 or size <= 0: - raise argparse.ArgumentTypeError( - f"{text!r} is not a whole number of bytes above 0; use for example 1GiB, 512MiB " - "or a whole number of bytes." - ) - return int(size) - - -def parse_workers(text: str) -> int | str: - """Parse ``--workers``: a whole number of at least 1, or ``auto`` (issue #107). - - Raises - ------ - argparse.ArgumentTypeError - For any other text. - """ - if text == "auto": - return text - if not re.fullmatch(r"[0-9]+", text, flags=re.ASCII) or int(text) < 1: - raise argparse.ArgumentTypeError(f"{text!r} is not a whole number of at least 1 or auto.") - return int(text) - def command_preflight(args: argparse.Namespace) -> Preflight: """Run :func:`preflight` with the options every command shares.""" @@ -161,8 +107,9 @@ def add_missing_as_singleton(parser: argparse.ArgumentParser) -> None: parser.add_argument( "--missing-as-singleton", action=argparse.BooleanOptionalAction, - help="confirm that images lacking some axes have one plane along them (default: as " - "in the earlier run, else no)", + help="confirm that an image without a particular dimension has size 1 along it " + "(default: as in the earlier run, else no). This does not enable analysis of " + "multi-slice Z-stacks", ) @@ -238,7 +185,7 @@ def add_run_arguments(run: argparse.ArgumentParser) -> None: The ``run`` command's parser. """ _run_inputs(run) - _run_settings(run) + add_run_settings(run) run.add_argument("--log", metavar="FILE", help="write technical details to this file") @@ -247,20 +194,24 @@ def _run_inputs(run: argparse.ArgumentParser) -> None: run.add_argument( "--axes", metavar="ROLES", - help="role of each axis of the images, in the order of their axes: X, Y, Z, C, T, or " - "- for none (for example ZCYX). 'check' prints the suggested value. Needed for the " - "first run unless every image names its axes, and again for plain stacks that are " - "new or changed", + help="roles of the stored dimensions, in their stored order: Y and X are image height " + "and width, C is channel, Z is depth, T is time, - an unused length-1 dimension (for " + "example CYX). 'check' prints the suggested value. Needed for the first run unless " + "every image names its axes, and again for plain stacks that are new or changed", ) run.add_argument( "--image-type", choices=IMAGE_TYPES, - help="fluorescence (each channel a separate stain) or rgb (colour images with " - "three channels); default: the earlier run's, else the type suggested from the " - "image headers, printed", + help="fluorescence (each channel a separate stain; the description calls it " + "channels) or rgb (colour images with three channels); default: the earlier run's, " + "else the type suggested from the image headers. The published description is the " + "record of what your channels are: correct it there, not with this option", ) run.add_argument( - "--no-masks", action="store_true", help="drop the masks folder of the earlier run" + "--no-masks", + action="store_true", + help="stop using the previously recorded external masks folder (does not delete mask " + "files)", ) run.add_argument( "--no-exclude", @@ -292,77 +243,11 @@ def _run_inputs(run: argparse.ArgumentParser) -> None: run.add_argument( "--verify-content", action=argparse.BooleanOptionalAction, - help="reuse rows only when each image's content SHA-256 is the one recorded with them, " - "not only its size and modification time (reads every image once more; changing it " - "recomputes every row; on by default: as in the earlier run, else yes; " - "--no-verify-content opts out and the manifest records that)", - ) - - -def _run_settings(run: argparse.ArgumentParser) -> None: - """Add the settings of ``run``; each one left out is the earlier run's, else the default.""" - run.add_argument("--bins", type=int, help="bins per plane (default: depends on pixel type)") - run.add_argument( - "--histogram-range", - choices=HISTOGRAM_RANGES, - help="range of histograms that are not exact (float images, and integer images with " - "more values than bins): minmax (default, each plane's minimum to maximum) or robust " - "(between the --robust-quantiles, the pixels outside counted separately); 8- and " - "16-bit histograms are the same either way", - ) - run.add_argument( - "--robust-quantiles", - type=float, - nargs=2, - metavar=("LOW", "HIGH"), - help="quantiles in percent of the robust range, also used by the range check " - f"(default {DEFAULT_ROBUST_QUANTILES[0]:g} {DEFAULT_ROBUST_QUANTILES[1]:g})", - ) - run.add_argument( - "--memory-limit", - type=parse_size, - default=DEFAULT_MEMORY_LIMIT, - metavar="SIZE", - help="working-memory limit per plane, e.g. 2GiB (default: 1GiB)", - ) - run.add_argument( - "--workers", - type=parse_workers, - default=1, - metavar="N|auto", - help="images read at once, each in its own thread (default 1: one after another); " - "auto: at most the CPUs and, with --max-ram, what the largest image's estimate fits. " - "The outputs are the same with any value", + help="verify that each image's contents are unchanged before reusing its histogram " + "(on by default for a new run; as in the earlier run otherwise). This reads the image " + "files again but avoids recomputing unchanged histograms; changing it recomputes " + "every row. --no-verify-content opts out, and the run manifest records that", ) - run.add_argument( - "--max-ram", - type=parse_size, - metavar="SIZE", - help="with --workers auto: memory the run may use, e.g. 8GiB (an image that does not " - "fit stops the run before any pixel is read)", - ) - checks = run.add_argument_group( - "intensity checks", "limits of the warnings printed after the run; the defaults suit most" - ) - for name, (kind, metavar, text) in _INTENSITY_HELP.items(): - checks.add_argument( - "--" + name.replace("_", "-"), dest=name, type=kind, metavar=metavar, help=text - ) - - -_INTENSITY_HELP = { - "outlier_limit": ( - float, - "N", - "robust deviations beyond which an image or biological repeat is reported (default 3)", - ), - "saturation_limit": ( - float, - "FRACTION", - "fraction of saturated pixels above which an image is reported (default 0.01, 1 %%)", - ), - "min_images": (int, "N", "fewest images a comparison needs (default 5)"), -} def run_command(args: argparse.Namespace) -> int: @@ -416,9 +301,34 @@ def run_command(args: argparse.Namespace) -> int: print(intensity_text(result.intensity)) if result.channel_identity is not None: print(f"\n{channel_identity_text(result.channel_identity)}") + if result.written: + print(f"\n{completed_text(result.output_folder)}") return 0 if result.written else 1 +def completed_text(output: Path) -> str: + """Return the hand-off of a run that wrote its outputs (review 7.1): which folder to give on. + + Parameters + ---------- + output + The run's output folder. + + Returns + ------- + str + """ + folder = shlex.quote(str(output)) + return "\n".join( + [ + f"Preprocessing completed. Review the warnings above. Use {output} as the input " + "folder for your next MorphoBricks analysis.", + "If your analysis uses masks, check their pixel values and relationships first:", + f" morphobricks-preprocessing masks --output {folder}", + ] + ) + + def lab_links_option(args: argparse.Namespace) -> LabLinks | None | Literal[False]: """Return the links of ``--lab-links``, None without it, or False after printing a refusal. @@ -529,7 +439,7 @@ def _settings_options( Each is None when none of its options is given (the run then uses the recorded one); None as a whole when a value is refused, which is printed. """ - intensity = {k: getattr(args, k) for k in _INTENSITY_HELP if getattr(args, k) is not None} + intensity = {k: getattr(args, k) for k in INTENSITY_HELP if getattr(args, k) is not None} histogram = { k: v for k, v in ( @@ -571,7 +481,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 +490,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/cli_run_options.py b/src/morphobricks_preprocessing/cli_run_options.py new file mode 100644 index 00000000..6dad77b7 --- /dev/null +++ b/src/morphobricks_preprocessing/cli_run_options.py @@ -0,0 +1,149 @@ +"""The ``run`` command's settings options and the size parsers the commands share. + +Moved from :mod:`.cli_run` to keep that module within the line limit: :func:`parse_size` +(memory sizes such as ``1GiB``), :func:`parse_workers` (``--workers``) and +:func:`add_run_settings` (the histogram, memory, worker and intensity-check options of ``run``). +""" + +from __future__ import annotations + +import argparse +import re +from fractions import Fraction + +from morphobricks_normalization.ranges import DEFAULT_ROBUST_QUANTILES, HISTOGRAM_RANGES + +from .planes import DEFAULT_MEMORY_LIMIT + +__all__ = ["INTENSITY_HELP", "add_run_settings", "parse_size", "parse_workers"] + +_UNITS = { + "": 1, + "B": 1, + "KIB": 2**10, + "MIB": 2**20, + "GIB": 2**30, + "KB": 10**3, + "MB": 10**6, + "GB": 10**9, +} + + +def parse_size(text: str) -> int: + """Parse a memory size such as ``"1GiB"``, ``"1.5 GiB"`` or ``"1073741824"``. + + The size must be an exact whole number of bytes above 0, computed without rounding + (``"1.5GiB"`` is 1610612736 bytes; ``"1.5"`` and ``"0.5B"`` are refused, issue #80). + ``argparse`` calls it while reading the command line, so a refused size stops the + command before anything is read. + + Raises + ------ + argparse.ArgumentTypeError + If the text is not a whole positive number of bytes. + """ + match = re.fullmatch(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([A-Za-z]*)\s*", text, flags=re.ASCII) + unit = match.group(2).upper() if match else None + if not match or unit not in _UNITS: + raise argparse.ArgumentTypeError( + f"{text!r} is not a memory size; use for example 1GiB, 512MiB or a number of bytes." + ) + size = Fraction(match.group(1)) * _UNITS[unit] + if size.denominator != 1 or size <= 0: + raise argparse.ArgumentTypeError( + f"{text!r} is not a whole number of bytes above 0; use for example 1GiB, 512MiB " + "or a whole number of bytes." + ) + return int(size) + + +def parse_workers(text: str) -> int | str: + """Parse ``--workers``: a whole number of at least 1, or ``auto`` (issue #107). + + Raises + ------ + argparse.ArgumentTypeError + For any other text. + """ + if text == "auto": + return text + if not re.fullmatch(r"[0-9]+", text, flags=re.ASCII) or int(text) < 1: + raise argparse.ArgumentTypeError(f"{text!r} is not a whole number of at least 1 or auto.") + return int(text) + + +def add_run_settings(run: argparse.ArgumentParser) -> None: + """Add the settings of ``run``; each one left out is the earlier run's, else the default. + + Parameters + ---------- + run + The ``run`` command's parser. + """ + run.add_argument( + "--bins", + type=int, + help="number of intensity-histogram bins for each channel of an image plane (default: " + "depends on the pixel type)", + ) + run.add_argument( + "--histogram-range", + choices=HISTOGRAM_RANGES, + help="range of histograms that are not exact (float images, and integer images with " + "more values than bins): minmax (default, each plane's minimum to maximum) or robust " + "(between the --robust-quantiles, the pixels outside counted separately); 8- and " + "16-bit histograms are the same either way", + ) + run.add_argument( + "--robust-quantiles", + type=float, + nargs=2, + metavar=("LOW", "HIGH"), + help="quantiles in percent of the robust range, also used by the range check " + f"(default {DEFAULT_ROBUST_QUANTILES[0]:g} {DEFAULT_ROBUST_QUANTILES[1]:g})", + ) + run.add_argument( + "--memory-limit", + type=parse_size, + default=DEFAULT_MEMORY_LIMIT, + metavar="SIZE", + help="working-memory limit per plane, e.g. 2GiB (default: 1GiB)", + ) + run.add_argument( + "--workers", + type=parse_workers, + default=1, + metavar="N|auto", + help="number of images processed in parallel (default 1: one after another); with " + "auto, chosen from the available CPUs and, with --max-ram, memory. Does not change " + "the scientific results", + ) + run.add_argument( + "--max-ram", + type=parse_size, + metavar="SIZE", + help="total memory budget, used only with --workers auto, for example --workers auto " + "--max-ram 8GiB (an image that does not fit stops the run before any pixel is read)", + ) + checks = run.add_argument_group( + "intensity checks", "limits of the warnings printed after the run; the defaults suit most" + ) + for name, (kind, metavar, text) in INTENSITY_HELP.items(): + checks.add_argument( + "--" + name.replace("_", "-"), dest=name, type=kind, metavar=metavar, help=text + ) + + +INTENSITY_HELP = { + "outlier_limit": ( + float, + "N", + "robust deviations beyond which an image or biological repeat is reported (default 3)", + ), + "saturation_limit": ( + float, + "FRACTION", + "fraction of saturated pixels above which an image is reported (default 0.01, 1 %%)", + ), + "min_images": (int, "N", "fewest images a comparison needs (default 5)"), +} diff --git a/src/morphobricks_preprocessing/cli_tissue_mask.py b/src/morphobricks_preprocessing/cli_tissue_mask.py index dfc86b1a..1e471c5c 100644 --- a/src/morphobricks_preprocessing/cli_tissue_mask.py +++ b/src/morphobricks_preprocessing/cli_tissue_mask.py @@ -1,31 +1,36 @@ """The command line's ``tissue-mask``: the opt-in H&E tissue mask helper (Spec ADR 0005 BM15). -``tissue-mask --output FOLDER --to NEW_ID`` writes, for every image of the run in ``--output`` -whose unit is declared ``rgb`` (or only the ``--image`` paths given, repeatable), its H&E tissue -mask as the new ``binary`` region mask ``NEW_ID`` (``RunInputs.he_tissue_mask``, rule -``he_tissue_v1``, provisional): nuclei, red blood cells and empty space left out, sizes in -pixels. The outputs go to the run's masks folder, each with its line of ``mask_lineage.jsonl``; -the image is never changed and nothing is overwritten. A same call again is a no-op, unless a -code identity is unverified: such a mask is written but never reused, so a retry is refused. -The command prints what it wrote, the kept share, and the next steps (declare the mask -``binary``, run preprocessing and the masks step again, use it as a region). It stops at the -first refusal (exit status 1), naming it; the images written before it stay written. Without -scikit-image it names the extra to install and writes nothing (exit status 1). +``tissue-mask --output FOLDER --to NEW_ID`` writes, for every image of the run in ``--output`` whose +unit is declared ``rgb`` (or only the ``--image`` paths given, repeatable), its H&E tissue mask as +the new ``binary`` region mask ``NEW_ID`` (``RunInputs.he_tissue_mask``, rule ``he_tissue_v2`` by +default, provisional): nuclei, red blood cells and empty space left out, sizes in pixels. The +outputs go to the run's masks folder, each with its line of ``mask_lineage.jsonl``; the image is +never changed and nothing is overwritten. A same call again is a no-op, unless a code identity is +unverified: such a mask is written but never reused, so a retry is refused. The command prints what +it wrote, the kept share, and the next steps (declare the mask ``binary``, run preprocessing and the +masks step again, use it as a region: ``region_mask`` in the next brick's settings). A run with +no masks folder gets one first (``_masks`` beside the experiment, or ``--masks +FOLDER``), recorded as ``run --masks`` records it (:mod:`.tissue_masks_folder`), said in one +line. It stops at the first refusal (exit status 1), naming it; the +images written before it stay written. Without scikit-image it names the extra to install and writes +nothing (exit status 1). """ from __future__ import annotations import argparse +import shlex from .plane_errors import PlaneReadError from .run_inputs import RunInputs from .run_inputs_tissue import ( - HE_TISSUE_V1, + HE_TISSUE_V2, NOT_REUSED, - PROVISIONAL_NOTE, + provisional_note, rgb_positions, tissue_next_steps, ) +from .tissue_masks_folder import MasksFolderRefused, create_masks_folder from .validation import plural @@ -44,30 +49,58 @@ def add_tissue_mask_parser(commands: argparse._SubParsersAction) -> argparse.Arg """ tissue = commands.add_parser( "tissue-mask", - help="write an H&E tissue mask (nuclei, red blood cells and empty space left out) of " - "each RGB image as a new binary region mask (needs the he-mask extra)", + help="create a binary H&E tissue mask for each 8-bit RGB image of a preprocessing run " + "(provisional rule; needs the he-mask extra)", + description="""\ +Create a binary region mask for each selected 8-bit RGB H&E image in a +completed preprocessing run. A provisional fixed rule attempts to exclude +nuclei, red blood cells and empty background. Inspect the masks before you use +them. + +Requires: + 8-bit RGB images (three colour channels), one depth plane and one time point + the he-mask installation extra""", + epilog="""\ +Example: + morphobricks-preprocessing tissue-mask \\ + --output he_MorphoBricks_Preprocessing --to HETissue + +Inspect the generated masks, then declare them as binary. The command prints +the next commands to run.""", + formatter_class=argparse.RawDescriptionHelpFormatter, ) tissue.add_argument( - "--output", metavar="FOLDER", required=True, help="the output folder of the run" + "--output", + metavar="FOLDER", + required=True, + help="the preprocessing output folder containing morphobricks.toml", ) tissue.add_argument( "--to", metavar="NEW_ID", required=True, - help="the new mask ID; declare it binary afterwards", + help="new, unused mask identifier, for example HETissue; declare it as binary after " + "checking the generated masks", ) tissue.add_argument( "--image", action="append", default=[], metavar="PATH", - help="only this image, relative to the experiment folder (repeatable; default: every " - "image of a unit declared rgb)", + help="create masks only for this image, relative to the experiment folder " + "(repeatable). By default, every RGB image; other images do not receive this mask", + ) + tissue.add_argument( + "--masks", + metavar="FOLDER", + help="only when the run has no masks folder: the new, empty masks folder to create " + "and record (default: _masks beside the experiment folder)", ) tissue.add_argument( "--rule", - default=HE_TISSUE_V1, - help=f"the fixed rule (default and only rule: {HE_TISSUE_V1}, provisional)", + default=HE_TISSUE_V2, + help=f"the fixed rule (default {HE_TISSUE_V2}, the white estimated from each image; or " + "he_tissue_v1, the white fixed at 255; both provisional)", ) return tissue @@ -81,26 +114,98 @@ def tissue_mask_command(args: argparse.Namespace) -> int: return 1 images = tuple(args.image) or rgb_positions(run) if not images: - print("The run has no image of a unit declared rgb; nothing was written.") + print( + "No images in this preprocessing run are declared RGB; tissue-mask requires RGB " + "H&E images. Nothing was written." + ) + return 1 + if args.masks and run.masks_root is not None: + print( + f"--masks creates a masks folder for a run without one; this run records " + f"{run.masks_root}, where the tissue masks go. Nothing was written." + ) return 1 - print(PROVISIONAL_NOTE) + 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 + created = run.masks_root is None + if created: + try: + run = create_masks_folder(run, args.masks).run + except MasksFolderRefused as exc: + print(f"No tissue mask written. {exc}") + return 1 + print( + f"Masks folder created and registered: {run.masks_root}. The preprocessing run " + "now records this folder." + ) + print(provisional_note(args.rule)) written = [] for image in images: try: result = run.he_tissue_mask(image, output_mask_id=args.to, rule=args.rule) # Every refusal: RunInputsError, a missing extra, and a plane that cannot be read (#469). except (ValueError, ImportError, PlaneReadError, OSError) as exc: - print(f"{image}: no tissue mask written. {exc}") + print(_refusal(image, exc)) + if created: + print(f"The registered masks folder {run.masks_root} remains in place.") if written: - print(f"{plural(len(written), 'image')} before it stay written.") + print( + f"The masks of {plural(len(written), 'earlier image')} remain available. " + "Complete the required masks before declaring this mask type." + ) return 1 written.append(result) - state = "written" if result.published else "already written" + state = "saved" if result.published else "already saved" kept = 100 * result.fractions["kept"] - line = f"{image}: {result.path} ({state}), kept {kept:.1f} %" + line = f"{image}: mask {state} to {result.path}; retained area: {kept:.1f} % of the image" if kept == 0: - line += " (nothing kept: an empty region)" + line += " (empty region: no tissue pixels retained; inspect this image)" print(line if result.reusable else f"{line}; {NOT_REUSED}") print() - print(tissue_next_steps((r.mask_id for r in written), run.masks_root)) + ids = sorted({r.mask_id for r in written}) + print(tissue_next_steps(ids, run.masks_root, _commands(args.output, ids, run.masks_root))) return 0 + + +def _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`. That module is imported here, not at the top, so a + core-only install loads none of the H&E code until the command runs. + """ + from .he_tissue_mask import current_rule, resolved_fov # noqa: PLC0415 + + try: + current_rule(rule) + except (TypeError, ValueError, ImportError) as exc: + 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}: ") + if image in text: + return f"No tissue mask written. {text}" + return f"{image}: no tissue mask written. {text}" + + +def _commands(output: str, ids: list[str], masks_root: object) -> list[str]: + """Return the commands that declare the masks binary and check them (run, then masks).""" + types = " ".join(f"--type {shlex.quote(i)}=binary" for i in ids) + target = f"--output {shlex.quote(output)}" + return [ + f"morphobricks-preprocessing declare-masks {target} {types} " + f"--masks {shlex.quote(str(masks_root))}", + f"morphobricks-preprocessing run {target}", + f"morphobricks-preprocessing masks {target}", + ] diff --git a/src/morphobricks_preprocessing/conversion_issues.py b/src/morphobricks_preprocessing/conversion_issues.py index 8146bf48..9eabd268 100644 --- a/src/morphobricks_preprocessing/conversion_issues.py +++ b/src/morphobricks_preprocessing/conversion_issues.py @@ -87,25 +87,18 @@ def work_folder_issue(dest: Path, name: str, all_nul: bool = False) -> Validatio """ if all_nul: cause = ( - "Its owner file is unreadable: it holds only NUL bytes, possibly left by a power " - "loss while a conversion wrote it, so it cannot be proven that a conversion made " - "this folder." + "'s ownership record is unreadable (it holds only NUL bytes, possibly left by a " + "power loss)" ) else: - cause = ( - "So it was not made by a conversion, or was changed since, and it cannot be " - "proven that a conversion made it." - ) + cause = " has an invalid or missing ownership record, or contains unexpected files" return error( "conversion_work_folder_unowned", - f"The folder for the named-axis copies holds {name}, the name of the folder a " - "conversion writes its copies in, but not as a conversion leaves it: the owner file a " - "conversion writes into it first is missing or not well formed, or it holds something " - f"else than that file and the folder 'files'. {cause} Nothing was removed and " - "nothing was written.", + f"The temporary conversion folder {dest / name}{cause}. The folder has not been " + "removed: it has been left untouched. Nothing was removed and nothing was written.", [name], - f"Check {dest / name}, then move or remove it yourself if you no longer need what it " - "holds, or choose a new, empty folder for the copies.", + "Use a new, empty folder for the copies (--to), or inspect the temporary folder before " + "moving it.", ) @@ -117,13 +110,12 @@ def work_folder_in_use_issue(dest: Path, name: str, holder: LockHolder) -> Valid """ return error( "conversion_work_folder_in_use", - f"The folder for the named-axis copies holds {name}, the work folder of a " - f"conversion by {holder.describe()}, which is still running on this computer, so it " - "may still be writing there (its lock was probably removed by mistake). Nothing was " - "removed and nothing was written.", + "A process associated with an earlier conversion is still running on this computer " + f"({holder.describe()}). The temporary folder {dest / name} has been left untouched. " + "Nothing was removed and nothing was written.", [name], - "Wait for that conversion to finish, then convert again. If that process is not a " - f"conversion (process IDs are reused), move or remove {dest / name} yourself.", + "Wait for the conversion to finish, or use another destination. If that process is not " + "a conversion (process IDs are reused), inspect the temporary folder before moving it.", ) @@ -131,13 +123,11 @@ def work_folder_not_removed_issue(dest: Path, name: str, exc: OSError) -> Valida """Refuse a conversion whose leftover work folder ``name`` cannot be removed (#488).""" return error( "conversion_work_folder_not_removed", - f"The folder for the named-axis copies holds {name}, the work folder of a conversion " - f"that was stopped, and it cannot be removed ({exc}): a file in it may be open in " - "another program, such as an antivirus or a sync client (OneDrive, Dropbox). Part of " - "it may have been removed. Nothing was written.", + f"The temporary conversion folder {dest / name}, left by a stopped conversion, could " + f"not be removed: {exc}. Part of it may have been removed; nothing was written.", [name], - "Close the programs that may use it, or wait for them to finish, then convert again " - f"(the conversion removes it). Or remove {dest / name} yourself.", + f"Close programs using {dest / name} (such as an antivirus or a sync client like " + "OneDrive) and retry, or choose another empty destination.", ) @@ -154,13 +144,12 @@ def path_too_long_issue( ) return error( "copy_path_too_long", - f"{plural(len(paths), 'copy', 'copies')} would have {what} while it is written in the " - f"conversion's work folder in {dest}, and Windows cannot handle such paths without " - "long paths enabled. Nothing was written.", + f"The converted files would exceed Windows' path-length limit: " + f"{plural(len(paths), 'copy', 'copies')} would have {what} in the conversion's work " + f"folder in {dest}. Nothing was written.", paths, - "Choose a folder for the copies with a shorter path (for example near the top of the " - "drive), or shorten the names of these images or of their folders, or ask your " - "administrator to enable Windows' long paths (LongPathsEnabled).", + "Choose a destination with a shorter path, shorten the named folders or ask your " + "administrator to enable long paths.", ) @@ -316,3 +305,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/src/morphobricks_preprocessing/describe_ids.py b/src/morphobricks_preprocessing/describe_ids.py new file mode 100644 index 00000000..f34fc1dd --- /dev/null +++ b/src/morphobricks_preprocessing/describe_ids.py @@ -0,0 +1,171 @@ +"""The IDs ``describe --id FOLDER=ID`` names on the command line (owner, 4 December 2026; pure). + +A condition, biological-repeat or technical-repeat folder whose label cannot be an ID +(``control`` and ``files`` are forbidden names, ``E_FORBIDDEN_FIELD``; experiment-v1 4.7) has +no proposal (:mod:`.draft_ids`): the user names its ID. In the notebook that is a text field; +on the command line it is ``--id control=ctrl`` (repeatable). Each ID is the user's, adopted +exactly as typed and checked with the notebook's own rules (:meth:`.draft.Draft.confirm_id`), +so the command line accepts what the notebook accepts and refuses what it refuses. + +``FOLDER`` is the folder label as the draft lists it. A label that names folders of two +levels (a condition and a technical repeat both called ``a``) needs the level: +``--id condition:a=A``, ``--id repeat:a=A`` or ``--id technical:a=A``. +""" + +from __future__ import annotations + +import shlex +import unicodedata +from collections.abc import Collection, Iterable, Sequence + +from .description_rules import Code, Refusal +from .draft import Draft, DraftError +from .draft_ids import IdKind, id_problems + +LEVELS: dict[str, IdKind] = { + "condition": "conditions", + "repeat": "repeats", + "technical": "technical_repeats", +} +"""The level prefixes of ``--id`` and the draft table each names.""" +NOUNS: dict[IdKind, str] = { + "conditions": "condition folder", + "repeats": "biological repeat", + "technical_repeats": "technical repeat folder", +} + + +_RESERVED = "This name is reserved. Choose another identifier." +_USED = "This identifier has already been used for another entry. Choose an unused identifier." +REASONS: dict[str, str] = { + Code.E_FORBIDDEN_FIELD: _RESERVED, + Code.E_ID_RESERVED: _RESERVED, + Code.E_ID_SYNTAX: ( + "This identifier contains characters that are not permitted. Choose a valid identifier." + ), + Code.E_ID_TEXT: ( + "This identifier is empty, starts or ends with a space, or reads as a missing value " + "(such as NA or none). Choose a valid identifier." + ), + Code.E_ID_NOT_NFC: ( + "This identifier contains accented characters in a form that is not permitted (not " + "Unicode NFC). Type it again, or choose another identifier." + ), + Code.E_SINGLE_MISUSE: ( + "'single' is kept, in lower case, for a level without its own folder. Choose another " + "identifier." + ), + Code.E_ID_CASE_COLLISION: ( + "This identifier differs from another identifier only in upper/lower case. Choose a " + "distinct identifier." + ), + Refusal.R_USED_ID_REUSED: _USED, + "id_in_use_in_draft": _USED, + "in_use": _USED, +} +"""Why an ID is refused, in words, by the code the ID rules give (``id_problems``, the draft).""" + + +def reasons(codes: Iterable[str]) -> str: + """Say why an ID is refused, each reason once, then the codes in brackets.""" + codes = tuple(dict.fromkeys(codes)) or ("in_use",) + said = dict.fromkeys(REASONS.get(code, "This identifier is not permitted.") for code in codes) + shown = ", ".join(code for code in codes if code != "in_use") + text = " ".join(said) + return f"{text[:-1]} ({shown})." if shown else text + + +def example_id(kind: IdKind, folder: str, used: Collection[str] = ()) -> str: + """Return an allowed ID to show for ``folder``: ``ctrl`` for ``control``, else from its name.""" + if folder == "control": + return "ctrl" + base = unicodedata.normalize("NFC", folder.strip()) or "Group" + for candidate in (base, f"{base}_1", f"{base}_2", "Group1"): + if not id_problems(kind, candidate, used): + return candidate + return "Group1" + + +def id_option(folder: str, value: str) -> str: + """Return the ``--id`` option that names ``folder``'s ID, quoted for the shell where needed.""" + return f"--id {shlex.quote(f'{folder}={value}')}" + + +def needs_id(kind: IdKind, folder: str, used: Collection[str] = ()) -> str: + """Say why ``folder`` has no proposed ID and which ``--id`` names one (a concrete example).""" + codes = id_problems(kind, folder, used) + noun, option = NOUNS[kind], id_option(folder, example_id(kind, folder, used)) + if {"E_FORBIDDEN_FIELD", "E_ID_RESERVED"} & set(codes): + why = f" because {folder!r} is reserved ({', '.join(codes)})." + else: + why = f". {reasons(codes)}" + return ( + f"The {noun} {folder!r} needs another identifier{why} Keep the folder name and add " + f"{option} (or type the ID in the notebook)." + ) + + +def _keys(draft: Draft, kind: IdKind) -> Sequence[str]: + """Return the labels of one level of the draft.""" + table = { + "conditions": draft.conditions, + "repeats": draft.repeats, + "technical_repeats": draft.technical_repeats, + }[kind] + return tuple(table) + + +def _locate(draft: Draft, folder: str) -> list[tuple[IdKind, str]]: + """Return the (level, label) entries ``folder`` names: a bare label, or ``level:label``.""" + found = [(kind, folder) for kind in LEVELS.values() if folder in _keys(draft, kind)] + level, sep, label = folder.partition(":") + if not found and sep and level in LEVELS and label in _keys(draft, LEVELS[level]): + found = [(LEVELS[level], label)] + return found + + +def apply_ids(draft: Draft, given: Sequence[str]) -> tuple[Draft, list[str]]: + """Return the draft with every ``--id FOLDER=ID`` confirmed, and every refusal in words. + + A refusal names the option to give again; on any refusal the caller publishes nothing. + """ + refusals: list[str] = [] + seen: dict[tuple[IdKind, str], str] = {} + for item in given: + folder, sep, value = item.rpartition("=") + if not sep or not folder or not value: + refusals.append(f"--id {item}: write it as FOLDER=ID, for example --id control=ctrl") + continue + found = _locate(draft, folder) + if not found: + known = sorted({k for kind in LEVELS.values() for k in _keys(draft, kind)}) + refusals.append( + f"--id {item}: {folder!r} is not a condition, biological-repeat or " + f"technical-repeat folder of this experiment (folders: {', '.join(known)})" + ) + continue + if len(found) > 1: + prefixes = [p for p, kind in LEVELS.items() if (kind, folder) in found] + levels = " or ".join(id_option(f"{p}:{folder}", value) for p in prefixes) + refusals.append( + f"--id {item}: the name {folder!r} occurs at more than one folder level. " + f"Specify which level you mean: {levels}." + ) + continue + key = found[0] + if key in seen: + refusals.append(f"--id {item}: {folder!r} is named twice; give one ID") + continue + seen[key] = value + try: + draft = draft.confirm_id(key[0], key[1], value) + except DraftError as exc: + example = example_id(key[0], key[1], draft.used_ids.get(key[0], ())) + refusals.append( + f"--id {item}: {value!r} cannot be the ID of {NOUNS[key[0]]} {key[1]!r}. " + f"{reasons(exc.codes)} For example: {id_option(folder, example)}" + ) + return draft, refusals + + +__all__ = ["LEVELS", "REASONS", "apply_ids", "example_id", "id_option", "needs_id", "reasons"] diff --git a/src/morphobricks_preprocessing/describe_questions.py b/src/morphobricks_preprocessing/describe_questions.py new file mode 100644 index 00000000..dd6e131b --- /dev/null +++ b/src/morphobricks_preprocessing/describe_questions.py @@ -0,0 +1,130 @@ +"""The open questions ``describe`` prints, and which option answers each one (pure). + +Moved from :mod:`.cli_describe` with ``--id`` (owner, 4 December 2026). A question is listed +with only the options that can answer it: ``--accept-ids`` accepts a proposal, so an ID that +cannot be proposed (``control``, ``files``) is answered by ``--id FOLDER=ID`` alone, and the +line never offers ``--accept-ids`` for it. +""" + +from __future__ import annotations + +from .describe_ids import needs_id +from .draft import Draft, OpenQuestion +from .draft_ids import IdKind +from .validation import plural + +QUESTION_TEXT = { + "id_pending": "choose the ID of {subject} (accept the proposal or type another)", + "repeat_not_confirmed": ( + "confirm, only if it is true, that the samples of {subject} were prepared and acquired " + "comparably; otherwise review the experimental grouping in the notebook. Do not confirm " + "an incorrect experimental design" + ), + "confirmed_on_missing": "{subject} is confirmed but has no date: confirm it again", +} +"""What the user must do for each open question of a draft, in plain words.""" + + +def proposal(kind: IdKind, folder: str, proposed: str | None, named: str | None = None) -> str: + """Say what is proposed for a folder, the user's ``--id``, or why nothing is proposed.""" + if named is not None: + return f"ID {named!r} (yours, --id)" + if proposed is not None: + return f"proposed ID {proposed!r}" + return f"no ID proposed. {needs_id(kind, folder)}" + + +def unproposed(draft: Draft) -> dict[str, tuple[IdKind, str]]: + """Return the ID questions with no proposal, by subject: --accept-ids cannot answer them.""" + out: dict[str, tuple[IdKind, str]] = { + f"condition {k}": ("conditions", k) + for k, slot in draft.conditions.items() + if slot.proposed is None + } + out |= { + f"technical repeat {k}": ("technical_repeats", k) + for k, slot in draft.technical_repeats.items() + if slot.proposed is None + } + return out | { + f"repeat {k}": ("repeats", k) for k, rep in draft.repeats.items() if rep.id.proposed is None + } + + +def _text(q: OpenQuestion, named_by: dict[str, tuple[IdKind, str]]) -> str: + """Return one open question in words; an unproposable ID names its ``--id`` option.""" + if q.code == "id_pending" and q.subject in named_by: + return needs_id(*named_by[q.subject]) + return QUESTION_TEXT[q.code].format(subject=q.subject) + + +def fast_question_lines( + draft: Draft, *, accept_ids: bool, comparable: bool, dated: bool, named: bool +) -> list[str]: + """Return the draft's questions the fast-mode options leave open, or say none is left. + + ``--accept-ids`` answers every ID question that has a proposal, ``--comparable`` with a + valid ``--confirmed-on`` (``dated``) every repeat question; ``named`` says ``--id`` was + given. The questions are listed only while some remain, each heading naming only the + options that answer what is left. + """ + named_by = unproposed(draft) + questions = draft.open_questions() + left = [ + q + for q in questions + if not ( + (accept_ids and q.subject not in named_by) + if q.code == "id_pending" + else (comparable and dated) + ) + ] + if not questions: + return ["", "No question is open."] + if not left: + given = ["--accept-ids", "--comparable", "--confirmed-on"] + given = ["--id", *given] if named else given + return [ + "", + f"The draft's {plural(len(questions), 'open question')} are answered by your " + f"options ({', '.join(given)}).", + ] + options = [] + if any(q.code == "id_pending" and q.subject in named_by for q in left): + options.append("--id FOLDER=ID") + if any(q.code == "id_pending" and q.subject not in named_by for q in left): + options.append("--accept-ids") + if any(q.code != "id_pending" for q in left): + options.append("--comparable and --confirmed-on YYYY-MM-DD") + out = [ + "", + f"{plural(len(left), 'open question')} (answer them with {', '.join(options)}, " + "or in the notebook):", + ] + return out + [f" - {_text(q, named_by)}" for q in left] + + +def question_lines(draft: Draft) -> list[str]: + """Return what the user still has to answer, one line each (no fast-mode option given).""" + questions = draft.open_questions() + if not questions: + return ["", "No question is open."] + named_by = unproposed(draft) + out = ["", f"{plural(len(questions), 'open question')} (answered by you, in the notebook):"] + return out + [f" - {_text(q, named_by)}" for q in questions] + + +def question_blockers(draft: Draft) -> list[str]: + """Return the draft's open questions as what stops publication, in plain words.""" + named_by = unproposed(draft) + return [_text(q, named_by) for q in draft.open_questions()] + + +__all__ = [ + "QUESTION_TEXT", + "fast_question_lines", + "proposal", + "question_blockers", + "question_lines", + "unproposed", +] diff --git a/src/morphobricks_preprocessing/description_run_text.py b/src/morphobricks_preprocessing/description_run_text.py index f60555d5..e6ceadf5 100644 --- a/src/morphobricks_preprocessing/description_run_text.py +++ b/src/morphobricks_preprocessing/description_run_text.py @@ -8,7 +8,9 @@ from __future__ import annotations +import shlex from collections.abc import Iterable +from pathlib import PurePath from .channel_plan import channel_coverage, partial_repeats from .description import Description @@ -20,7 +22,6 @@ from .description_report import DescriptionIssue from .description_rules import Code from .fast_layout import FAST_LAYOUT_CONTRADICTION, contradiction_message -from .fast_layout import FIX as FAST_FIX from .physical_check import ( CHANNEL_COUNT_MISMATCH, HEADER_CONTRADICTION, @@ -43,12 +44,49 @@ _ACTIONS = { UNIT_NOT_FOUND: "Remove that acquisition from the description or restore its folder.", UNIT_NOT_DECLARED: "Add the acquisition to the description, or exclude its images.", - MASK_TYPE_NOT_DECLARED: ( - "Declare the mask type in the description (the notebook's describe steps, or " - "morphobricks-preprocessing declare-masks --output FOLDER --type TYPE=instances), or " - "remove its files." - ), } +_DECLARE = ( + "If every object has its own positive label, declare it as instance labels{where}:\n" + " morphobricks-preprocessing declare-masks --output {output} --type {instances}\n" + "To skip this mask type instead:\n" + " morphobricks-preprocessing declare-masks --output {output} --ignore {name}\n" + "For a foreground/background mask, use {binary} instead. For labels grouping several " + "objects, use {parent}. Then run preprocessing again." +) +"""The undeclared mask type's fix: each representation with what it means, none guessed.""" + + +def declare_action(mask_type: str, output_folder: str | PurePath | None = None) -> str: + """Return how to declare or skip an undeclared mask type, its name and folder quoted.""" + where = "" + if output_folder is None: + where, output = " (replacing OUTPUT with your output folder)", "OUTPUT" + else: + output = shlex.quote(str(output_folder)) + return _DECLARE.format( + where=where, + output=output, + instances=shlex.quote(f"{mask_type}=instances"), + name=shlex.quote(mask_type), + binary=shlex.quote(f"{mask_type}=binary"), + parent=shlex.quote(f"{mask_type}=parent_labels"), + ) + + +FAST_ACTION = ( + "Review the channel order in the acquisitions listed above. Tag acquisitions separately in " + 'the notebook where their channel lists differ (channels_from = "unit"), save the ' + "description and run again." +) +"""The fix of ``R_FAST_LAYOUT_CONTRADICTION`` (experiment-v1 section 8 names it: tag those units +on their own, ``channels_from = "unit"``); the message lists every image and its unit once.""" + +OVERRIDE_FIX = ( + "Images that store R, G and B as three interleaved samples under a header that does not " + "say colour need no own tags: declare the RGB header override on their acquisitions " + "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: @@ -69,7 +107,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"The mask type {issue.detail!r} was found but has not been declared. Choose how " + "its pixel values should be interpreted." + ) reasons = { UNIT_NOT_HOMOGENEOUS: "Images of one acquisition differ in their layout", CHANNEL_COUNT_MISMATCH: "An image has another number of channels than described", @@ -84,10 +125,19 @@ def _what(issue: PhysicalIssue) -> str: return f"{reasons[issue.code]} in {where}{image}: {issue.detail}." -def physical_issue(issue: PhysicalIssue) -> ValidationIssue: - """Return one physical check refusal as an error naming its code, unit and image.""" +def physical_issue( + issue: PhysicalIssue, output_folder: str | PurePath | None = None +) -> ValidationIssue: + """Return one physical check refusal as an error naming its code, unit and image. + + ``output_folder``, when known, is named in an undeclared mask type's commands; without it + they say OUTPUT and what to replace it with. + """ paths = () if issue.path is None else (issue.path,) - return error(issue.code, _what(issue), paths, _ACTIONS.get(issue.code, FIX)) + action = _ACTIONS.get(issue.code, FIX) + if issue.code == MASK_TYPE_NOT_DECLARED: # the type found, never a guessed representation + action = declare_action(issue.detail, output_folder) + return error(issue.code, _what(issue), paths, action) def fast_layout_issue(issues: Iterable[PhysicalIssue]) -> ValidationIssue: @@ -95,15 +145,16 @@ def fast_layout_issue(issues: Iterable[PhysicalIssue]) -> ValidationIssue: Every image of every fast unit is listed once, with its FOV key, path and every contradiction found in it (kind, C index, expected and found), and the action names the - one fix: tag those units on their own, then run again. + one fix: tag those acquisitions separately in the notebook, then run again. """ listed = { (fov_text(issue), issue.path): issue.contradictions for issue in issues if issue.code == FAST_LAYOUT_CONTRADICTION } - units = sorted({unit_text(i.unit) for i in issues if i.code == FAST_LAYOUT_CONTRADICTION}) - action = f"{FAST_FIX} Units: " + "; ".join(units) + "." + action = FAST_ACTION + if any(i.override_fits for i in issues if i.code == FAST_LAYOUT_CONTRADICTION): + action += f" {OVERRIDE_FIX}" paths = [path for _, path in listed] return error(FAST_LAYOUT_CONTRADICTION, contradiction_message(listed), paths, action) @@ -114,29 +165,73 @@ def fov_text(issue: PhysicalIssue) -> str: return f"{unit.condition}/{unit.biological_repeat}/{unit.technical_repeat}/{issue.fov}" -def physical_issues(issues: Iterable[PhysicalIssue]) -> list[ValidationIssue]: +def physical_issues( + issues: Iterable[PhysicalIssue], output_folder: str | PurePath | None = None +) -> list[ValidationIssue]: """Return the physical refusals, every fast-mode contradiction as one issue (ADR 0006). One publication or run carries ``R_FAST_LAYOUT_CONTRADICTION`` at most once, with all images, beside every other applicable code (AQ2); the others are one issue each. + ``output_folder`` is as in :func:`physical_issue`. """ issues = list(issues) - out = [physical_issue(i) for i in issues if i.code != FAST_LAYOUT_CONTRADICTION] + out = [physical_issue(i, output_folder) for i in issues if i.code != FAST_LAYOUT_CONTRADICTION] if any(i.code == FAST_LAYOUT_CONTRADICTION for i in issues): out.append(fast_layout_issue(issues)) return out +_MEANINGS = { + Code.E_FILE_ENCODING: "is not saved as UTF-8 text", + Code.E_TOML_SYNTAX: "is not valid TOML text", + Code.E_DUPLICATE_KEY: "names the same entry twice", + Code.E_SCHEMA_ID: "is not an experiment description of this format", + Code.E_SCHEMA_VERSION_MISSING: "does not say which format version it is", + Code.E_SCHEMA_VERSION_UNSUPPORTED: "is of a format version this release does not read", + Code.E_TYPE: "has a value of the wrong kind", + Code.E_UNKNOWN_FIELD: "has a field this release does not know", + Code.E_FORBIDDEN_FIELD: "has a field that is not allowed in it", + Code.E_MISSING_FIELD: "is missing a required field", + Code.E_EMPTY: "has an empty list or table", + Code.E_TEXT_EMPTY: "has an empty text", + Code.E_ENUM: "has a value that is not one of the allowed choices", + Code.E_DATE_FORMAT: "has a date that is not written as YYYY-MM-DD", + Code.E_VALUE_RANGE: "has a number out of its allowed range", + Code.E_REPEAT_UNCONFIRMED: "has a biological repeat that is not confirmed", + Code.E_UNKNOWN_CONDITION: "refers to a condition it does not define", + Code.E_UNKNOWN_CHANNEL: "refers to a channel it does not define", + Code.E_REFERENCE_UNKNOWN: "compares a condition against one it does not define", + Code.E_REFERENCE_SELF: "compares a condition against itself", + Code.E_REFERENCE_CYCLE: "has conditions compared against each other in a circle", +} +"""What a reader code means, in plain words, after "The experiment description".""" + + +def _meaning(code: str) -> str: + """Say in plain words what a reader code means (a family's meaning for the others).""" + if code in _MEANINGS: + return _MEANINGS[code] + kind, _, rest = code.partition("_") # E_ID_SYNTAX: kind E, family ID + family = rest.partition("_")[0] + if kind == "E" and family in {"ID", "SINGLE"}: + return "has an identifier that is not permitted" + if kind == "E" and family == "RGB": + return "has colour (RGB) settings that do not agree" + if kind == "R": + return "differs from what was published before in a way that is not allowed" + return "breaks one of its rules" + + def reader_issue(issue: DescriptionIssue) -> ValidationIssue: - """Return one reader (or file) refusal as an error with its code, table path and value.""" + """Return one reader (or file) refusal: its plain meaning, then its table path and code.""" code = issue.code.value - shown = "" if issue.value is None else f" (value {issue.value!r})" + parts = [f"at {issue.path}"] if issue.path else [] if issue.code is Code.E_TYPE: # the type found, which the code alone does not say - shown = f" (value {issue.value!r}, of type {type_name(issue.value)})" - message = ( - f"The experiment description morphobricks.toml cannot be used: {code} at " - f"{issue.path}{shown}." - ) + parts.append(f"value {issue.value!r} of type {type_name(issue.value)}") + elif issue.value is not None: + parts.append(f"value {issue.value!r}") + shown = ", ".join([*parts, code]) + message = f"The experiment description (morphobricks.toml) {_meaning(code)} ({shown})." return error(code, message, (), FIX) diff --git a/src/morphobricks_preprocessing/entry_errors.py b/src/morphobricks_preprocessing/entry_errors.py index 751dc530..46f1cfa2 100644 --- a/src/morphobricks_preprocessing/entry_errors.py +++ b/src/morphobricks_preprocessing/entry_errors.py @@ -229,8 +229,53 @@ def entry_output_incomplete(output: str | Path, brick: str, reason: str) -> Entr ) +def uncertain_code_fix( + brick: str = "the brick", library: tuple[str, str | None, str] | None = None +) -> str: + """Return the fix of ``ENTRY_IDENTITY_UNCERTAIN`` cases (a)-(c): the installed code. + + Parameters + ---------- + brick + The brick's distribution name. + library + When a library, not the brick, is what is uncertain: its name, installed version and + why (``"editable install"`` or ``"RECORD missing"``, from + :func:`.entry_identity.library_identity`). + The ADR's text names the brick; telling the user to reinstall a brick that is already a + released install would not help, so the fix names the library instead. Both library + fixes force the reinstall: pip leaves an installed version that already satisfies the + pin (an editable one included) as it is. + """ + if library is None: + return ( + f"Install a released {brick} (not editable, its files as its RECORD lists them), " + "or give another --output." + ) + name, version, why = library + pinned = f"{name}=={version}" if version else name + if why == "RECORD missing": + return ( + f"The library {name} {version or ''}".rstrip() + + " is installed without a RECORD file (conda and setup.py installs write none), " + f"so its files cannot be identified; {brick} itself needs no change. Reinstall " + f'{name} with pip (pip install --force-reinstall --no-deps "{pinned}"), or give ' + "another --output." + ) + return ( + f"The library {name} is an editable install; {brick} itself needs no change. Install a " + f'released {name} (pip install --force-reinstall --no-deps "{pinned}"), or give ' + "another --output." + ) + + def entry_identity_uncertain( - output: str | Path, reason: str, case: str, brick: str = "the brick" + output: str | Path, + reason: str, + case: str, + brick: str = "the brick", + *, + library: tuple[str, str | None, str] | None = None, ) -> EntryError: """Return ``ENTRY_IDENTITY_UNCERTAIN``: the output cannot be compared with this run. @@ -245,14 +290,15 @@ def entry_identity_uncertain( :data:`UNCERTAIN_MOVED` ((e)); it chooses the fix. brick The brick's distribution name, for case (a)-(c)'s fix. + library + For case (a)-(c), the library that is uncertain when the brick itself is not + (:func:`.entry_identity.uncertain_library`); the fix then names it + (:func:`uncertain_code_fix`). """ if case not in _UNCERTAIN_CASES: raise ValueError(f"{case!r} is not one of {_UNCERTAIN_CASES}") fix = { - UNCERTAIN_CODE: ( - f"Install a released {brick} (not editable, its files as its RECORD lists them), " - "or give another --output." - ), + UNCERTAIN_CODE: uncertain_code_fix(brick, library), UNCERTAIN_RECORD: "Give another --output.", UNCERTAIN_MOVED: ( "Open the run folder with the experiment and masks folders at the location the " diff --git a/src/morphobricks_preprocessing/entry_identity.py b/src/morphobricks_preprocessing/entry_identity.py index 4d0abced..f89726f8 100644 --- a/src/morphobricks_preprocessing/entry_identity.py +++ b/src/morphobricks_preprocessing/entry_identity.py @@ -5,14 +5,21 @@ commit, with **every installed file of the brick hashed** against ``RECORD`` on each run (:func:`.code_identity.code_identity`, owner decision of 19 November 2026); the Python version and the machine; every library the brick may compute with (each requirement of its -distribution, directly or through another, whatever its extra or marker; the names a caller -adds, such as MorphoFeature's ``RESULT_LIBRARIES``; every installed ``nvidia-*``), each by name, +distribution, directly or through another, whatever its extra or marker, except the installers +:data:`INSTALL_TOOLS`; the names a caller adds, such as MorphoFeature's ``RESULT_LIBRARIES``; +every installed ``nvidia-*``), each by name, version, Git commit and the SHA-256 of its ``RECORD``, with **no per-file hashing of libraries**; the thread setting (recorded in the ``brick`` part but left out of the record's identity digest: ADR 0007 RE7, owner decision 3 of 1 December 2026); a provider manifest's and the model weights' SHA-256. An editable install of the brick or of a library, a brick or library without ``RECORD``, or a brick file that differs from its ``RECORD`` makes the identity ``uncertain`` (never reused). + +The installers ``pip``, ``setuptools`` and ``wheel`` are not followed as requirements (v0.10.1): +they install and build distributions, no brick computes a value with them, and conda installs +``setuptools`` as an ``.egg-info`` without ``RECORD``, which made every entry output written in a +conda environment uncertain (never reused). A caller that names one in ``libraries`` still has +it identified. """ from __future__ import annotations @@ -37,6 +44,8 @@ "NUMBA_NUM_THREADS", ) """The thread variables MorphoFeature's ``brick_cache`` keys on (its ``threads.py``).""" +INSTALL_TOOLS = frozenset({"pip", "setuptools", "wheel"}) +"""Installers left out of the requirement closure: no brick computes with them (v0.10.1).""" _REQUIREMENT_NAME = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?") @@ -57,7 +66,8 @@ def _normalized(name: str) -> str: def _requirements(name: str) -> set[str]: """Return every distribution ``name`` requires, directly or through an installed one. - Every requirement counts, whatever its extra or marker (MorphoFeature's ``brick_cache``). + Every requirement counts, whatever its extra or marker (MorphoFeature's ``brick_cache``), + except the installers :data:`INSTALL_TOOLS`, which are neither listed nor followed. """ found: set[str] = set() pending = [_normalized(name)] @@ -68,7 +78,9 @@ def _requirements(name: str) -> set[str]: continue # recorded as absent for requirement in requires: match = _REQUIREMENT_NAME.match(requirement.strip()) - if match and _normalized(match.group()) not in found: + if not match or _normalized(match.group()) in INSTALL_TOOLS: + continue + if _normalized(match.group()) not in found: found.add(_normalized(match.group())) pending.append(_normalized(match.group())) return found @@ -111,6 +123,23 @@ def library_identity(name: str) -> dict[str, object]: return found +def uncertain_library(brick: Mapping[str, object]) -> tuple[str, str | None, str] | None: + """Return the library that makes a ``brick`` part uncertain: name, version and why. + + None when the brick is certain or when its own code is what is uncertain (the brick's + reason comes first, as in :func:`brick_identity`). + """ + code = brick.get("code") + if not brick.get("uncertain") or not isinstance(code, Mapping) or not code.get("verified"): + return None + libraries = brick.get("libraries") + for name, found in (libraries if isinstance(libraries, Mapping) else {}).items(): + if isinstance(found, Mapping) and found.get("uncertain"): + version = found.get("version") + return str(name), version if isinstance(version, str) else None, str(found["uncertain"]) + return None + + def thread_setting(threads: Mapping[str, object] | None = None) -> dict[str, object]: """Return the thread setting of the identity (RE7, MorphoFeature's ``thread_identity``). @@ -141,7 +170,8 @@ def brick_identity( The brick's ID, as the output name uses it. libraries Libraries the brick computes with besides its requirements (MorphoFeature's - ``RESULT_LIBRARIES``); every installed ``nvidia-*`` is always added. + ``RESULT_LIBRARIES``), identified even when one is in :data:`INSTALL_TOOLS`; every + installed ``nvidia-*`` is always added. provider_manifest_sha256 For a MorphoFeature provider, its manifest's SHA-256. weights diff --git a/src/morphobricks_preprocessing/entry_record.py b/src/morphobricks_preprocessing/entry_record.py index 53a5daf5..2daa7c69 100644 --- a/src/morphobricks_preprocessing/entry_record.py +++ b/src/morphobricks_preprocessing/entry_record.py @@ -43,6 +43,7 @@ import json import os import re +import warnings from collections.abc import Iterable, Mapping from dataclasses import dataclass from pathlib import Path @@ -56,10 +57,12 @@ entry_identity_uncertain, entry_output_exists, entry_output_incomplete, + uncertain_code_fix, ) from .entry_identity import brick_identity as brick_identity from .entry_identity import library_identity as library_identity from .entry_identity import plain as _plain +from .entry_identity import uncertain_library as uncertain_library from .entry_publish import ENTRY_FILENAME as ENTRY_FILENAME from .entry_publish import check_output_place as check_output_place from .entry_publish import default_output as default_output @@ -90,6 +93,29 @@ class EntryRecordError(ValueError): """A ``morphobricks_entry.json`` that is not a record this package reads (the reason).""" +class EntryIdentityWarning(UserWarning): + """An output written under an uncertain code identity: it will never be reused (RE10).""" + + +def identity_warning(record: Mapping, output: str | os.PathLike | None = None) -> str | None: + """Return what a first run under an uncertain identity tells its user, or None if certain. + + ADR 0007 RE10 publishes such an output and never reuses it; saying so when it is written + spares the user a refusal they cannot explain on the next run. ``output`` is the published + output's path, when known (:func:`write_entry_record` writes into the staging folder). + """ + brick = record["brick"] + if not brick.get("uncertain"): + return None + fix = uncertain_code_fix(str(brick.get("distribution")), uncertain_library(brick)) + subject = "This output" if output is None else f"The output {output}" + return ( + f"{subject} is written, but its code identity is uncertain ({brick['uncertain']}), so " + "it will never be reused: a later run or check with this output is refused with " + f"ENTRY_IDENTITY_UNCERTAIN. {fix}" + ) + + @dataclass(frozen=True) class EntryResult: """What a brick's entry returns (ADR 0007 "The entry contract"). @@ -254,7 +280,9 @@ def write_entry_record(folder: str | os.PathLike, record: Mapping) -> Path: """Write ``record`` as ``morphobricks_entry.json`` in ``folder`` (canonical, UTF-8, LF). Call it last: the record marks a complete output. It is checked by :func:`check_entry_record` - before it is written, and never replaces an existing record. + before it is written, and never replaces an existing record. A record whose ``brick`` is + uncertain is written and an :class:`EntryIdentityWarning` (:func:`identity_warning`) says that + the output will never be reused. """ data = _plain(record) _checked(data, Path(folder) / ENTRY_FILENAME) @@ -264,6 +292,9 @@ def write_entry_record(folder: str | os.PathLike, record: Mapping) -> Path: handle.write(text) handle.flush() os.fsync(handle.fileno()) + # Only once the record is on disk: the warning says the output is written. + if (message := identity_warning(data)) is not None: + warnings.warn(message, EntryIdentityWarning, stacklevel=2) return path @@ -475,7 +506,11 @@ def reuse_or_refuse( return None if record["brick"].get("uncertain"): raise entry_identity_uncertain( - folder, record["brick"]["uncertain"], UNCERTAIN_CODE, record["brick"]["distribution"] + folder, + record["brick"]["uncertain"], + UNCERTAIN_CODE, + record["brick"]["distribution"], + library=uncertain_library(record["brick"]), ) path = folder / ENTRY_FILENAME if not path.is_file() or path.is_symlink(): diff --git a/src/morphobricks_preprocessing/fast_answers.py b/src/morphobricks_preprocessing/fast_answers.py index f5d24632..00bbad58 100644 --- a/src/morphobricks_preprocessing/fast_answers.py +++ b/src/morphobricks_preprocessing/fast_answers.py @@ -9,9 +9,16 @@ in folder order (named in the output); its header names are confirmed as the channels' ``header_names`` (FC3 evidence), never matched by similarity; - ``--image-type`` is the list's image type, never inferred; -- ``--accept-ids`` accepts every proposed ID (a folder with no proposal stops publication); +- ``--accept-ids`` accepts every proposed ID; ``--id FOLDER=ID`` names one folder's ID (applied + to the draft before, :mod:`.describe_ids`), and a folder with neither stops publication; - ``--comparable`` is the N35 answer for every biological repeat; -- ``--confirmed-on`` is the day of those statements, never the clock's. +- ``--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 +27,19 @@ from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Collection, Sequence +from .describe_ids import needs_id from .draft import Draft from .draft_answers import ( CHANNELS, + EXPERIMENT, ChannelAnswer, ConditionAnswer, DraftAnswers, LayoutAnswer, RepeatAnswer, + UnitAnswer, UnitKey, valid_day, ) @@ -47,29 +57,61 @@ def tagged_unit(draft: Draft) -> UnitKey | None: def _ids(draft: Draft) -> tuple[dict, dict, dict, list[str]]: - """Return the proposed IDs as answers, and every folder that has no proposal.""" + """Return the IDs as answers (``--id``'s, else the proposal), and every folder with none.""" missing: list[str] = [] conditions = {} for folder, slot in sorted(draft.conditions.items()): - if slot.proposed is None: - missing.append( - f"condition folder {folder!r} has no proposed ID: name it in the notebook" - ) - conditions[folder] = ConditionAnswer(slot.proposed) + chosen = slot.confirmed or slot.proposed + if chosen is None: + missing.append(needs_id("conditions", folder, draft.used_ids.get("conditions", ()))) + conditions[folder] = ConditionAnswer(chosen) technical = {} for folder, slot in sorted(draft.technical_repeats.items()): - if slot.proposed is None: - missing.append(f"technical repeat folder {folder!r} has no proposed ID") + chosen = slot.confirmed or slot.proposed + if chosen is None: + used = draft.used_ids.get("technical_repeats", ()) + missing.append(needs_id("technical_repeats", folder, used)) else: - technical[folder] = slot.proposed + technical[folder] = chosen repeats = {} for label, repeat in sorted(draft.repeats.items()): - if repeat.id.proposed is None: - missing.append(f"repeat {label!r} has no proposed ID") - repeats[label] = RepeatAnswer(repeat.id.proposed) + chosen = repeat.id.confirmed or repeat.id.proposed + if chosen is None: + missing.append(needs_id("repeats", label, draft.used_ids.get("repeats", ()))) + repeats[label] = RepeatAnswer(chosen) return conditions, technical, repeats, missing +def _all_named(draft: Draft) -> bool: + """Return whether every ID of the draft is already the user's (``--id``).""" + slots = [*draft.conditions.values(), *draft.technical_repeats.values()] + slots += [repeat.id for repeat in draft.repeats.values()] + return all(slot.confirmed is not None for slot in slots) + + +def _statements( + draft: Draft, accept_ids: bool, comparable: bool, confirmed_on: str | None +) -> list[str]: + """Return the user's statements still missing: the IDs, the N35 answer and its day.""" + blockers = [] + if not accept_ids and not _all_named(draft): + blockers.append( + "accept the proposed IDs (--accept-ids), or name them (--id FOLDER=ID, or in the " + "notebook)" + ) + if not comparable: + blockers.append( + "Comparability has not been confirmed. Add --comparable only if the samples in each " + "biological repeat were prepared and acquired comparably. If some repeats were not, " + "do not add --comparable: answer for each biological repeat on the notebook's Check " + "and save card (step 1), which records the repeats that are not comparable. Do not " + "confirm an incorrect experimental design." + ) + if confirmed_on is None or not valid_day(confirmed_on): + blockers.append("give the day of your statements as YYYY-MM-DD (--confirmed-on)") + return blockers + + def fast_answers( draft: Draft, channels: Sequence[str], @@ -79,30 +121,37 @@ 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: - blockers.append("accept the proposed IDs (--accept-ids), or name them in the notebook") - if not comparable: - blockers.append( - "say that every biological repeat's folders were prepared and acquired under the " - "same circumstances (--comparable)" - ) - if confirmed_on is None or not valid_day(confirmed_on): - blockers.append("give the day of your statements as YYYY-MM-DD (--confirmed-on)") + blockers = _statements(draft, accept_ids, comparable, confirmed_on) if image_type == "rgb" and tuple(channels) != RGB_LIST: blockers.append("a colour (RGB) list is exactly R,G,B (--channels R,G,B)") + if rgb_override and image_type != "rgb": + 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)): blockers.append( - f"the tagged unit's image has {len(header_names)} named channels, --channels " - f"lists {len(channels)}: tag it again" + f"The first acquisition has {len(header_names)} named channels, but --channels lists " + f"{len(channels)}. Check the number and stored order of the channels, then correct " + "--channels. If acquisitions have different channel lists, describe their channels " + "separately in the notebook." ) conditions, technical, repeats, missing = _ids(draft) blockers += missing @@ -121,6 +170,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/he_tissue_array.py b/src/morphobricks_preprocessing/he_tissue_array.py index 6e8ed867..fb3bdfef 100644 --- a/src/morphobricks_preprocessing/he_tissue_array.py +++ b/src/morphobricks_preprocessing/he_tissue_array.py @@ -1,11 +1,11 @@ """The H&E tissue mask of an image array in memory, with no run (contract §15.4; roadmap K3). -``he_tissue_mask_array(rgb)`` computes the fixed rule ``he_tissue_v1`` (**provisional**) on one -``uint8`` ``(Y, X, 3)`` R, G, B array and returns the boolean mask (``True`` kept) with a small -immutable record of what computed it. It is for standalone users (a script, another brick's +``he_tissue_mask_array(rgb)`` computes a fixed rule (``he_tissue_v2`` by default, **provisional**) +on one ``uint8`` ``(Y, X, 3)`` R, G, B array and returns the boolean mask (``True`` kept) with a +small immutable record of what computed it. It is for standalone users (a script, another brick's folder command) who have pixels but no MorphoBricks run. The computation is the run route's own -(:func:`.he_tissue_mask.rule_on_plane`, called with the array moved to ``(3, Y, X)``), never a -copy, so the two masks are bitwise equal for the same pixels. +(:func:`.he_tissue_mask.rule_on_plane`, called with the array moved to ``(3, Y, X)``), never a copy, +so the two masks are bitwise equal for the same pixels. **Not a run artifact (Spec ADR 0005 BM15).** BM15 governs a derived region mask *written in a run*: a file in the masks folder with its ``mask_lineage.jsonl`` line, declared by the user and @@ -38,7 +38,7 @@ import numpy as np -HE_TISSUE_V1 = "he_tissue_v1" +HE_TISSUE_V2 = "he_tissue_v2" """The default rule, as in ``RunInputs.he_tissue_mask`` (provisional; :mod:`.he_tissue_rule`).""" IN_MEMORY = "" """The label of the plane in the shared computation: an array, not an image of a run.""" @@ -68,7 +68,7 @@ class TissueMaskArrayRecord: Attributes ---------- rule_id - The rule asked for (``"he_tissue_v1"``). + The rule asked for (``"he_tissue_v2"`` by default). operation The rule's operation (``"he_tissue_mask"``), as in the run route's lineage. rule_text @@ -113,12 +113,12 @@ def rule(self) -> dict: @property def rule_version(self) -> int: - """The rule record's ``version`` (``1`` for ``he_tissue_v1``).""" + """The rule record's ``version`` (``2`` for ``he_tissue_v2``).""" return self.rule["version"] @property def status(self) -> str: - """The rule record's ``status``: ``"provisional"`` for ``he_tissue_v1``.""" + """The rule record's ``status``: ``"provisional"`` for both rules.""" return self.rule["status"] @property @@ -154,14 +154,14 @@ class TissueMaskArray: record: TissueMaskArrayRecord -def he_tissue_mask_array(rgb: np.ndarray, *, rule: str = HE_TISSUE_V1) -> TissueMaskArray: +def he_tissue_mask_array(rgb: np.ndarray, *, rule: str = HE_TISSUE_V2) -> TissueMaskArray: """Compute the H&E tissue mask of one ``uint8`` ``(Y, X, 3)`` R, G, B array in memory. - The rule ``he_tissue_v1`` is **provisional** and fixed: it leaves out nuclei, red blood - cells and empty space, sizes in pixels, colour maths from normalization. The computation is - ``RunInputs.he_tissue_mask``'s own, so the mask is bitwise equal to the run route's for the - same pixels. Nothing is written and no run is read; for MorphoBricks runs use the run route, - which writes the mask with its lineage. + The rule (``he_tissue_v2`` by default) is **provisional** and fixed: it leaves out nuclei, + red blood cells and empty space, sizes in pixels, colour maths from normalization. The + computation is ``RunInputs.he_tissue_mask``'s own, so the mask is bitwise equal to the run + route's for the same pixels. Nothing is written and no run is read; for MorphoBricks runs use + the run route, which writes the mask with its lineage. Parameters ---------- @@ -169,7 +169,8 @@ def he_tissue_mask_array(rgb: np.ndarray, *, rule: str = HE_TISSUE_V1) -> Tissue A plain ``numpy.ndarray`` of pixel type ``uint8`` and shape ``(Y, X, 3)``, the last axis R, G, B. Nothing is converted and no axis is guessed. rule - The rule ID; ``"he_tissue_v1"`` is the only one. + The rule ID: ``"he_tissue_v2"`` (the default: the white estimated from the plane) or + ``"he_tissue_v1"`` (the white fixed at 255). Returns ------- diff --git a/src/morphobricks_preprocessing/he_tissue_mask.py b/src/morphobricks_preprocessing/he_tissue_mask.py index 971b38eb..15cfaf10 100644 --- a/src/morphobricks_preprocessing/he_tissue_mask.py +++ b/src/morphobricks_preprocessing/he_tissue_mask.py @@ -1,8 +1,9 @@ """The opt-in H&E tissue mask helper (Spec ADR 0005 BM15; design ``docs/design/he-tissue-mask.md``). ``RunInputs.he_tissue_mask(fov, output_mask_id=...)`` writes one ``uint8`` region mask of one RGB -position: ``1`` where the fixed rule (:mod:`.he_tissue_rule`, ``he_tissue_v1``, **provisional**) -keeps the pixel, ``0`` where it leaves out nuclei, red blood cells or empty space. +position: ``1`` where the fixed rule (:mod:`.he_tissue_rule`, ``he_tissue_v2`` by default, +``he_tissue_v1`` on request, both **provisional**) keeps the pixel, ``0`` where it leaves out +nuclei, red blood cells or empty space. ``RunInputs.preview_he_tissue_mask(fov)`` computes the same in memory and writes nothing. Both are reached through :class:`.run_inputs_tissue.TissueMaskInputs`, which imports this module only when called: scikit-image, normalization's ``stain`` module and this module stay out of a core @@ -24,8 +25,9 @@ **Colour maths: normalization's, never reimplemented.** ``E`` and ``H`` are ``stain.to_scalar(rgb, axes="CYX", preset="he_eosin")``'s ``image`` and ``exclusion``; the per-channel optical density is ``optical_density(rgb_yxc(rgb, "CYX"), check_white((255, 255, -255)))``, unpacked as ``(od, od_floored)``. The HED matrix is only looked up by the preset's own -name for it, to hash it into the rule record. +255)))``, unpacked as ``(od, od_floored)``; under ``he_tissue_v2``, of the plane rescaled to its +white (:func:`.he_tissue_rule.white_rescaled`). The HED matrix is only looked up by the +preset's own name for it, to hash it into the rule record. **Output and publication.** The file goes to ``///.tif`` with its line of ``mask_lineage.jsonl`` (the BM15 schema, @@ -60,14 +62,16 @@ from .code_identity import code_identity from .he_tissue_rule import ( - HE_TISSUE_V1, + DEFAULT_RULE, OPERATION, PROVISIONAL, RULES, TissueComponents, rule_record, tissue_components, + white_rescaled, ) +from .he_tissue_run_facts import override_record, pixel_size_record from .image_names import position_id from .lineage_schema import BM15_LINE_KEYS, CODE_KEYS, EXPERIMENT_ROOT, rule_sha256 from .mask_conversion import _check_case_collision, _check_output_id, _digest_of @@ -158,9 +162,11 @@ class TissueMaskPreview: fractions As :attr:`TissueMaskResult.fractions`, from the full-resolution mask. rule - The rule's canonical record (``status`` ``"provisional"`` for ``he_tissue_v1``). + The rule's canonical record (``status`` ``"provisional"``). code The two code identities; ``reusable`` is True only when both are verified. + white + The white ``E``, ``H`` and ``od`` were measured against (v2), or ``None`` (v1: 255). """ image: str @@ -173,6 +179,7 @@ class TissueMaskPreview: fractions: Mapping[str, float] rule: Mapping[str, Any] code: Mapping[str, Mapping[str, object]] + white: tuple[float, float, float] | None = None @property def reusable(self) -> bool: @@ -260,8 +267,9 @@ def current_rule(rule: str) -> dict: found = stain.PRESETS[PRESET].version if found != PRESET_VERSION: raise ValueError( - f"The installed normalization's {PRESET} preset is version {found}; {rule} is " - f"defined on version {PRESET_VERSION}" + "The installed normalization version is incompatible with this tissue-mask rule " + f"({rule} needs its {PRESET} preset at version {PRESET_VERSION}, found {found}). " + "Reinstall this preprocessing release with its required dependencies and retry." ) source, digest = hed_matrix() return rule_record(rule, hed_source=source, hed_sha256=digest) @@ -289,23 +297,26 @@ def resolved_fov(run: RunInputs, fov: object) -> Fov: raise RunInputsError(f"{relative} is not an image of this run.") if found.image_type != "rgb": raise ValueError( - f"{relative} is declared {found.image_type}; the H&E tissue mask takes a unit declared " - 'image_type = "rgb"' + f"{relative} was described as separate channels rather than RGB. If it is genuinely " + "a colour image, correct the experiment description and run preprocessing again." ) if found.z_count > 1 or found.t_count > 1: raise ValueError( - f"{relative} has {found.z_count} Z planes and {found.t_count} time points; the H&E " - "tissue mask takes one 2-D plane" + f"{relative} has {found.z_count} Z planes and {found.t_count} time points. The H&E " + "tissue mask does not accept Z-stacks or time-lapses. Use a supported single-plane " + "RGB image, or create appropriate masks with another segmentation tool." ) if found.dtype != "uint8" or found.c_count != 3: raise ValueError( - f"{relative} has the pixel type {found.dtype} and {found.c_count} channels; the H&E " - "tissue mask takes 8-bit RGB (uint8, three channels R, G, B)" + f"{relative} has the pixel type {found.dtype} and {found.c_count} channels. This " + "helper requires 8-bit colour images containing red, green and blue (uint8). Export " + "a suitable RGB copy (converting to 8-bit changes the intensities the rule's " + "thresholds apply to) or create a region mask using another tool." ) return found -def preview(run: RunInputs, fov: object, *, rule: str = HE_TISSUE_V1) -> TissueMaskPreview: +def preview(run: RunInputs, fov: object, *, rule: str = DEFAULT_RULE) -> TissueMaskPreview: """Compute one position's tissue mask in memory (``RunInputs.preview_he_tissue_mask``).""" found = resolved_fov(run, fov) record = current_rule(rule) @@ -313,7 +324,7 @@ def preview(run: RunInputs, fov: object, *, rule: str = HE_TISSUE_V1) -> TissueM def he_tissue_mask( - run: RunInputs, fov: object, *, output_mask_id: str, rule: str = HE_TISSUE_V1 + run: RunInputs, fov: object, *, output_mask_id: str, rule: str = DEFAULT_RULE ) -> TissueMaskResult: """Write one position's tissue mask with its lineage line (``RunInputs.he_tissue_mask``). @@ -331,7 +342,8 @@ def he_tissue_mask( if run.masks_root is None: raise ValueError( f"{found.relative_path}: the run has no masks folder; the H&E tissue mask is written " - "there only. Run preprocessing with a masks folder first" + "there only. Run preprocessing with a masks folder first (the command tissue-mask " + "creates and records one)" ) record = current_rule(rule) relative = _output_target(run, found.relative_path, output_mask_id) @@ -388,14 +400,14 @@ def _differences( def _collision(relative: str, differences: list[str]) -> ValueError: """Return the refusal of an existing output that is not this computation's.""" text = ( - f"{relative} exists in the masks folder and is not this computation's output (it " - f"differs in: {', '.join(differences)}); nothing is overwritten. Choose another output " - "mask ID" + f"A different mask already exists at {relative} in the masks folder (it differs in: " + f"{', '.join(differences)}). It will not be overwritten. Choose another output mask ID " + "(--to on the command line), for example HETissue_v2." ) if "rule" in differences or "rule_sha256" in differences: text += ( - ": a rule with another record (a frozen rule included) makes a new mask under a new " - "output mask ID, declared binary, with the masks step run again" + " A rule with another record (a frozen rule included) makes a new mask under a new " + "output mask ID, declared binary, with the masks step run again." ) return ValueError(text) @@ -469,8 +481,9 @@ def rule_on_plane( computation, never a copy. The caller has checked the plane and the rule (:func:`current_rule`). ``image`` labels the plane in the result. """ - scalar = stain.to_scalar(pixels, axes=SOURCE_AXES, preset=PRESET) - od, od_floored = _optical_density(pixels) + measured, white = white_rescaled(pixels, record) + scalar = stain.to_scalar(measured, axes=SOURCE_AXES, preset=PRESET) + od, od_floored = _optical_density(measured) components = tissue_components(scalar.image, scalar.exclusion, od, record) fractions = {**components.fractions(), "od_floored": od_floored} return TissueMaskPreview( @@ -484,6 +497,7 @@ def rule_on_plane( fractions=MappingProxyType(fractions), rule=MappingProxyType(record), code=code_identities(), + white=white, ) @@ -510,30 +524,6 @@ def _optical_density(pixels: np.ndarray) -> tuple[np.ndarray, float]: return od, floored -def _override(run: RunInputs, found: Fov) -> dict[str, object]: - """Return the unit's declared RGB header override and this image's recorded item.""" - recorded = run.manifest.experiment_description or {} - for unit in recorded.get("units", ()): - key = (unit.get("repeat"), unit.get("condition"), unit.get("technical_repeat")) - if key == (found.repeat_group, found.condition_id, found.technical_repeat_id): - items = unit.get("rgb_header_override_images", ()) - image = next((i for i in items if i.get("image") == found.relative_path), None) - return {"declared": unit.get("rgb_header_override") is True, "image": image} - raise RunInputsError(f"The run records no unit for {found.relative_path}. Run it again.") - - -def _pixel_size(run: RunInputs, image: str) -> dict | None: - """Return the recorded X and Y sizes (information only), or None when neither has one.""" - sizes = run.pixel_sizes(image) - found = {role: sizes.get(role) for role in ("X", "Y")} - if all(size is None or size.value is None for size in found.values()): - return None - return { - role: None if size is None else {k: v for k, v in size.to_dict().items() if k != "role"} - for role, size in found.items() - } - - def _planned( run: RunInputs, found: Fov, relative: str, output_id: str, record: Mapping[str, Any] ) -> dict: @@ -553,8 +543,8 @@ def _planned( "scikit_image_version": skimage_module().__version__, "scipy_version": scipy.__version__, "image_type": found.image_type, - "rgb_header_override": _override(run, found), - "pixel_size": _pixel_size(run, found.relative_path), + "rgb_header_override": override_record(run, found), + "pixel_size": pixel_size_record(run, found.relative_path), "fractions": None, "helper": HELPER, "helper_version": __version__, diff --git a/src/morphobricks_preprocessing/he_tissue_rule.py b/src/morphobricks_preprocessing/he_tissue_rule.py index 74e2f562..f0d01dcd 100644 --- a/src/morphobricks_preprocessing/he_tissue_rule.py +++ b/src/morphobricks_preprocessing/he_tissue_rule.py @@ -14,7 +14,20 @@ - background: ``max(OD_R, OD_G, OD_B) < 0.08``; opened by a disk of radius 2, then pieces under 1000 px removed (only lumens, fat and tears; not the gaps between fibres). -``keep = not (nuclei or red_cells or background)``. ``E`` and ``H`` are normalization's +``keep = not (nuclei or red_cells or background)``. + +``he_tissue_v2`` (status ``"provisional"``; the default since v0.10.1) is ``he_tissue_v1`` on the +plane rescaled to its own white: v1 fixes the white at 255, so a scan whose glass is grey (the +Zenodo 4550300 cores, glass near (127, 135, 145)) read as stained everywhere and v1 kept 0 %. +v2 estimates the white per channel as the **median of the pixels whose R + G + B is at or above +the 99.9th percentile of R + G + B** (NumPy ``percentile``, method ``linear``), raised to at +least 1 (:func:`estimate_white`), rescales the plane with normalization's +``rescale_to_white`` (``clip(rint(I * 255 / white), 0, 255)`` as uint8, N69) and then applies +v1's components unchanged to the rescaled plane. On a plane whose brightest pixels are white +(255) the rescaling is the identity and v2 equals v1. The white is read from the plane, so a +plane with no glass or empty space takes its brightest tissue as white (recorded in the design). + +``E`` and ``H`` are normalization's ``to_scalar(..., preset="he_eosin")`` ``image`` and ``exclusion`` (float32), ``OD`` its ``optical_density`` (float64, ``(Y, X, 3)``). Every comparison is made in float64 on the values as normalization returns them, as written (``>=`` or ``<``), with no rounding and no tolerance; @@ -35,6 +48,7 @@ from dataclasses import dataclass import numpy as np +from morphobricks_normalization.optical_density import check_white, rescale_to_white from scipy import ndimage PROVISIONAL = "provisional" @@ -43,6 +57,11 @@ OPERATION = "he_tissue_mask" """The lineage ``operation`` of every ``he_tissue`` rule (Spec ADR 0005 BM15).""" HE_TISSUE_V1 = "he_tissue_v1" +HE_TISSUE_V2 = "he_tissue_v2" +DEFAULT_RULE = HE_TISSUE_V2 +"""The rule used when none is named (since v0.10.1; ``he_tissue_v1`` stays offered unchanged).""" +WHITE_PERCENTILE = 99.9 +"""v2's white: the median of the pixels at or above this percentile of R + G + B.""" CONNECTIVITY = 8 DISK = "x*x + y*y <= r*r" COMPONENT_NAMES = ("nuclei", "red_cells", "background") @@ -94,8 +113,22 @@ "combine": "keep = not (nuclei or red_cells or background)", } -RULES: Mapping[str, str] = {HE_TISSUE_V1: PROVISIONAL} -"""The known rule IDs and the ``status`` each is offered with (v1 is provisional).""" +_V2 = copy.deepcopy(_V1) +_V2["version"] = 2 +_V2["input"]["white"] = "estimated" +_V2["white"] = { + "estimate": "per channel: median of the pixels whose R+G+B >= percentile(R+G+B, 99.9, " + "method='linear'), at least 1", + "rescale": { + "function": "morphobricks_normalization.optical_density.rescale_to_white", + "definition": "clip(rint(I * 255 / white), 0, 255) as uint8, rint half to even", + }, + "then": "the components of he_tissue v1 on the rescaled plane, white [255, 255, 255]", +} +_RECORDS = {HE_TISSUE_V1: _V1, HE_TISSUE_V2: _V2} + +RULES: Mapping[str, str] = {HE_TISSUE_V1: PROVISIONAL, HE_TISSUE_V2: PROVISIONAL} +"""The known rule IDs and the ``status`` each is offered with (both provisional).""" def rule_record(rule_id: str, *, hed_source: str, hed_sha256: str) -> dict: @@ -121,7 +154,7 @@ def rule_record(rule_id: str, *, hed_source: str, hed_sha256: str) -> dict: raise ValueError(f"The rule {rule_id!r} is not known; the known rules are {known}") if RULES[rule_id] not in STATUSES: raise ValueError(f"The rule {rule_id!r} has the unknown status {RULES[rule_id]!r}") - record = copy.deepcopy(_V1) + record = copy.deepcopy(_RECORDS[rule_id]) record["status"] = RULES[rule_id] record["colour"]["hed_matrix"] = {"source": hed_source, "sha256": hed_sha256} return record @@ -150,6 +183,40 @@ def fractions(self) -> dict[str, float]: } +def estimates_white(rule: Mapping[str, object]) -> bool: + """Return True when a rule record rescales the plane to its own white first (v2).""" + return "white" in rule + + +def estimate_white(rgb: np.ndarray) -> tuple[float, float, float]: + """Return a plane's white as v2 estimates it, from its ``uint8`` ``(Y, X, 3)`` pixels. + + Per channel, the median of the pixels whose ``R + G + B`` is at or above the 99.9th + percentile of ``R + G + B`` (NumPy ``percentile``, method ``linear``), raised to at least 1 + so that normalization accepts it as a white. Pure counting: no colour maths. + """ + total = rgb.astype(np.int32).sum(axis=-1) + bright = total >= np.percentile(total, WHITE_PERCENTILE, method="linear") + white = np.maximum(np.median(rgb[bright], axis=0), 1.0) + return tuple(float(value) for value in white) + + +def white_rescaled( + pixels: np.ndarray, rule: Mapping[str, object] +) -> tuple[np.ndarray, tuple[float, float, float] | None]: + """Return the ``uint8`` ``(3, Y, X)`` plane a rule measures, and the white it rescaled to. + + A rule that estimates the white (v2) rescales the plane to :func:`estimate_white` with + normalization's ``rescale_to_white``; any other returns ``pixels`` itself and ``None``. + """ + if not estimates_white(rule): + return pixels, None + rgb = np.moveaxis(pixels, 0, -1) + white = estimate_white(rgb) + rescaled, _clipped = rescale_to_white(rgb, check_white(white)) + return np.ascontiguousarray(np.moveaxis(rescaled, -1, 0)), white + + def disk(radius: int) -> np.ndarray: """Return the boolean disk ``x*x + y*y <= r*r`` of side ``2 r + 1``.""" yy, xx = np.mgrid[-radius : radius + 1, -radius : radius + 1] diff --git a/src/morphobricks_preprocessing/he_tissue_run_facts.py b/src/morphobricks_preprocessing/he_tissue_run_facts.py new file mode 100644 index 00000000..dd5c0a06 --- /dev/null +++ b/src/morphobricks_preprocessing/he_tissue_run_facts.py @@ -0,0 +1,40 @@ +"""What the H&E tissue mask's lineage line records about the run (Spec ADR 0005 BM15). + +Moved from :mod:`.he_tissue_mask` (v0.10.1, its 600-line limit): the unit's declared RGB header +override with this image's recorded item (copied unchanged, never decided again; design §2), and +the image's recorded X and Y pixel sizes, for information only (sizes in the rule are pixels). +Nothing here reads a pixel. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .run_inputs_error import RunInputsError + +if TYPE_CHECKING: + from .run_inputs import Fov, RunInputs + + +def override_record(run: RunInputs, found: Fov) -> dict[str, object]: + """Return the unit's declared RGB header override and this image's recorded item.""" + recorded = run.manifest.experiment_description or {} + for unit in recorded.get("units", ()): + key = (unit.get("repeat"), unit.get("condition"), unit.get("technical_repeat")) + if key == (found.repeat_group, found.condition_id, found.technical_repeat_id): + items = unit.get("rgb_header_override_images", ()) + image = next((i for i in items if i.get("image") == found.relative_path), None) + return {"declared": unit.get("rgb_header_override") is True, "image": image} + raise RunInputsError(f"The run records no unit for {found.relative_path}. Run it again.") + + +def pixel_size_record(run: RunInputs, image: str) -> dict | None: + """Return the recorded X and Y sizes (information only), or None when neither has one.""" + sizes = run.pixel_sizes(image) + found = {role: sizes.get(role) for role in ("X", "Y")} + if all(size is None or size.value is None for size in found.values()): + return None + return { + role: None if size is None else {k: v for k, v in size.to_dict().items() if k != "role"} + for role, size in found.items() + } diff --git a/src/morphobricks_preprocessing/ignored_masks.py b/src/morphobricks_preprocessing/ignored_masks.py new file mode 100644 index 00000000..06c84576 --- /dev/null +++ b/src/morphobricks_preprocessing/ignored_masks.py @@ -0,0 +1,211 @@ +"""Mask types and OME-Zarr label images a run skips (owner, 4 December 2026). + +An OME-Zarr image may carry label images a run will not use (a segmentation of another tool, +an old annotation), and a masks folder may hold a mask type that is not part of the analysis. +Every mask type found must be declared (``R_MASK_TYPE_NOT_DECLARED``), and the experiment +description (``morphobricks.toml``, experiment-v1) has no field for "not used". So the +output folder holds a second, small file beside it, written by ``declare-masks --ignore +LABEL`` (:func:`.mask_declare.ignore_masks`, under the output folder's lock): + +.. code-block:: toml + + # Mask types and OME-Zarr label images the runs of this output folder skip. + # Written by declare-masks --ignore; declare a type to use it again. + version = 1 + ignore = ["old_cells", "tissue_v0"] + +``check`` and ``run`` read it (:func:`read_ignored`) and leave those types out of mask +discovery (:func:`.masks.find_masks` ``ignore``): no header check, no record, no +``R_MASK_TYPE_NOT_DECLARED``. The run records the list and the file's SHA-256 in the manifest +(``ignored_masks``), so :class:`.run_inputs.RunInputs` does not count those files as +unrecorded, and refuses a file changed, added or removed since the run +(``RUN_FOLDER_STALE``). Names are compared exactly, as declared types are. A type that is +declared cannot be ignored, and declaring a type takes it off the list. Undeclared types that +are not listed are still refused, as before. + +The reader is strict: other keys, another version, a name twice or a name that is not a mask +type's are :class:`IgnoredMasksError`; nothing is guessed. +""" + +from __future__ import annotations + +import os +import shlex +import tomllib +from collections.abc import Iterable +from dataclasses import dataclass +from pathlib import Path + +from ._io import file_sha256 + +IGNORED_FILENAME = "ignored_masks.toml" +IGNORED_VERSION = 1 +MANIFEST_KEY = "ignored_masks" +"""The manifest's optional entry: ``{"types": [...], "file_sha256": "..."}``.""" +HEADER = ( + "# Mask types and OME-Zarr label images the runs of this output folder skip.\n" + "# Written by declare-masks --ignore; declare a type to use it again.\n" +) + + +class IgnoredMasksError(ValueError): + """Raised when ``ignored_masks.toml`` cannot be read as written, or a name is refused.""" + + +@dataclass(frozen=True) +class IgnoredMasks: + """The ignored mask types of an output folder, and the file's SHA-256 (None: no file).""" + + types: tuple[str, ...] = () + sha256: str | None = None + + def to_manifest(self) -> dict | None: + """Return the manifest's ``ignored_masks`` entry, or None when nothing is ignored.""" + if self.sha256 is None: + return None + return {"types": list(self.types), "file_sha256": self.sha256} + + +def recorded_ignored(entry: object) -> dict | None: + """Return the manifest's ``ignored_masks`` entry checked, as written and as read. + + Raises + ------ + ValueError + When it is not ``{"types": [names, sorted, each once], "file_sha256": 64 hex}``. + """ + if entry is None: + return None + sha = entry.get("file_sha256") if isinstance(entry, dict) else None + types = entry.get("types") if isinstance(entry, dict) else None + if ( + set(entry) != {"types", "file_sha256"} + or not isinstance(sha, str) + or len(sha) != 64 + or any(c not in "0123456789abcdef" for c in sha) + or not isinstance(types, list) + or not all(isinstance(t, str) and name_problem(t) is None for t in types) + or types != sorted(set(types)) + ): + raise ValueError( + f"the manifest's {MANIFEST_KEY} entry is not {{types: sorted names, file_sha256}}" + ) + return {"types": list(types), "file_sha256": sha} + + +def ignored_sha256(manifest: object) -> str | None: + """Return the SHA-256 of ``ignored_masks.toml`` a run's manifest records (None: no file).""" + entry = getattr(manifest, "ignored_masks", None) + return None if entry is None else entry["file_sha256"] + + +def ignored_types(manifest: object) -> frozenset[str]: + """Return the mask types a run's manifest records as skipped.""" + entry = getattr(manifest, "ignored_masks", None) + return frozenset(() if entry is None else entry["types"]) + + +def unreadable_fix(output_folder: str | os.PathLike) -> str: + """Say how to recover from an ignore list that cannot be read (declare-masks reads it first). + + ``declare-masks`` reads the file before it writes it, so it refuses while the unreadable + file is there: the file is moved out (kept as a backup), then the list is made again. + """ + output = shlex.quote(Path(output_folder).as_posix()) + return ( + f"Move {IGNORED_FILENAME} out of the output folder and keep it as a backup: " + "declare-masks reads the list before changing it, so it cannot rewrite an unreadable " + "one. Then recreate the list with morphobricks-preprocessing declare-masks --output " + f"{output} --ignore TYPE, once for every mask type you still intend to skip (replacing " + "TYPE with its name; --ignore can be repeated), and run preprocessing again." + ) + + +def name_problem(name: str) -> str | None: + """Return why ``name`` cannot be an ignored mask type, or None when it can.""" + if not name or name != name.strip(): + return "Give a non-empty mask-type name without leading or trailing spaces." + if any(c in name for c in "/\\") or any(ord(c) < 32 for c in name): + return ( + "Give a mask-type name that is one folder or label name, without '/', '\\' or " + "control characters." + ) + return None + + +def ignored_text(types: Iterable[str]) -> str: + """Return the file's canonical text for ``types`` (sorted, each once).""" + names = sorted(set(types)) + for name in names: + if name_problem(name) is not None: + raise IgnoredMasksError(f"{name!r}: {name_problem(name)}") + quoted = ", ".join('"' + n.replace("\\", "\\\\").replace('"', '\\"') + '"' for n in names) + return f"{HEADER}version = {IGNORED_VERSION}\nignore = [{quoted}]\n" + + +def parse_ignored(data: bytes) -> tuple[str, ...]: + """Return the ignored types of the file's bytes, checked strictly. + + Raises + ------ + IgnoredMasksError + Not UTF-8 TOML, other keys, another version, or an ``ignore`` that is not a list of + distinct mask-type names. + """ + try: + table = tomllib.loads(data.decode("utf-8")) + except (UnicodeDecodeError, tomllib.TOMLDecodeError) as exc: + raise IgnoredMasksError(f"{IGNORED_FILENAME} is not UTF-8 TOML: {exc}") from exc + if set(table) != {"version", "ignore"}: + raise IgnoredMasksError( + f"{IGNORED_FILENAME} holds the keys version and ignore only; it holds " + f"{', '.join(sorted(table)) or 'none'}" + ) + if table["version"] != IGNORED_VERSION or isinstance(table["version"], bool): + raise IgnoredMasksError( + f"{IGNORED_FILENAME} is version {table['version']!r}; this release reads version " + f"{IGNORED_VERSION}" + ) + names = table["ignore"] + if not isinstance(names, list) or not all(isinstance(n, str) for n in names): + raise IgnoredMasksError(f"{IGNORED_FILENAME}: ignore is a list of names") + if len(set(names)) != len(names): + raise IgnoredMasksError(f"{IGNORED_FILENAME}: a name is listed twice") + for name in names: + if name_problem(name) is not None: + raise IgnoredMasksError(f"{IGNORED_FILENAME}: {name!r}: {name_problem(name)}") + return tuple(sorted(names)) + + +def read_ignored(output_folder: str | os.PathLike) -> IgnoredMasks: + """Return the output folder's ignored mask types (empty without the file). + + Raises + ------ + IgnoredMasksError + When the file cannot be read as written (:func:`parse_ignored`), or is a link. + """ + path = Path(output_folder) / IGNORED_FILENAME + if not os.path.lexists(path): + return IgnoredMasks() + if path.is_symlink() or not path.is_file(): + raise IgnoredMasksError(f"{path} is not a plain file; a link is never followed") + data = path.read_bytes() + return IgnoredMasks(parse_ignored(data), file_sha256(path)) + + +__all__ = [ + "IGNORED_FILENAME", + "IGNORED_VERSION", + "MANIFEST_KEY", + "IgnoredMasks", + "IgnoredMasksError", + "ignored_sha256", + "ignored_text", + "ignored_types", + "name_problem", + "parse_ignored", + "read_ignored", + "recorded_ignored", + "unreadable_fix", +] 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/links.py b/src/morphobricks_preprocessing/links.py index 5a3b0cbe..a33d74cc 100644 --- a/src/morphobricks_preprocessing/links.py +++ b/src/morphobricks_preprocessing/links.py @@ -296,11 +296,16 @@ def issues(self) -> list[ValidationIssue]: error( LINK_OUTSIDE, f"{plural(len(self.outside), 'link')} in the {self.what} " - f"{agree(self.outside, 'leads', 'lead')} outside it (link -> target), " - "and nothing outside the selected folder is read: not followed.", + f"{agree(self.outside, 'leads', 'lead')} outside it (link -> target), so " + "the images or masks behind them are not found. Links are followed only " + "inside the selected folder: a run reads, fingerprints and records only " + "what is inside it, and a file behind such a link could be changed or " + "moved through its other path without the run seeing it.", self.outside, - f"Copy or move the files into the {self.what}, or select a folder that " - "holds them, then remove the links.", + f"Move (do not copy) the data into the {self.what}: on the same drive a " + "move is instant, however large the image. Or put the experiment's " + "folders on the drive that holds the data, move the images into them and " + f"select that folder as the {self.what}. Then remove the links.", ) ) if self.loops: diff --git a/src/morphobricks_preprocessing/manifest.py b/src/morphobricks_preprocessing/manifest.py index a1382548..2aef2ad2 100644 --- a/src/morphobricks_preprocessing/manifest.py +++ b/src/morphobricks_preprocessing/manifest.py @@ -34,6 +34,8 @@ from .channel_identity_model import ChannelIdentitySettings, recorded_settings, settings_entry from .description_record import KEY as DESCRIPTION_KEY from .description_record import SectionDigestsError, UnitRecordError, recorded_description +from .ignored_masks import MANIFEST_KEY as IGNORED_KEY +from .ignored_masks import recorded_ignored from .image_qc_record import KEY as IMAGE_QC_KEY from .image_qc_record import recorded_image_qc from .lab_links import KEY as LAB_LINKS_KEY @@ -226,6 +228,9 @@ class RunManifest: image_qc The image QC table written with the run (:mod:`.image_qc_record`: file, SHA-256, metric version and settings); None (key left out) in manifests written before it. + ignored_masks + The mask types the run skipped and the SHA-256 of ``ignored_masks.toml`` + (:mod:`.ignored_masks`, v0.10.1); None (key left out) when the run skipped none. schema_version Version of the histogram table format, as text: ``"6"`` (``"5"`` in a version 5 manifest). @@ -256,6 +261,7 @@ class RunManifest: projection: dict | None = None lab_links: dict | None = None image_qc: dict | None = None + ignored_masks: dict | None = None schema_version: str = str(SCHEMA_VERSION) manifest_version: str = MANIFEST_VERSION @@ -337,6 +343,7 @@ def to_dict(self) -> dict: optional[PROJECTION_KEY] = self.projection optional[LAB_LINKS_KEY] = recorded_lab_links(self.lab_links) optional[IMAGE_QC_KEY] = recorded_image_qc(self.image_qc) + optional[IGNORED_KEY] = recorded_ignored(self.ignored_masks) data.update({key: value for key, value in optional.items() if value is not None}) return data @@ -393,6 +400,7 @@ def from_dict(cls, data: dict) -> RunManifest: projection=recorded_projection(data.get(PROJECTION_KEY)), lab_links=recorded_lab_links(data.get(LAB_LINKS_KEY)), image_qc=recorded_image_qc(data.get(IMAGE_QC_KEY)), + ignored_masks=recorded_ignored(data.get(IGNORED_KEY)), schema_version=str(data["schema_version"]), manifest_version=str(version), ) diff --git a/src/morphobricks_preprocessing/mask_declare.py b/src/morphobricks_preprocessing/mask_declare.py index 982a44b5..58361166 100644 --- a/src/morphobricks_preprocessing/mask_declare.py +++ b/src/morphobricks_preprocessing/mask_declare.py @@ -25,17 +25,28 @@ from __future__ import annotations import os +import shlex import unicodedata from collections.abc import Iterable, Mapping from dataclasses import dataclass, replace from pathlib import Path +from ._io import write_text_atomic +from .describe_ids import reasons from .description import Description, DescriptionError, Mask from .description_rules import REPRESENTATIONS from .draft_ids import id_problems, propose_id +from .ignored_masks import ( + IGNORED_FILENAME, + IgnoredMasksError, + ignored_text, + name_problem, + read_ignored, + unreadable_fix, +) from .run.description_file import Publication, PublicationRefused, publish_description from .run.description_run import load_description -from .run.lock import OutputLockedError +from .run.lock import OutputLockedError, output_lock from .segmentation_record import SegmentationError, check_mask_type_folder @@ -67,15 +78,17 @@ def _mask_id(item: MaskDeclaration) -> str: codes = id_problems("masks", item.mask_id) if codes: raise MaskDeclarationRefused( - f"{item.mask_id!r} cannot be a mask ID: {', '.join(codes)}", tuple(codes) + f"{item.mask_id!r} cannot be a mask ID. {reasons(codes)}", tuple(codes) ) return item.mask_id proposal = propose_id("masks", item.source_type) if proposal is None: codes = id_problems("masks", item.source_type) + example = shlex.quote(f"{item.source_type}=instances:Nuclei") raise MaskDeclarationRefused( - f"The mask type {item.source_type!r} is not a valid mask ID ({', '.join(codes)}): " - f"give its ID (for example --type {item.source_type}=:).", + f"The mask type {item.source_type!r} needs a different ID ({', '.join(codes)}). " + f"Keep its folder name and supply an ID, for example --type {example}, if it " + "contains instance labels.", ("mask_id_needed",), ) return proposal @@ -223,10 +236,102 @@ def declare_masks( return DeclaredMasks(added, publication) +def declared_types(output_folder: str | os.PathLike) -> tuple[str, ...]: + """Return the ``source_type`` of every mask the published description declares (none: ()).""" + found, problems = load_description(Path(output_folder)) + if problems or found is None: + return () + return tuple(sorted({mask.source_type for mask in found.description.masks.values()})) + + +def ignore_masks( + output_folder: str | os.PathLike, + add: Iterable[str] = (), + *, + declared: Iterable[str] = (), +) -> tuple[tuple[str, ...], bool]: + """Add types to the ignore list and take every declared type off it; return list, changed. + + ``declared`` are the ``source_type``s of the published description's masks: a type both + asked to be ignored and declared is refused; one declared and listed is removed (declaring + a type uses it again). The file is written under the output folder's lock, atomically, and + removed when the list becomes empty. Nothing is written when nothing changes. + + Raises + ------ + IgnoredMasksError + A refused name, a declared type asked to be ignored, or a file that cannot be read. + """ + add, declared = tuple(add), set(declared) + folder = check_ignore(output_folder, add, declared=declared, read=False) + with output_lock(folder): + try: + before = read_ignored(folder).types + except IgnoredMasksError as exc: + raise IgnoredMasksError( + f"The ignored-mask list cannot be read: {exc}. {unreadable_fix(folder)}" + ) from exc + after = tuple(sorted((set(before) | set(add)) - declared)) + if after == before: + return after, False + 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)}") + both = sorted(set(add) & declared) + if both: + raise IgnoredMasksError( + f"--ignore {', '.join(both)}: declared in the description, so the run uses it; a " + "declared mask type is not ignored" + ) + folder = Path(output_folder) + if not folder.is_dir(): + raise IgnoredMasksError(f"The output folder {folder} does not exist.") + if read: + try: + read_ignored(folder) + except IgnoredMasksError as exc: + raise IgnoredMasksError( + f"The ignored-mask list cannot be read: {exc}. {unreadable_fix(folder)}" + ) from exc + return folder + + __all__ = [ + "check_ignore", "DeclaredMasks", "MaskDeclaration", "MaskDeclarationRefused", "declare_masks", + "declared_types", + "ignore_masks", "with_declared_masks", ] diff --git a/src/morphobricks_preprocessing/mask_text.py b/src/morphobricks_preprocessing/mask_text.py index 91ecd522..018ee732 100644 --- a/src/morphobricks_preprocessing/mask_text.py +++ b/src/morphobricks_preprocessing/mask_text.py @@ -49,14 +49,17 @@ def mask_summary(masks: MaskInventory) -> str: def mask_report_summary(report: MaskReport) -> str: """Describe the mask types, their relationships and the hierarchy in plain words. - Every statement is a suggestion from the masks' pixels; the text ends by asking the - user to name the masks and check the relationships. + Every statement is measured from the masks' pixels and never replaces the declared + representation; the text ends by saying the relationships are inferred from overlap. """ - lines = [f"Mask types ({plural(report.images, 'image')} scanned):"] + lines = [ + f"Mask properties measured from the pixel values ({plural(report.images, 'image')} " + "scanned). These properties do not replace the declared mask representation.", + ] for name, summary in sorted(report.types.items()): lines.append( - f" {name}: {_MASK_KINDS[summary.kind]}; {plural(summary.objects, 'object')}, " - f"median {summary.median_pieces_per_label:g} piece(s) per label" + f" {name}: {_MASK_KINDS[summary.kind]}; {plural(summary.objects, 'positive label')}; " + f"median {summary.median_pieces_per_label:g} connected piece(s) per label" ) relationships = [pair for pair in report.relationships if pair.relation != "same_objects"] if relationships: @@ -67,15 +70,15 @@ def mask_report_summary(report: MaskReport) -> str: lines += [f" {first} and {second}" for first, second in report.same_objects] ambiguous = mask_ambiguous_lines(report) if ambiguous: - lines += ["", "Objects given no parent (equally in two or more objects of the other mask):"] + lines += ["", "Objects with no assigned parent because of equal overlap:"] lines += [f" {line}" for line in ambiguous] lines += ["", "Hierarchy (direct parents only):"] lines += _hierarchy_lines(report.hierarchy) lines += ["", f"Thresholds: {mask_thresholds_used(report)}"] lines += [ "", - "These are suggestions from the masks' pixels: name each mask, then check the " - "relationships before using them.", + "The relationships above are inferred from spatial overlap. Review them before using " + "them in a biological analysis.", ] return "\n".join(lines) @@ -179,8 +182,9 @@ def mask_ambiguous_lines(report: MaskReport) -> list[str]: the relation of the pair, so every pair is listed, ``none`` included. """ return [ - f"{pair.child} in {pair.parent}: {plural(pair.evidence['ambiguous_parent'], 'object')}" - f" of {pair.evidence['children']:,} equally in two or more {pair.parent}" + f"{pair.child} in {pair.parent}: {pair.evidence['ambiguous_parent']:,} of " + f"{plural(pair.evidence['children'], pair.child + ' label')} overlap two or more " + f"{pair.parent} labels equally; no parent was assigned" for pair in report.pairs if pair.evidence.get("ambiguous_parent") ] @@ -198,9 +202,9 @@ def _relationship_line(pair: PairRelation) -> str: f" {pair.child} {_RELATIONS[pair.relation]} {pair.parent}" f"{'' if pair.direct else ' (through another mask)'}: " f"{e['inside']} of {plural(e['children'], 'object')} inside; " - f"{pair.parent} with 0/1/2/3+ {pair.child}: {e['parents_with_0_children']}/" - f"{e['parents_with_1_child']}/{e['parents_with_2_children']}/" - f"{e['parents_with_3_or_more_children']}" + f"{pair.parent} containing {pair.child}: none = {e['parents_with_0_children']}, " + f"one = {e['parents_with_1_child']}, two = {e['parents_with_2_children']}, three or " + f"more = {e['parents_with_3_or_more_children']}" ) extra = [] if e["outside_parents"]: diff --git a/src/morphobricks_preprocessing/masks/files.py b/src/morphobricks_preprocessing/masks/files.py index edd88303..4c9eaceb 100644 --- a/src/morphobricks_preprocessing/masks/files.py +++ b/src/morphobricks_preprocessing/masks/files.py @@ -49,6 +49,7 @@ def find_masks( output_folder: str | os.PathLike | None = None, bind: bool = False, progress: Callable[[int, int, str], None] | None = None, + ignore: Collection[str] = (), ) -> MaskInventory: """Pair every image with its masks and check them from their headers, without pixels. @@ -83,6 +84,10 @@ def find_masks( Called as ``progress(done, total, mask_path)`` before each mask's header is read, and as ``progress(total, total, "")`` after the last. It changes nothing about the result. + ignore + Mask types (masks-folder types and OME-Zarr label names) the run skips + (``ignored_masks.toml``, :mod:`..ignored_masks`): left out before any check or + header read, compared exactly, as declared types are. Returns ------- @@ -102,6 +107,7 @@ def find_masks( issues.extend(extra) found, unreadable = _label_masks(discovery.root, images) files.extend(found) + files = [f for f in files if f.mask_type not in ignore] issues.extend(_name_issues(files)) issues.extend(_description_name_issues(files)) files.sort(key=lambda f: (f.image, f.mask_type)) diff --git a/src/morphobricks_preprocessing/notebook_run_plan.py b/src/morphobricks_preprocessing/notebook_run_plan.py index 2f97fcfe..2bc54abe 100644 --- a/src/morphobricks_preprocessing/notebook_run_plan.py +++ b/src/morphobricks_preprocessing/notebook_run_plan.py @@ -184,8 +184,9 @@ def _memory_plan(self, review: AxisReview) -> tuple[str, str]: line = ( f"{plural(len(plan.blocked), 'image')} " f"{'has' if len(plan.blocked) == 1 else 'have'} " - f"planes too large to read whole within the memory limit of {limit} (they need " - f"up to {largest}), so they will be read in blocks. The histograms are exactly the " + f"planes too large to measure whole within the memory limit of {limit} " + f"(reading one channel and computing its histogram at once needs up to " + f"{largest}), so they will be read in blocks. The histograms are exactly the " "same; reading takes longer. To read them whole, raise the memory limit to " f"{largest} or more in Settings above (untick Use the recommended " "settings), " diff --git a/src/morphobricks_preprocessing/notebook_tissue_mask.py b/src/morphobricks_preprocessing/notebook_tissue_mask.py index c26ff730..4577417c 100644 --- a/src/morphobricks_preprocessing/notebook_tissue_mask.py +++ b/src/morphobricks_preprocessing/notebook_tissue_mask.py @@ -159,7 +159,7 @@ def _children(self) -> list[widgets.Widget]: return [ ui.help_text( "Writes a new region mask that leaves out nuclei, red blood cells and " - "empty space of H&E images, with a fixed rule (he_tissue_v1, " + "empty space of H&E images, with a fixed rule (he_tissue_v2, " "provisional; not a trained segmentation). The images are only read and nothing " "is overwritten. Each file gets a line in mask_lineage.jsonl. Declare the " "new mask as binary, run again and describe the masks before a brick uses it." diff --git a/src/morphobricks_preprocessing/ome_zarr_copy.py b/src/morphobricks_preprocessing/ome_zarr_copy.py index 0c5e2a6a..3b1447b3 100644 --- a/src/morphobricks_preprocessing/ome_zarr_copy.py +++ b/src/morphobricks_preprocessing/ome_zarr_copy.py @@ -8,8 +8,15 @@ The store is written directly (no ``zarr`` package is needed to write it; reading it needs the ``zarr`` extra, as for any OME-Zarr image): a Zarr version 2 group with one array ``0``, -uncompressed, one chunk per plane (the whole Y and X), little-endian, so every plane has a -fixed file and the same copy is the same bytes. Each plane is the plane read under the +uncompressed, little-endian, in chunks of one plane by at most :data:`CHUNK_SIDE` rows and +columns (``1 x ... x 1024 x 1024``, :func:`chunk_shape`), so every chunk has a fixed file and +the same copy is the same bytes. Spatial chunks let a later brick read a window of a large +image by decoding only the chunks under it (:mod:`.window_reader`): a whole plane in one chunk +had to be decoded whole for every window, which no memory limit could serve on a slide +(v0.10.1). Each plane is written as it is read, block by block (:meth:`.planes.Plane.blocks`, +within the memory limit), each block's part of each chunk written in place: a plane is never +held whole unless it is read whole. One level only (no pyramid): the brick reads level 0 alone +(:data:`.windows.LEVEL`). Each plane is the plane read under the confirmed roles, bit for bit; a projected copy's planes are computed as in :func:`.ome_tiff_copy.write_projected_copy`. The metadata follow the copy's layout (:class:`.copy_axes.CopyLayout`): the axes by role with their units, the level-0 ``scale`` from @@ -31,6 +38,7 @@ import os from dataclasses import replace from pathlib import Path +from typing import BinaryIO import numpy as np @@ -53,6 +61,12 @@ NGFF_VERSION = "0.4" _AXIS_TYPES = {"T": "time", "C": "channel", "Z": "space", "Y": "space", "X": "space"} BITS_NOT_WRITTEN = "OME-NGFF 0.4 has no field for significant bits" +CHUNK_SIDE = 1024 +"""The largest chunk along Y and along X of an OME-Zarr copy (one plane along every other axis). + +1024 x 1024 is bioformats2raw's default and common practice for OME-NGFF 0.4 images: 1 MiB +(``uint8``) to 8 MiB (``float64``) per chunk, so a window reader decodes a few MiB per chunk it +touches, while a slide of 100,000 x 100,000 pixels has about 10,000 chunk files per plane.""" OMERO_COLOUR = "FFFFFF" """The ``color`` of every ``omero`` channel (required by OME-NGFF 0.4; display only).""" @@ -141,6 +155,12 @@ def _json(path: Path, data: dict) -> None: path.write_bytes(text.encode("utf-8")) +def chunk_shape(shape: tuple[int, ...]) -> tuple[int, ...]: + """Return the chunks of a copy of ``shape``: 1 along each leading axis, at most 1024 in Y, X.""" + *leading, rows, cols = shape + return (*([1] * len(leading)), min(rows, CHUNK_SIDE), min(cols, CHUNK_SIDE)) + + def _lay_out(target: Path, layout: CopyLayout, dtype: np.dtype, description: str | None) -> Path: """Write the store's metadata and return the folder of the array's chunks.""" target.mkdir(parents=True) @@ -148,14 +168,13 @@ def _lay_out(target: Path, layout: CopyLayout, dtype: np.dtype, description: str array.mkdir() _json(target / ".zgroup", {"zarr_format": 2}) _json(target / ".zattrs", _metadata(layout, dtype, description)) - rows, cols = layout.plane_shape stored = dtype.newbyteorder("<") if dtype.itemsize > 1 else dtype _json( array / ".zarray", { "zarr_format": 2, "shape": list(layout.shape), - "chunks": [*([1] * (len(layout.shape) - 2)), rows, cols], + "chunks": list(chunk_shape(layout.shape)), "dtype": stored.str, "compressor": None, "filters": None, @@ -167,11 +186,68 @@ def _lay_out(target: Path, layout: CopyLayout, dtype: np.dtype, description: str return array -def _chunk_path(array: Path, position: tuple[int, ...]) -> Path: - """Return the file of the plane at ``position`` (its leading indices), making its folder.""" - path = array.joinpath(*(str(i) for i in position), "0", "0") - path.parent.mkdir(parents=True, exist_ok=True) - return path +class _PlaneChunks: + """The chunk files of one plane, written in place block by block (never the whole plane). + + Each chunk file is created at its full size (an edge chunk too, as Zarr version 2 stores + it, its outside zero, the ``fill_value``) the first time a block reaches it; each block's + part of it is written at its place. Files of the chunk rows a block no longer reaches are + closed, so a plane read in bands holds about two rows of chunk files open at once. + """ + + def __init__( + self, array: Path, position: tuple[int, ...], chunks: tuple[int, int], dtype: np.dtype + ) -> None: + self.folder = array.joinpath(*(str(i) for i in position)) + self.chunks, self.itemsize = chunks, dtype.itemsize + self.open: dict[tuple[int, int], BinaryIO] = {} + self.made: set[tuple[int, int]] = set() + + def _file(self, key: tuple[int, int]) -> BinaryIO: + """Return the open file of the chunk at ``key`` (its grid row and column).""" + stream = self.open.get(key) + if stream is not None: + return stream + path = self.folder / str(key[0]) / str(key[1]) + if key in self.made: + stream = open(path, "r+b") + else: + path.parent.mkdir(parents=True, exist_ok=True) + stream = open(path, "w+b") + stream.truncate(self.chunks[0] * self.chunks[1] * self.itemsize) + self.made.add(key) + self.open[key] = stream + return stream + + def _drop(self, below: int) -> None: + """Close the files of the chunk rows above grid row ``below``.""" + for key in [key for key in self.open if key[0] < below]: + self.open.pop(key).close() + + def write(self, y: int, x: int, pixels: np.ndarray) -> None: + """Write the stored values ``pixels`` (little-endian) at row ``y`` and column ``x``.""" + ch, cw = self.chunks + height, width = pixels.shape + self._drop(y // ch) + for gy in range(y // ch, -(-(y + height) // ch)): + a, b = max(y, gy * ch), min(y + height, (gy + 1) * ch) + for gx in range(x // cw, -(-(x + width) // cw)): + c, d = max(x, gx * cw), min(x + width, (gx + 1) * cw) + part = pixels[a - y : b - y, c - x : d - x] + stream = self._file((gy, gx)) + start = ((a - gy * ch) * cw + (c - gx * cw)) * self.itemsize + if d - c == cw: # whole chunk rows: one contiguous run of the file + stream.seek(start) + stream.write(memoryview(np.ascontiguousarray(part)).cast("B")) + continue + for r in range(b - a): + stream.seek(start + r * cw * self.itemsize) + stream.write(memoryview(np.ascontiguousarray(part[r])).cast("B")) + + def close(self) -> None: + """Close every chunk file still open.""" + while self.open: + self.open.popitem()[1].close() def _little(pixels: np.ndarray, dtype: np.dtype) -> np.ndarray: @@ -219,18 +295,16 @@ def write_named_zarr( """ dtype = np.dtype(dtype) array = _lay_out(Path(target), layout, dtype, layout.description) - rows, cols = layout.plane_shape + chunks = chunk_shape(layout.shape)[-2:] roles = [role.lower() for role in layout.axes[:-2]] - row_nbytes = cols * dtype.itemsize for plane in iter_planes(source, mapping, memory_limit=memory_limit): position = tuple(int(plane.coordinates[role]) for role in roles) - with open(_chunk_path(array, position), "wb") as stream: - stream.truncate(rows * row_nbytes) + files = _PlaneChunks(array, position, chunks, dtype) + try: for block in plane.blocks(): - pixels = _little(block.pixels, dtype) - for r in range(pixels.shape[0]): - stream.seek((block.y + r) * row_nbytes + block.x * dtype.itemsize) - stream.write(memoryview(pixels[r]).cast("B")) + files.write(block.y, block.x, _little(block.pixels, dtype)) + finally: + files.close() def write_projected_zarr( @@ -256,6 +330,7 @@ def write_projected_zarr( start, stop = details.z_range out = np.dtype(details.output_dtype) array = _lay_out(Path(target), layout, out, projection_description(details)) + chunks = chunk_shape(layout.shape)[-2:] roles = [role.lower() for role in layout.axes[:-2]] has_z = mapping.index_of("Z") is not None for position in np.ndindex(*layout.shape[:-2]): @@ -275,12 +350,16 @@ def write_projected_zarr( if plane.pixels is None: raise CopyWriteError(f"a plane of {source} does not fit the memory limit") running.add(plane.pixels) - pixels = _little(running.result(), out) - _chunk_path(array, tuple(int(i) for i in position)).write_bytes(pixels.tobytes()) + files = _PlaneChunks(array, tuple(int(i) for i in position), chunks, out) + try: + files.write(0, 0, _little(running.result(), out)) + finally: + files.close() __all__ = [ "BITS_NOT_WRITTEN", + "CHUNK_SIDE", "NGFF_VERSION", "OMERO_COLOUR", "OME_TIFF", @@ -288,6 +367,7 @@ def write_projected_zarr( "STORES", "ZARR_COPY_SUFFIX", "as_zarr_copy", + "chunk_shape", "write_named_zarr", "write_projected_zarr", "zarr_copy_name", diff --git a/src/morphobricks_preprocessing/physical_check.py b/src/morphobricks_preprocessing/physical_check.py index 8b3bc622..66914674 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`` in the masks folder, or an + OME-Zarr label image) must be the ``source_type`` of a declared mask. Only names are compared. + """ + known = {mask.source_type for mask in description.masks.values()} + return [ + 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/plane_channels.py b/src/morphobricks_preprocessing/plane_channels.py index a7be09a4..15ed1af0 100644 --- a/src/morphobricks_preprocessing/plane_channels.py +++ b/src/morphobricks_preprocessing/plane_channels.py @@ -87,6 +87,13 @@ def xyc_plane_memory( ) -> int: """Return the working memory :func:`read_xyc_plane` checks, from the header only. + This is the memory of reading the pixels of ``channel_count`` channels into one + ``(C, Y, X)`` array, with no histogram. It is not a run's measuring memory + (:attr:`.planes.PlaneLayout.memory_estimate`, the figure of ``planes_read_in_blocks``: + one channel read and its histogram and image QC computed), so the two figures differ + for the same plane: for the 30720 x 36864 x 3 ``uint16`` mosaic in 1024 x 1024 chunks, + about 14.8 GiB here and 38.0 GiB for the run (most of it the histogram's arrays). + ``channel_count`` defaults to the image's channel count (1 without a channel axis). For TIFF the bound is of the pages holding the plane at ``z`` and ``t``, sized from their own strip or tile byte counts (pages can compress very differently). The request is checked @@ -248,7 +255,8 @@ def _refuse_over(memory: int, layout: PlaneLayout, count: int, path: str | os.Pa return channels = "its channel" if count == 1 else f"all {count} channels" raise PlaneMemoryError( - f"Reading one plane of {Path(path).name} whole, {channels}, needs about " + f"Reading one plane of {Path(path).name} whole, {channels} into one array (the " + f"pixels only: no histogram is computed), needs about " f"{format_bytes(memory)} of working memory, more than the limit of " f"{format_bytes(layout.memory_limit)}. Raise the memory limit if this computer " "has enough memory, or read the plane in windows." diff --git a/src/morphobricks_preprocessing/planes.py b/src/morphobricks_preprocessing/planes.py index dc976fce..6a0ba7b0 100644 --- a/src/morphobricks_preprocessing/planes.py +++ b/src/morphobricks_preprocessing/planes.py @@ -296,8 +296,8 @@ class PlaneLayout: Size of a page as stored in the file (compressed size, if compressed); 0 for OME-Zarr, whose compressed chunk sizes are not known in advance. memory_estimate - Estimated working memory to read one whole plane and, except for - :func:`read_plane`, compute its histogram, in bytes. + Working memory to read one whole plane of one channel and (except for :func:`read_plane`) + compute its histogram and QC, in bytes; not :func:`.plane_channels.xyc_plane_memory`. memory_limit The memory limit the layout was worked out for, in bytes. block_shape @@ -651,10 +651,10 @@ def check_planes( issues.append( warning( "planes_read_in_blocks", - f"The planes of {plural(len(blocked), 'image')} are too large to read whole " - f"within the memory limit of {format_bytes(memory_limit)} (they would need up " - f"to {format_bytes(largest)}), so they will be read in blocks. The histograms " - "are exactly the same; reading takes longer.", + f"The planes of {plural(len(blocked), 'image')} are too large to measure whole " + f"within the limit of {format_bytes(memory_limit)}: one channel and its histogram " + f"would need up to {format_bytes(largest)}, so blocks are read (exactly the same " + "histograms). Reading all channels without a histogram needs another amount.", [rel for rel, _ in blocked], "Nothing needs to be done. To read the planes whole, which is faster, raise " f"the memory limit to {format_bytes(largest)} or more if this computer has " diff --git a/src/morphobricks_preprocessing/projection_issues.py b/src/morphobricks_preprocessing/projection_issues.py index e608c555..046c8ce7 100644 --- a/src/morphobricks_preprocessing/projection_issues.py +++ b/src/morphobricks_preprocessing/projection_issues.py @@ -29,8 +29,8 @@ def nothing_to_project_issue(roles: str) -> ValidationIssue: f"--project was given, but no image has a depth axis (Z) under the roles {roles}. " "Nothing was written.", [], - "Check the roles: Z must be the axis of the slices of a stack, and every image is " - "otherwise left as it is.", + "Check the stored axis order: Z must be the axis of the slices of a stack. If these " + "images have no depth dimension, omit --project.", ) @@ -77,7 +77,8 @@ def over_memory_issue(path: str, needed: str, limit: str, count: int) -> Validat f"Projecting {path}{more} needs {needed} for one plane and its running total; the " f"limit is {limit}. Nothing was written.", [path], - "Raise the memory limit (--memory-limit).", + "Increase --memory-limit only if sufficient RAM is available, or export smaller images " + "for projection.", ) @@ -85,10 +86,11 @@ def zarr_issue(paths: Sequence[str]) -> ValidationIssue: """Refuse OME-Zarr images in a projection (they are not projected yet).""" return error( "projection_zarr_not_supported", - f"{plural(len(paths), 'OME-Zarr image')} cannot be projected yet: a projected copy is " - "an OME-TIFF, and the copy tree keeps each image's path. Nothing was written.", + "Projection of OME-Zarr source images is not supported in this release " + f"({plural(len(paths), 'OME-Zarr image')}). No projected copies were written.", paths, - "Exclude these images, or project the TIFF images in a separate experiment folder.", + "Export suitable TIFF copies of these images before projection, or process the TIFF " + "images separately.", ) @@ -102,7 +104,10 @@ def masks_3d_issue(by_type: Mapping[str, Sequence[str]]) -> ValidationIssue: "Masks are never projected: a projected label image merges different objects. " "Nothing was written.", paths, - "Make 2-D masks on the projected images, or move these masks out of the masks folder.", + "Existing 3-D masks cannot be used with this projection. Keep the original masks " + "separately, outside the masks folder, then convert the images without those 3-D masks. " + "Create new 2-D masks from the projected images and register them with the new " + "experiment.", ) @@ -114,7 +119,8 @@ def masks_axes_unknown_issue(paths: Sequence[str]) -> ValidationIssue: "are not named, so it is not known whether they have depth slices (Z). Masks are " "never projected, and no axis is guessed. Nothing was written.", paths, - "Name the axes in the masks' metadata, or move these masks out of the masks folder.", + "Check and export the mask axes correctly. If these masks belong to the original 3-D " + "images, keep them separate from the projected experiment.", ) diff --git a/src/morphobricks_preprocessing/report.py b/src/morphobricks_preprocessing/report.py index bdf97015..95af6798 100644 --- a/src/morphobricks_preprocessing/report.py +++ b/src/morphobricks_preprocessing/report.py @@ -238,11 +238,12 @@ def _stopped_summary(result: RunResult) -> str: if result.report_written: written.append(f"{REPORT_FILENAME} and {REPORT_TEXT_FILENAME} (the report)") lines = [ - f"The run stopped ({issue_counts(result.issues)}): no table or manifest was written.", + f"Preprocessing stopped ({issue_counts(result.issues)}). No new histogram table or run " + "manifest was published; existing results from an earlier successful run were kept.", f"Written to {result.output_folder}: {', '.join(written)}." if written else "Nothing was written.", - "Resolve the errors and run again.", + "Review the errors, correct the problems and run again.", ] return "\n".join(lines) diff --git a/src/morphobricks_preprocessing/required_description.py b/src/morphobricks_preprocessing/required_description.py index 7b7add8f..168f8369 100644 --- a/src/morphobricks_preprocessing/required_description.py +++ b/src/morphobricks_preprocessing/required_description.py @@ -3,14 +3,15 @@ A run without a published ``morphobricks.toml`` in its output folder is refused on every route (the notebook, the command line's ``check``, ``run`` and ``masks``, :func:`.run.run_experiment`, :func:`.run.mask_step.prepare_mask_step` and :class:`.run_inputs.RunInputs`) with the one code -``A_DESCRIPTION_REQUIRED``, naming the fix: describe the experiment (the notebook's describe -steps; the command line's ``describe`` shows what is still open). Nothing is taken from folder +``A_DESCRIPTION_REQUIRED``, naming the fix: describe the experiment, in the notebook's describe +steps or with the command line's ``describe --publish`` (both named). Nothing is taken from folder names in its place and there is no undescribed run. """ from __future__ import annotations import os +import shlex from pathlib import Path from typing import Literal @@ -22,12 +23,33 @@ DESCRIPTION_REQUIRED = "A_DESCRIPTION_REQUIRED" """The refusal of a run without a published description (ADR 0002 AR11 ruling 1).""" -FIX = ( - "Describe the experiment first: run the notebook's describe steps and save the " - "description (Check and save), which publishes morphobricks.toml in the output folder. " - "The command line's 'describe' shows what is still to be answered." +_EXAMPLE = ( + "morphobricks-preprocessing describe my_experiment{output} --channels COL,FN " + "--image-type channels --accept-ids --comparable --confirmed-on 2026-12-04 --publish" ) -"""What the user does about it: the notebook's describe steps or the command line's ``describe``.""" +_FIX = ( + "Describe the experiment before running preprocessing. Start with the command below, " + "replacing EXPERIMENT with your images folder, and review the proposed IDs and channel " + "order:\n" + " morphobricks-preprocessing describe EXPERIMENT{output}\n" + "To publish a simple two-channel fluorescence experiment, use the following example, " + "replacing my_experiment, the channels and the confirmation date with your own:\n" + " {example}\n" + "If your acquisitions have different channel lists or orders, describe them in the notebook " + "instead." +) +FIX = _FIX.format(output="", example=_EXAMPLE.format(output="")) + ( + " Add --output with your output folder to both commands when it is not the default one." +) +"""What the user does about it: either route publishes (owner, 4 December 2026): the notebook's +describe steps, or the command line's ``describe --publish`` (fast mode). Placeholders are +named in words, never as shell-unsafe text such as ``a|b`` (external review, 4 December 2026).""" + + +def fix_text(output_folder: str | os.PathLike) -> str: + """Return :data:`FIX` naming the refused output folder in both commands (``--output``).""" + output = f" --output {shlex.quote(Path(output_folder).as_posix())}" + return _FIX.format(output=output, example=_EXAMPLE.format(output=output)) def is_published(output_folder: str | os.PathLike) -> bool: @@ -53,7 +75,7 @@ def description_required_issue(output_folder: str | os.PathLike) -> ValidationIs DESCRIPTION_REQUIRED, required_message(output_folder), [Path(output_folder).as_posix()], - FIX, + fix_text(output_folder), ) diff --git a/src/morphobricks_preprocessing/run/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/src/morphobricks_preprocessing/run/outputs.py b/src/morphobricks_preprocessing/run/outputs.py index bc6e9e60..45960be3 100644 --- a/src/morphobricks_preprocessing/run/outputs.py +++ b/src/morphobricks_preprocessing/run/outputs.py @@ -88,6 +88,7 @@ def write_generation( experiment_description=manifest_entry(described, masks, run.output, len(rows.entries)), lab_links=None if run.lab_links is None else run.lab_links.to_dict(), image_qc=image_qc_entry(qc_sha256), + ignored_masks=pre.ignored.to_manifest(), manifest_version=MANIFEST_VERSION, ) manifest = _kept_time(manifest, run.previous[0]) diff --git a/src/morphobricks_preprocessing/run/preflight.py b/src/morphobricks_preprocessing/run/preflight.py index 39617500..e8640802 100644 --- a/src/morphobricks_preprocessing/run/preflight.py +++ b/src/morphobricks_preprocessing/run/preflight.py @@ -26,6 +26,13 @@ from ..dataset import DatasetReport, check_dataset from ..discovery import DiscoveryResult, default_output_folder, discover_experiment from ..fingerprint import Fingerprint, current_fingerprint +from ..ignored_masks import ( + IGNORED_FILENAME, + IgnoredMasks, + IgnoredMasksError, + read_ignored, + unreadable_fix, +) from ..mask_names import MASK_NAME_CODES, mask_name_issues from ..masks import MaskFile, MaskInventory, find_masks from ..metadata import ( @@ -88,6 +95,11 @@ class Preflight: headers_reused The images whose header was taken from a recorded check (``recorded`` of :func:`preflight`) instead of being read again, sorted; empty otherwise. + ignored + The mask types and label images the output folder's ``ignored_masks.toml`` lists + (:mod:`..ignored_masks`), left out of :attr:`masks`; empty without the file. + ignored_issues + The error ``ignored_masks_invalid`` when that file cannot be read as written. """ discovery: DiscoveryResult @@ -101,6 +113,8 @@ class Preflight: conversion: ConversionReview | None = None header_fingerprints: Mapping[str, Fingerprint | None] = field(default_factory=dict) headers_reused: tuple[str, ...] = () + ignored: IgnoredMasks = field(default_factory=IgnoredMasks) + ignored_issues: tuple[ValidationIssue, ...] = () @property def issues(self) -> tuple[ValidationIssue, ...]: @@ -112,6 +126,7 @@ def issues(self) -> tuple[ValidationIssue, ...]: *self.dataset.issues, *(self.masks.issues if self.masks is not None else ()), *(self.conversion.issues if self.conversion is not None else ()), + *self.ignored_issues, ] return tuple(sorted(merged, key=lambda issue: not issue.is_error)) @@ -251,6 +266,7 @@ def preflight( inspected, bound, reused = _inspected(root, images, bind_headers, progress, recorded or {}) metadata, calibration = _calibrated(inspected, discovery.images, output) report("masks", 0, 1, "") + ignored, ignored_issues = _ignored(output) masks = _masks( discovery, metadata, @@ -259,6 +275,7 @@ def preflight( output, bind_headers, lambda done, total, path: report("masks", done, total, path), + ignored.types, ) report("masks", 1, 1, "") # Each part of the comparison is reported, n of N (#579: the line seemed stuck). @@ -283,11 +300,28 @@ def preflight( conversion=conversion, header_fingerprints=bound, headers_reused=reused, + ignored=ignored, + ignored_issues=ignored_issues, ) report("acquisitions", total, total, "") return result +def _ignored(output: Path) -> tuple[IgnoredMasks, tuple[ValidationIssue, ...]]: + """Return the output folder's ignored mask types, or the error of a file that is invalid.""" + try: + return read_ignored(output), () + except (IgnoredMasksError, OSError) as exc: + return IgnoredMasks(), ( + error( + "ignored_masks_invalid", + f"The ignored-mask list cannot be read: {exc}", + [IGNORED_FILENAME], + unreadable_fix(output), + ), + ) + + ACQUISITION_PARTS = ( "the axes every header suggests", "the images per condition and repeat", @@ -406,8 +440,12 @@ def _masks( output: Path, bind: bool = False, progress: Callable[[int, int, str], None] | None = None, + ignore: tuple[str, ...] = (), ) -> MaskInventory | None: - """Pair the analysed images with their masks; None without masks folder or label image.""" + """Pair the analysed images with their masks; None without masks folder or label image. + + The types in ``ignore`` (``ignored_masks.toml``) are left out before any header is read. + """ masks = find_masks( masks_folder, discovery, @@ -416,6 +454,7 @@ def _masks( output_folder=output, bind=bind, progress=progress, + ignore=ignore, ) if masks_folder is None and not masks.files and not masks.issues: return None # no masks folder and no label images: the run has no masks diff --git a/src/morphobricks_preprocessing/run/steps.py b/src/morphobricks_preprocessing/run/steps.py index e5667a47..0978a5d3 100644 --- a/src/morphobricks_preprocessing/run/steps.py +++ b/src/morphobricks_preprocessing/run/steps.py @@ -28,6 +28,7 @@ from ..planes import check_planes from ..source_content import with_content from ..validation import ValidationIssue, error, has_errors, plural +from ..window_chunks import check_window_chunks from .entries import Comparison, compare_with_previous, file_entries from .modes import FULL from .phases import CONTENTS @@ -142,6 +143,8 @@ def header_checks( histogram_settings=inputs.histogram_settings, ) ) + # Chunks too large for a later brick's windows are named before the run (v0.10.1). + issues.extend(check_window_chunks(root, review, memory_limit=memory_limit)) return Checked(review, type_review, design, issues, bins) diff --git a/src/morphobricks_preprocessing/run_inputs.py b/src/morphobricks_preprocessing/run_inputs.py index 70a9ed4b..8ff8a42d 100644 --- a/src/morphobricks_preprocessing/run_inputs.py +++ b/src/morphobricks_preprocessing/run_inputs.py @@ -52,6 +52,7 @@ from .design import DESIGN_FILENAME from .fingerprint import Fingerprint from .folder_rules import masks_folder_issues +from .ignored_masks import IGNORED_FILENAME, ignored_sha256 from .links import LinkRefusedError from .manifest import ( MANIFEST_FILENAME, @@ -310,6 +311,8 @@ def _read( design = published_path(output, DESIGN_FILENAME, manifest.experiment_design_sha256) check_sha(design, manifest.experiment_design_sha256) check_calibration(output / CALIBRATION_FILENAME, manifest.calibration_sha256) + # The list of skipped mask types, as the run read it (changed, added or removed: stale). + check_calibration(output / IGNORED_FILENAME, ignored_sha256(manifest)) description = check_description(output, manifest) # A_DRAFT_REFUSED, or changed check_section_digests(manifest, description) # the digests a consumer keys on (#490) check_channel_coverage(manifest, description) # recorded as the description's (#490) diff --git a/src/morphobricks_preprocessing/run_inputs_text.py b/src/morphobricks_preprocessing/run_inputs_text.py index f622b4e8..0d0e0ca5 100644 --- a/src/morphobricks_preprocessing/run_inputs_text.py +++ b/src/morphobricks_preprocessing/run_inputs_text.py @@ -7,6 +7,8 @@ from __future__ import annotations +import re +from importlib.metadata import PackageNotFoundError, version from typing import TYPE_CHECKING from .validation import plural @@ -30,10 +32,36 @@ def _without_axes_text(paths: list[str]) -> str: ) +REPOSITORY = "git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git" + + +def zarr_install_line(installed: str | None) -> str: + """Return the install command of the ``zarr`` extra for the installed release. + + A release version (``X.Y.Z``) names its tag, so the extra comes with the same release; any + other version (a development build, or none known) gets the unpinned extra and says so. + """ + if installed is not None and re.fullmatch(r"\d+\.\d+\.\d+", installed): + pinned = f"morphobricks-preprocessing[zarr] @ {REPOSITORY}@v{installed}" + return f'python -m pip install "{pinned}"' + return ( + 'python -m pip install "morphobricks-preprocessing[zarr]" (install the same release ' + "of morphobricks-preprocessing as the one you use)" + ) + + +def _installed() -> str | None: + """Return the installed version of this package, or None when it is not known.""" + try: + return version("morphobricks-preprocessing") + except PackageNotFoundError: + return None + + _ZARR_MISSING = ( "The run holds OME-Zarr images, and the zarr package is not installed, so their label " "images cannot be checked against the run (none is ever skipped). Install it with: " - 'pip install "morphobricks-preprocessing[zarr]"' + f"{zarr_install_line(_installed())}" ) diff --git a/src/morphobricks_preprocessing/run_inputs_tissue.py b/src/morphobricks_preprocessing/run_inputs_tissue.py index 6c4367cf..0edf4601 100644 --- a/src/morphobricks_preprocessing/run_inputs_tissue.py +++ b/src/morphobricks_preprocessing/run_inputs_tissue.py @@ -15,21 +15,21 @@ from .he_tissue_mask import TissueMaskPreview, TissueMaskResult from .run_inputs import Fov -HE_TISSUE_V1 = "he_tissue_v1" -"""The default rule (provisional; :mod:`.he_tissue_rule`).""" +HE_TISSUE_V2 = "he_tissue_v2" +"""The default rule (provisional; :mod:`.he_tissue_rule`; ``he_tissue_v1`` on request).""" class TissueMaskInputs: """The H&E tissue mask helper of ``RunInputs`` (mixed into it).""" def he_tissue_mask( - self, fov: Fov | str, *, output_mask_id: str, rule: str = HE_TISSUE_V1 + self, fov: Fov | str, *, output_mask_id: str, rule: str = HE_TISSUE_V2 ) -> TissueMaskResult: """Write one RGB position's H&E tissue mask as a new ``binary`` region mask. The position is resolved from this run by its image path (a ``Fov``'s other attributes - are ignored). The rule ``he_tissue_v1`` is **provisional** and fixed: it leaves out - nuclei, red blood cells and empty space, sizes in pixels, colour maths from + are ignored). The rule (``he_tissue_v2`` by default) is **provisional** and fixed: it + leaves out nuclei, red blood cells and empty space, sizes in pixels, colour maths from normalization. The output goes to ``//...`` with its line of ``mask_lineage.jsonl``; declare it ``representation = "binary"``, run preprocessing and the masks step again, and use it as a region: in memory, never pass it as @@ -42,7 +42,8 @@ def he_tissue_mask( output_mask_id The new mask ID (experiment-v1 section 3.2), typed by the user. rule - The rule ID; ``"he_tissue_v1"`` is the only one. + The rule ID: ``"he_tissue_v2"`` (the default: the white estimated from the + plane) or ``"he_tissue_v1"`` (the white fixed at 255). Returns ------- @@ -63,7 +64,7 @@ def he_tissue_mask( return he_tissue_mask(self, fov, output_mask_id=output_mask_id, rule=rule) def preview_he_tissue_mask( - self, fov: Fov | str, *, rule: str = HE_TISSUE_V1 + self, fov: Fov | str, *, rule: str = HE_TISSUE_V2 ) -> TissueMaskPreview: """Compute one RGB position's H&E tissue mask in memory; nothing is written. @@ -83,9 +84,26 @@ def preview_he_tissue_mask( return preview(self, fov, rule=rule) -PROVISIONAL_NOTE = ( - "Sizes are in pixels. Fixed rule he_tissue_v1 (provisional), not a trained segmentation." -) +def provisional_note(rule: str) -> str: + """Return the note naming the tissue-mask ``rule`` actually used (review P1.14). + + Parameters + ---------- + rule + The rule the masks are computed with, for example ``he_tissue_v1``. + + Returns + ------- + str + """ + return ( + f"Tissue-mask rule: {rule} (provisional, a fixed rule, not a trained segmentation). " + "All spatial thresholds are in pixels. Inspect the resulting masks before analysis." + ) + + +PROVISIONAL_NOTE = provisional_note(HE_TISSUE_V2) +"""The note of the default rule (the notebook's previews use it).""" NOT_REUSED = "this mask will not be reused on retry" """Said whenever a code identity is unverified (the mask is written but never reused).""" @@ -95,20 +113,32 @@ def rgb_positions(run: object) -> tuple[str, ...]: return tuple(fov.relative_path for fov in run.fovs() if fov.image_type == "rgb") -def tissue_next_steps(mask_ids: Iterable[str], masks_root: object) -> str: - """Return what to do with the tissue masks written: declare, run again, use as a region.""" +def tissue_next_steps( + mask_ids: Iterable[str], masks_root: object, commands: Iterable[str] = () +) -> str: + """Return what to do with the tissue masks written: declare, run again, use as a region. + + ``commands`` are the command lines that declare the masks and run again (the command line's + ``tissue-mask`` gives them); without them the steps are said in words (the notebook). + The region is named as a brick's settings name it (``region_mask``), never as Python. + """ ids = sorted(set(mask_ids)) if not ids: return "No mask was written." - lines = [f"Written to the masks folder {masks_root}. Next:"] - lines += [ - f"- declare the mask {mask_id} (source type {mask_id}) as binary, with source_channels = " - '["R", "G", "B"]' - for mask_id in ids + lines = [ + f"Masks saved in the masks folder {masks_root}.", + "Inspect representative images with their masks overlaid (in Fiji or QuPath). Check " + "that the retained regions are the tissue you intend to measure. If the masks are " + "suitable, register and check them:", ] - lines.append("- then run preprocessing and the masks step again to check them.") + commands = list(commands) + if commands: + lines += [f" {command}" for command in commands] + else: + lines += [f"- declare the mask {mask_id} as binary" for mask_id in ids] + lines.append("- then run preprocessing and the masks step again to check them.") lines.append( - "- use it as a region (for example fiberfeatures MaskRequest(, 'region')); in " - "memory, never pass it as cell-mode labels." + f'- use it as a region: in the next brick\'s settings, region_mask = "{ids[0]}" (for ' + "example fiberfeatures); never as cell-mode labels." ) return "\n".join(lines) diff --git a/src/morphobricks_preprocessing/tissue_masks_folder.py b/src/morphobricks_preprocessing/tissue_masks_folder.py new file mode 100644 index 00000000..679df93a --- /dev/null +++ b/src/morphobricks_preprocessing/tissue_masks_folder.py @@ -0,0 +1,98 @@ +"""A masks folder for ``tissue-mask`` when the run has none (owner, 4 December 2026). + +The H&E tissue mask is written into the run's masks folder only (Spec ADR 0005 BM15). A run +of scanner images often has no masks: before v0.10.1 the command then stopped with "Run +preprocessing with a masks folder first". Now it creates one, an empty folder beside the +experiment (``_masks``) or the one ``--masks`` names, and records it the way +``run --masks FOLDER`` records a masks folder: by running preprocessing again on the output +folder with that masks folder and every other setting as the earlier run recorded +(:func:`.run.pipeline.run_experiment`; unchanged images are not read again). A folder that +already exists is never adopted silently: it must be empty, as a new one is. + +Nothing is created when the run is refused: a folder this module created is removed again. +""" + +from __future__ import annotations + +import os +import shlex +from dataclasses import dataclass +from pathlib import Path + +from .report import format_issues +from .run import run_experiment +from .run_inputs import RunInputs +from .validation import has_errors + +MASKS_SUFFIX = "_masks" +"""The name of the default masks folder: the experiment folder's name and this suffix.""" + + +class MasksFolderRefused(ValueError): + """Raised when no masks folder can be created and recorded; nothing was left behind.""" + + +@dataclass(frozen=True) +class CreatedFolder: + """A masks folder created and recorded for the run; ``run`` is the run opened again.""" + + folder: Path + run: RunInputs + + +def default_masks_folder(experiment_root: Path) -> Path: + """Return the masks folder created by default: ``_masks`` beside it.""" + return experiment_root.parent / f"{experiment_root.name}{MASKS_SUFFIX}" + + +def create_masks_folder(run: RunInputs, folder: str | os.PathLike | None) -> CreatedFolder: + """Create an empty masks folder and record it for the run; return it and the run again. + + Parameters + ---------- + run + The opened run, which records no masks folder. + folder + Where to create it, or None for :func:`default_masks_folder`. + + Raises + ------ + MasksFolderRefused + When the folder exists and is not empty, cannot be created, or the run with it is + refused (its issues in the message). A folder created here is removed again. + """ + target = Path(folder).resolve() if folder else default_masks_folder(run.experiment_root) + created = not target.exists() + if not created and (not target.is_dir() or any(target.iterdir())): + output, masks = shlex.quote(str(run.output_folder)), shlex.quote(str(target)) + raise MasksFolderRefused( + f"{target} already exists and is not an empty folder. Choose another empty folder " + "with --masks. If this is your experiment's existing masks folder, register it " + f"using morphobricks-preprocessing run --output {output} --masks {masks} before " + "retrying." + ) + try: + target.mkdir(parents=True, exist_ok=True) + except OSError as exc: + raise MasksFolderRefused( + f"The masks folder {target} cannot be created ({exc.strerror or exc})." + ) from exc + result = run_experiment(output_folder=run.output_folder, masks_folder=target) + if has_errors(result.issues): + if created: + target.rmdir() + errors = [issue for issue in result.issues if issue.is_error] + raise MasksFolderRefused( + f"The run with the masks folder {target} was refused, so no masks folder was " + f"recorded:\n{format_issues(errors)}" + ) + return CreatedFolder(target, RunInputs.open(run.output_folder)) + + +__all__ = [ + "MASKS_SUFFIX", + "CreatedFolder", + "MasksFolderRefused", + "create_masks_folder", + "default_masks_folder", +] diff --git a/src/morphobricks_preprocessing/unrecorded.py b/src/morphobricks_preprocessing/unrecorded.py index 09a19d1c..a6f04850 100644 --- a/src/morphobricks_preprocessing/unrecorded.py +++ b/src/morphobricks_preprocessing/unrecorded.py @@ -14,7 +14,8 @@ OME-Zarr images, less the masks the run recorded and the outputs of the mask conversion helpers of a mask type the run did not record (each with its published line of ``mask_lineage.jsonl``, Spec ADR 0005 BM12: a new mask no description of this run declares, - read only after the run is made again). Label images are never skipped: without + read only after the run is made again), and the mask types the run skipped + (``ignored_masks.toml``, recorded in the manifest). Label images are never skipped: without the ``zarr`` extra, or with a ``labels`` group that cannot be read, the check raises instead of passing (owner, 2 November 2026); - links: a link that leaves the experiment or masks folder, leads back to a folder holding @@ -29,6 +30,7 @@ from pathlib import Path from .discovery import DiscoveryResult, discover_experiment +from .ignored_masks import ignored_types from .links import refuse_links from .manifest import RunManifest from .mask_lineage import conversion_outputs @@ -101,8 +103,9 @@ def unrecorded_files( refuse_links(discovery.issues) images = set(discovery.images) - recorded - set(manifest.settings.exclude) recorded_masks = {m["path"] for m in (manifest.masks or {}).get("files", ())} - masks = _folder_mask_paths(masks_root, discovery, recorded) | _label_paths( - experiment_root, recorded + ignored = ignored_types(manifest) # skipped by the run as ignored_masks.toml lists them + masks = _folder_mask_paths(masks_root, discovery, recorded, ignored) | _label_paths( + experiment_root, recorded, ignored ) types = {str(t).casefold() for t in (manifest.masks or {}).get("types", ())} masks -= conversion_outputs(masks_root, masks, types) @@ -110,17 +113,22 @@ def unrecorded_files( def _folder_mask_paths( - masks_root: Path | None, discovery: DiscoveryResult, recorded: Collection[str] + masks_root: Path | None, + discovery: DiscoveryResult, + recorded: Collection[str], + ignored: Collection[str] = (), ) -> set[str]: """Return the masks-folder files that pair with a recorded image, by the run's rules.""" if masks_root is None or not masks_root.is_dir(): return set() found, issues = _folder_masks(masks_root, discovery, recorded) refuse_links(issues) - return {mask.path for mask in found if mask.source == FOLDER} + return {m.path for m in found if m.source == FOLDER and m.mask_type not in ignored} -def _label_paths(experiment_root: Path, recorded: Collection[str]) -> set[str]: +def _label_paths( + experiment_root: Path, recorded: Collection[str], ignored: Collection[str] = () +) -> set[str]: """Return the label images of the recorded OME-Zarr images, as their mask paths. Without the ``zarr`` extra, :class:`.zarr_input.ZarrUnavailableError` is raised, and an @@ -135,5 +143,5 @@ def _label_paths(experiment_root: Path, recorded: Collection[str]) -> set[str]: names = ngff_label_names(experiment_root / image) except NgffError as exc: raise NgffError(f"the label images of {image} cannot be read: {exc}") from exc - paths.update(f"{image}/labels/{name}" for name in names) + paths.update(f"{image}/labels/{name}" for name in names if name not in ignored) return paths diff --git a/src/morphobricks_preprocessing/window_chunks.py b/src/morphobricks_preprocessing/window_chunks.py new file mode 100644 index 00000000..0d77c309 --- /dev/null +++ b/src/morphobricks_preprocessing/window_chunks.py @@ -0,0 +1,108 @@ +"""Name, before a run, the OME-Zarr images whose chunks are too large for windowed reads (v0.10.1). + +A later brick reads a large image in windows through ``RunInputs.window_reader`` +(:mod:`.window_reader`), which decodes every OME-Zarr chunk a window touches whole and keeps +the chunks it decoded in a cache. A store in one chunk per plane (as ``convert --store +ome-zarr`` wrote before v0.10.1) is read whole for every window: preprocessing itself reads it +fine (its planes in blocks of rows), so nothing failed before the later brick's first window. + +:func:`check_window_chunks` works out from the headers the least a window reader needs for any +window of each OME-Zarr image (:func:`.windows.smallest_window_memory`: a window of one pixel, +read through a cache that holds one chunk, the least that keeps a chunk for the next window) +and warns, ``chunks_too_large_for_windows``, when it is over the memory limit. The reader +refuses the same store when it is opened with a cache that leaves no room for it +(:class:`.window_reader.WindowReader`), with the same advice (:data:`.windows.CHUNK_FIX`). +TIFF images are not checked here: their strips and tiles have their own refusals +(``plane_over_memory_limit``, issue #356). +""" + +from __future__ import annotations + +import logging +import os +from collections.abc import Mapping +from pathlib import Path + +from .axes import AxisMapping, AxisReview +from .plane_errors import PlaneReadError +from .planes import DEFAULT_MEMORY_LIMIT, format_bytes +from .validation import ValidationIssue, plural, warning +from .windows import CHUNK_FIX, _source, smallest_window_memory +from .zarr_input import is_zarr_store + +logger = logging.getLogger(__name__) + +CODE = "chunks_too_large_for_windows" + + +def window_chunk_need( + path: str | os.PathLike, mapping: AxisMapping, memory_limit: int = DEFAULT_MEMORY_LIMIT +) -> int | None: + """Return the least working memory of a window read of an OME-Zarr image, from its header. + + A window of one pixel through a window reader whose cache holds one chunk; None for a + TIFF image. + + Raises + ------ + PlaneReadError + If the image cannot be read under ``mapping``. + """ + if not is_zarr_store(path): + return None + with _source(path, mapping, memory_limit) as source: + return smallest_window_memory(source, source.layout.blocking.piece_nbytes) + + +def check_window_chunks( + experiment_root: str | os.PathLike, + review: AxisReview | Mapping[str, AxisMapping], + *, + memory_limit: int = DEFAULT_MEMORY_LIMIT, +) -> list[ValidationIssue]: + """Warn about OME-Zarr images that no window reader can read within ``memory_limit``. + + Parameters + ---------- + experiment_root + The experiment folder. + review + The axis review, or its per-file mappings keyed by relative path. + memory_limit + The working-memory limit of one read, in bytes. + + Returns + ------- + list of ValidationIssue + One warning, ``chunks_too_large_for_windows``, naming the images, or nothing. An image + that cannot be read under its mapping is left to :func:`.planes.check_planes`. + """ + mappings = review.file_mappings if isinstance(review, AxisReview) else review + root = Path(experiment_root) + found: list[tuple[str, int]] = [] + for rel in sorted(mappings): + try: + need = window_chunk_need(root / rel, mappings[rel], memory_limit) + except PlaneReadError: + logger.debug("Cannot plan windows of %s", rel, exc_info=True) + continue + if need is not None and need > memory_limit: + found.append((rel, need)) + if not found: + return [] + largest = max(need for _, need in found) + return [ + warning( + CODE, + f"{plural(len(found), 'OME-Zarr image')} cannot be read in windows within the memory " + f"limit of {format_bytes(memory_limit)}: the chunks are so large that even a window " + f"of one pixel needs up to {format_bytes(largest)} (a chunk is decoded whole). " + "Preprocessing reads them, but a later brick that reads windows (a patch-window " + "route) will refuse them.", + [rel for rel, _ in found], + CHUNK_FIX, + ) + ] + + +__all__ = ["CODE", "check_window_chunks", "window_chunk_need"] diff --git a/src/morphobricks_preprocessing/window_reader.py b/src/morphobricks_preprocessing/window_reader.py index 84328323..cc782646 100644 --- a/src/morphobricks_preprocessing/window_reader.py +++ b/src/morphobricks_preprocessing/window_reader.py @@ -57,8 +57,10 @@ _Source, _source, check_level, + chunk_note, plane_position, ) +from .zarr_input import is_zarr_store @dataclass(frozen=True) @@ -162,7 +164,10 @@ class WindowReader: ValueError If ``cache_bytes`` is not a whole number above 0. WindowMemoryError - If ``cache_bytes`` leaves no room under ``memory_limit``. + If ``cache_bytes`` leaves no room under ``memory_limit``, or for an OME-Zarr image + whose chunks are too large for even a window of one pixel to be read within + ``memory_limit`` with this cache (:func:`.windows.chunk_note`: a store written in one + chunk per plane; the message names the chunks and what to do). WindowSourceChangedError If the image is missing, or its fingerprint is not ``fingerprint``. """ @@ -188,6 +193,8 @@ def __init__( self.fingerprint = self._now() if fingerprint is None else fingerprint self._check() self._identity = os.path.realpath(self.path) + if is_zarr_store(self.path): + self._check_chunks() def window_plan( self, @@ -300,6 +307,25 @@ def __exit__(self, *exc_info: object) -> None: """Close the reader (:meth:`close`).""" self.close() + def _check_chunks(self) -> None: + """Refuse an OME-Zarr image no window of which fits the limit with this cache. + + From the header: a chunk is decoded whole for any window, so a store in chunks too + large (one chunk per plane of a slide) is refused when the reader is opened, naming its + chunks and what to do, rather than on its first window. + """ + with _source(self.path, self.mapping, self.memory_limit) as source: + note = chunk_note( + source, self.path, self.memory_limit, cache_bytes=self.cache.max_bytes + ) + if note: + self.close() + raise WindowMemoryError( + f"No window of {self.path.name} can be read within the memory limit of " + f"{format_bytes(self.memory_limit)} with a window cache of " + f"{format_bytes(self.cache.max_bytes)}." + note + ) + def _check_open(self) -> None: """Refuse a window asked after :meth:`close`.""" if self._closed: @@ -325,7 +351,10 @@ def _plan( plan = _plan(source, bounds, channels, self.memory_limit, position) plan = _with_cache(plan, self.cache.max_bytes) if plan.memory_estimate > self.memory_limit: - raise WindowMemoryError(_memory_text(plan, self.path) + _CACHE_NOTE) + note = chunk_note( + source, self.path, self.memory_limit, cache_bytes=self.cache.max_bytes + ) + raise WindowMemoryError(_memory_text(plan, self.path) + _CACHE_NOTE + note) return plan def _cached(self, key: Hashable, decode: Callable[[], np.ndarray | None]) -> np.ndarray | None: diff --git a/src/morphobricks_preprocessing/windows.py b/src/morphobricks_preprocessing/windows.py index 2909473f..de01af4d 100644 --- a/src/morphobricks_preprocessing/windows.py +++ b/src/morphobricks_preprocessing/windows.py @@ -316,7 +316,9 @@ def _read_source( position = _position(source.layout, mapping, {"Z": z, "T": t}) plan = _plan(source, bounds, channels, memory_limit, position) if plan.memory_estimate > memory_limit: - raise WindowMemoryError(_memory_text(plan, path)) + raise WindowMemoryError( + _memory_text(plan, path) + chunk_note(source, path, memory_limit, cache_bytes=0) + ) rows_are_y = source.layout.blocking.rows_are_y y0, y1, x0, x1 = plan.bounds box = (y0, y1, x0, x1) if rows_are_y else (x0, x1, y0, y1) @@ -521,3 +523,48 @@ def _memory_text(plan: WindowPlan, path: str | os.PathLike) -> str: f"{format_bytes(plan.memory_limit)}. Ask for a smaller window or fewer channels, or " "raise the memory limit if this computer has enough memory." ) + + +CHUNK_FIX = ( + "If it is an OME-Zarr copy written by 'convert --store ome-zarr' or the notebook before " + "v0.10.1 (one chunk per plane), convert the original images again into a new folder: " + "copies are now written in chunks of 1024 x 1024 pixels. Otherwise save the image again " + "with chunks of at most 1024 x 1024 pixels along Y and X (one plane along the other axes)." +) +"""What to do about an OME-Zarr image whose chunks are too large for windowed reads.""" + + +def smallest_window_memory(source: _Source, cache_bytes: int = 0) -> int: + """Return the working memory of the smallest window read of an open image, from its header. + + A window of one pixel of one channel, read without a cache (``cache_bytes`` 0) or through a + reader whose cache holds ``cache_bytes`` (counted in the figure, as a reader's plan counts + it). An OME-Zarr chunk is decoded whole however small the window, so for a store in one + chunk per plane this is several times the plane: no window of it can be read in less. + """ + plan = _plan(replace(source, cached=cache_bytes > 0), (0, 1, 0, 1), (0,), 0) + return plan.memory_estimate + cache_bytes + + +def chunk_note( + source: _Source, path: str | os.PathLike, memory_limit: int, *, cache_bytes: int +) -> str: + """Return the sentences naming chunks too large for any window within the limit, or "". + + Only for OME-Zarr images (TIFF pieces are bounded by their own refusals, issue #356): + when even a window of one pixel (:func:`smallest_window_memory`, with ``cache_bytes``) is + over ``memory_limit``, no smaller window helps, and the chunks are what to change. + """ + blocking = source.layout.blocking + if blocking.kind != "zarr": + return "" + need = smallest_window_memory(source, cache_bytes) + if need <= memory_limit: + return "" + rows, cols = blocking.unit + return ( + f" {Path(path).name} is stored in chunks of {rows} x {cols} pixels " + f"({format_bytes(blocking.piece_nbytes)} each), and a chunk is decoded whole for any " + f"window it holds: even a window of one pixel needs about {format_bytes(need)}. " + + CHUNK_FIX + ) diff --git a/tests/code_identity_tree.py b/tests/code_identity_tree.py index 08bc3060..040521d3 100644 --- a/tests/code_identity_tree.py +++ b/tests/code_identity_tree.py @@ -19,14 +19,19 @@ def _hash(data): return "sha256=" + base64.urlsafe_b64encode(digest).rstrip(b"=").decode() -def install(site, files=FILES, *, editable=False, unhashed=(), commit=COMMIT): - """Install ``files`` as the distribution ``fakepkg`` 1.0 under ``site``; return it.""" +def install(site, files=FILES, *, editable=False, unhashed=(), commit=COMMIT, requires=()): + """Install ``files`` as the distribution ``fakepkg`` 1.0 under ``site``; return it. + + ``requires`` are its ``Requires-Dist`` lines. + """ info = site / "fakepkg-1.0.dist-info" info.mkdir(parents=True) for name, data in files.items(): (site / name).parent.mkdir(parents=True, exist_ok=True) (site / name).write_bytes(data) - (info / "METADATA").write_bytes(b"Metadata-Version: 2.1\nName: fakepkg\nVersion: 1.0\n") + lines = ["Metadata-Version: 2.1", "Name: fakepkg", "Version: 1.0"] + lines += [f"Requires-Dist: {requirement}" for requirement in requires] + (info / "METADATA").write_text("\n".join(lines) + "\n", encoding="utf-8") url = {"url": "file:///src/fakepkg"} url |= {"dir_info": {"editable": True}} if editable else {"vcs_info": {"commit_id": commit}} (info / "direct_url.json").write_text(json.dumps(url), encoding="utf-8") @@ -41,6 +46,17 @@ def install(site, files=FILES, *, editable=False, unhashed=(), commit=COMMIT): return metadata.PathDistribution(info) +def install_egg_info(site, name, version, requires=()): + """Install ``name`` as conda installs ``setuptools``: an ``.egg-info`` with no ``RECORD``.""" + info = site / f"{name}-{version}-py3.egg-info" + info.mkdir(parents=True) + (info / "PKG-INFO").write_text( + f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n", encoding="utf-8" + ) + (info / "requires.txt").write_text("".join(f"{r}\n" for r in requires), encoding="utf-8") + return metadata.PathDistribution(info) + + def modules_of(site, names=("fakepkg", "fakepkg.mod")): """Imported modules of the installation, as ``sys.modules`` would hold them.""" paths = {"fakepkg": "fakepkg/__init__.py", "fakepkg.mod": "fakepkg/mod.py"} diff --git a/tests/data/he_core_1B_D9_crop.npz b/tests/data/he_core_1B_D9_crop.npz new file mode 100644 index 00000000..5e25c26c Binary files /dev/null and b/tests/data/he_core_1B_D9_crop.npz differ diff --git a/tests/data/make_he_core_crop.py b/tests/data/make_he_core_crop.py new file mode 100644 index 00000000..71290a0c --- /dev/null +++ b/tests/data/make_he_core_crop.py @@ -0,0 +1,55 @@ +"""Write ``he_core_1B_D9_crop.npz``: a crop of a real H&E TMA core for the tissue mask tests. + +The crop is rows 500 to 819 and columns 80 to 399 (320 x 320, ``uint8`` ``(Y, X, 3)`` R, G, B) +of ``validation2/1B_D9_WB.tif`` from Zenodo record 4550300, "Multimodal Biomedical Dataset for +Evaluating Registration Methods (Full-size TMA Cores)", by Kevin Eliceiri, Bin Li and Adib +Keikhosravi (2021), doi 10.5281/zenodo.4550300, licensed CC-BY-4.0 +(https://creativecommons.org/licenses/by/4.0/). The crop is unchanged otherwise: its pixels are +the file's. It spans the core's edge: grey glass on the left, stroma with nuclei and a lumen on the +right. The scanner's glass is near (127, 135, 145), not white, and the file's photometric tag says +MINISBLACK although its three samples are R, G, B (the run reads it with the RGB header override): +the images on which ``he_tissue_v1`` kept 0 % (issue of 3 December 2026). + +Run once, from the repository root, with the record's ``validation2.zip`` downloaded: + + python tests/data/make_he_core_crop.py path/to/validation2.zip + +The digests below are checked before anything is written. +""" + +from __future__ import annotations + +import hashlib +import io +import sys +import zipfile +from pathlib import Path + +import numpy as np +import tifffile + +ZIP_SHA256 = "f7eb874bc22c4df339f903f021992d4dcdc8f6c095c3a5bc90a97f23957945f8" +MEMBER = "validation2/1B_D9_WB.tif" +MEMBER_SHA256 = "8c74caddfd9e7f2f29950637f4cd1118d1f4781e8acba29233f3db1e6ddcc099" +ROWS, COLUMNS = slice(500, 820), slice(80, 400) +TARGET = Path(__file__).with_name("he_core_1B_D9_crop.npz") + + +def main(zip_path: str) -> None: + """Check the downloaded zip and its member, then write the crop next to this script.""" + data = Path(zip_path).read_bytes() + if hashlib.sha256(data).hexdigest() != ZIP_SHA256: + raise SystemExit(f"{zip_path} is not the record's validation2.zip (SHA-256 differs)") + member = zipfile.ZipFile(io.BytesIO(data)).read(MEMBER) + if hashlib.sha256(member).hexdigest() != MEMBER_SHA256: + raise SystemExit(f"{MEMBER} differs from the one this crop was taken from") + with tifffile.TiffFile(io.BytesIO(member)) as tif: + rgb = tif.series[0].asarray() + crop = np.ascontiguousarray(rgb[ROWS, COLUMNS]) + assert crop.shape == (320, 320, 3) and crop.dtype == np.uint8 + np.savez_compressed(TARGET, rgb=crop) + print(f"wrote {TARGET} ({TARGET.stat().st_size} bytes)") + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/tests/test_axis_check.py b/tests/test_axis_check.py index 4d9fb9b1..576effa8 100644 --- a/tests/test_axis_check.py +++ b/tests/test_axis_check.py @@ -390,7 +390,7 @@ def test_cli_run_names_the_swapped_files(tmp_path, capsys): assert main_described(["run", str(root), "--axes", "CXY"]) == 1 out = capsys.readouterr().out assert "header CYX, confirmed CXY: ctrl/a.tif" in out - assert "no table or manifest was written" in out + assert "No new histogram table or run manifest was published" in out def test_notebook_marks_roles_that_disagree_with_the_header(tmp_path): diff --git a/tests/test_brick_api_surface.py b/tests/test_brick_api_surface.py index 7beb473d..dcdedac4 100644 --- a/tests/test_brick_api_surface.py +++ b/tests/test_brick_api_surface.py @@ -84,11 +84,11 @@ "histograms": "(self) -> 'tuple[PlaneRecord, ...]'", # Spec ADR 0005 BM15: the opt-in H&E tissue mask helper (imported lazily, he-mask extra). "he_tissue_mask": ( - "(self, fov: 'Fov | str', *, output_mask_id: 'str', rule: 'str' = 'he_tissue_v1') " + "(self, fov: 'Fov | str', *, output_mask_id: 'str', rule: 'str' = 'he_tissue_v2') " "-> 'TissueMaskResult'" ), "preview_he_tissue_mask": ( - "(self, fov: 'Fov | str', *, rule: 'str' = 'he_tissue_v1') -> 'TissueMaskPreview'" + "(self, fov: 'Fov | str', *, rule: 'str' = 'he_tissue_v2') -> 'TissueMaskPreview'" ), "description": "(self) -> 'Description'", "section_digests": "(self) -> 'dict[str, str]'", diff --git a/tests/test_brick_checks.py b/tests/test_brick_checks.py index 004729a2..74d7041b 100644 --- a/tests/test_brick_checks.py +++ b/tests/test_brick_checks.py @@ -288,3 +288,15 @@ def refuse(path="."): assert raised.value.code == "masks_folder_unreadable" assert str(raised.value).startswith("masks_folder_unreadable: ") assert str(locked) in str(raised.value) + + +def test_the_zarr_install_line_names_the_installed_release(): + from morphobricks_preprocessing.run_inputs_text import zarr_install_line + + assert zarr_install_line("0.10.0") == ( + 'python -m pip install "morphobricks-preprocessing[zarr] @ ' + 'git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.0"' + ) + for unreleased in ("0.10.1.dev3+g197b6db", None): # no tag to name: never a made-up one + line = zarr_install_line(unreleased) + assert "@v" not in line and "the same release" in line diff --git a/tests/test_calibrate_containment.py b/tests/test_calibrate_containment.py index be4b028b..91db1d87 100644 --- a/tests/test_calibrate_containment.py +++ b/tests/test_calibrate_containment.py @@ -82,7 +82,7 @@ def test_calibrate_writes_next_to_the_experiment(exp, tmp_path, capsys): assert read_calibration(output / CALIBRATION_FILENAME)[0].entries assert not (output / LOCK_FILENAME).exists() assert main(["calibrate", str(exp), *SIZE]) == 0 # the default output folder - assert "Written to" in capsys.readouterr().out + assert "Calibration saved to" in capsys.readouterr().out def test_calibrate_allows_a_prefix_sibling_of_the_experiment(exp, tmp_path, capsys): diff --git a/tests/test_calibration.py b/tests/test_calibration.py index e928f5d6..26a4f013 100644 --- a/tests/test_calibration.py +++ b/tests/test_calibration.py @@ -462,7 +462,7 @@ def test_the_calibrate_command_keeps_an_unreadable_file(tmp_path, capsys): def test_the_calibrate_command_states_shows_and_removes(tmp_path, capsys): output = tmp_path / "out" assert main(["calibrate", "--output", str(output)]) == 0 - assert "No pixel size is stated" in capsys.readouterr().out + assert "No pixel sizes have been stated" in capsys.readouterr().out assert not (output / CALIBRATION_FILENAME).exists() args = ["calibrate", "--output", str(output), "--size", ".", "YX", "0.65", "um"] assert main_described([*args, "--pixels", "ctrl/rep1", "Z"]) == 0 diff --git a/tests/test_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 diff --git a/tests/test_cli.py b/tests/test_cli.py index 588fabef..fbb6c4e4 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -48,7 +48,11 @@ def test_check_prints_summary_and_suggested_axes(experiment, capsys): assert "Suggested option for 'run': --axes TCYX (axes in the files: TCYX)" in out # 'check' is the run's step stopped after the report: it writes the report only. output = experiment.parent / "exp_MorphoBricks_Preprocessing" - assert check_outputs(output) and f"Report written to {output}" in out + assert ( + check_outputs(output) + and f"Report saved to {output}" in out + and "Header check passed." in out + ) def test_check_exits_with_1_on_errors(experiment, capsys): @@ -113,7 +117,10 @@ def test_rgb_is_refused_for_images_that_cannot_be_rgb(experiment, capsys): out = capsys.readouterr().out assert "contradict their header" in out assert "RGB images need exactly three colour channels" in out - assert "8 channels of type uint8" in out and "no table or manifest was written" in out + assert ( + "8 channels of type uint8" in out + and "No new histogram table or run manifest was published" in out + ) def test_image_type_must_be_known(experiment): @@ -188,7 +195,7 @@ def test_run_reports_blocking_errors(experiment, capsys): assert main_described(["run", str(experiment), "--axes", "Z-YX"]) == 1 out = capsys.readouterr().out assert "No role is chosen for the axis C (channel)" in out - assert "no table or manifest was written" in out + assert "No new histogram table or run manifest was published" in out def test_run_without_readable_images(tmp_path, capsys): @@ -217,7 +224,7 @@ def test_different_channel_counts_stop_check_and_run(tmp_path, capsys): assert "different numbers of channels: 3 channels (2 images), 2 channels (1 image)" in out assert main_described(["run", str(root), "--axes", "TCYX"]) == 1 out = capsys.readouterr().out # one described unit: its images are not homogeneous - assert "b.tif" in out and "no table or manifest was written" in out + assert "b.tif" in out and "No new histogram table or run manifest was published" in out def test_axes_are_needed_for_the_first_run_of_plain_stacks_only(tmp_path, capsys): diff --git a/tests/test_cli_describe.py b/tests/test_cli_describe.py index 6837cd80..129ae94e 100644 --- a/tests/test_cli_describe.py +++ b/tests/test_cli_describe.py @@ -68,7 +68,7 @@ def test_describe_prints_the_proposals_and_the_open_questions_and_writes_nothing assert "rep1: proposed ID 'rep1'; not confirmed" in out assert "CTRL / rep1: 2 images" in out assert "open questions (answered by you, in the notebook)" in out - assert "confirm that the folders of repeat rep1 were prepared and acquired" in out + assert "only if it is true, that the samples of repeat rep1 were prepared and acquired" in out assert "choose the ID of condition CTRL" in out assert listing(tmp_path) == before and not output.exists() @@ -77,7 +77,9 @@ def test_a_folder_that_cannot_be_an_id_has_no_proposal_and_is_not_repaired(tmp_p root = tree(tmp_path / "exp", "control/rep1", "DrugA/rep1") assert main(["describe", str(root)]) == 0 out = capsys.readouterr().out - assert "control: no ID can be proposed" in out and "you name it" in out + assert "control: no ID proposed. The condition folder 'control' needs another" in out + assert "because 'control' is reserved (E_FORBIDDEN_FIELD)" in out + assert "Keep the folder name and add --id control=ctrl" in out assert "DrugA: proposed ID 'DrugA'" in out @@ -123,7 +125,7 @@ def test_publish_refuses_a_draft_with_open_questions_and_lists_them(experiment, assert "Not published. What is missing:" in out missing = out.split("Not published. What is missing:")[1] assert missing.count(" - choose the ID of") == 5 # 2 conditions, single, 2 repeats - assert " - confirm that the folders of repeat rep2" in out + assert " - confirm, only if it is true, that the samples of repeat rep2" in out assert not (output / TOML).exists() and not output.exists() assert listing(tmp_path) == before @@ -142,7 +144,7 @@ def test_a_complete_draft_is_still_not_publishable_from_the_command_line(tmp_pat ]: draft = draft.confirm_id(kind, key, key) assert [q.code for q in draft.open_questions()] == ["repeat_not_confirmed"] - assert any("same circumstances" in item for item in draft_blockers(draft)) + assert any("prepared and acquired comparably" in item for item in draft_blockers(draft)) done = replace( draft, repeats={"rep1": replace(draft.repeats["rep1"], confirmed=True, confirmed_on="2026-11-01")}, @@ -208,4 +210,6 @@ def test_a_description_that_cannot_be_read_is_refused(tmp_path, capsys): root, output = published(tmp_path) (output / TOML).write_text("schema = 'nope'\n", encoding="utf-8") assert main(["describe", str(root), "--output", str(output)]) == 1 - assert "cannot be used" in capsys.readouterr().out + out = capsys.readouterr().out # the plain meaning first, then the field path and code + assert "The experiment description (morphobricks.toml) is not an experiment" in out + assert "(at schema, value 'nope', E_SCHEMA_ID)" in out diff --git a/tests/test_cli_exit_status.py b/tests/test_cli_exit_status.py index 437b5a51..3aebb587 100644 --- a/tests/test_cli_exit_status.py +++ b/tests/test_cli_exit_status.py @@ -33,6 +33,9 @@ def test_without_a_published_description_every_run_command_exits_with_1( assert main([command, str(experiment), "--output", str(output), *extra]) == 1 out = capsys.readouterr().out assert "A_DESCRIPTION_REQUIRED" in out and "describe" in out + # Both routes that publish are named (owner, 4 December 2026): notebook and command line. + assert "in the notebook" in out and "morphobricks-preprocessing describe" in out + assert "--publish" in out assert not output.exists() # nothing read or written diff --git a/tests/test_cli_tissue_mask.py b/tests/test_cli_tissue_mask.py index 9bfee5ca..2c62aedd 100644 --- a/tests/test_cli_tissue_mask.py +++ b/tests/test_cli_tissue_mask.py @@ -44,16 +44,23 @@ def test_it_writes_every_rgb_image_and_names_the_next_steps(tmp_path, capsys, mo args = ["tissue-mask", "--output", str(run.output_folder), "--to", "HETissue"] assert main(args) == 0 printed = capsys.readouterr().out - assert "Fixed rule he_tissue_v1 (provisional)" in printed - assert f"{IMAGE}: HETissue/{IMAGE} (written), kept 80.4 %" in printed - assert "declare the mask HETissue (source type HETissue) as binary" in printed - assert "run preprocessing and the masks step again" in printed - assert "never pass it as cell-mode labels" in printed + assert "Tissue-mask rule: he_tissue_v2 (provisional" in printed + assert f"{IMAGE}: mask saved to HETissue/{IMAGE}; retained area: 80.4 % of the image" in printed + output = run.output_folder + assert ( + f"morphobricks-preprocessing declare-masks --output {output} --type HETissue=binary " + f"--masks {run.masks_root}" in printed + ) + assert f"morphobricks-preprocessing run --output {output}\n" in printed + assert f"morphobricks-preprocessing masks --output {output}\n" in printed + assert 'region_mask = "HETissue"' in printed and "never as cell-mode labels" in printed + assert "source_channels" not in printed and "MaskRequest" not in printed + assert "had no masks folder" not in printed line = json.loads((run.masks_root / "HETissue" / LINEAGE_FILENAME).read_text()) assert line["operation"] == "he_tissue_mask" and line["reusable"] is True before = tree(run.masks_root) assert main([*args, "--image", IMAGE]) == 0 # the same call: a no-op - assert "(already written)" in capsys.readouterr().out + assert "mask already saved to" in capsys.readouterr().out assert tree(run.masks_root) == before @@ -79,6 +86,11 @@ def test_a_refusal_is_printed_and_exits_1_writing_nothing(tmp_path, capsys): printed = capsys.readouterr().out assert printed.splitlines()[-1].startswith(f"{IMAGE}: no tissue mask written. The output") assert "is declared in the description already" in printed + other = "CTRL/rep1/zz.tif" + assert main([*args, "--image", other]) == 1 + last = capsys.readouterr().out.splitlines()[-1] + assert last == f"No tissue mask written. {other} is not an image of this run." + assert last.count(other) == 1 # the image is named once (owner, 4 December 2026) assert main(["tissue-mask", "--output", str(tmp_path / "none"), "--to", "X"]) == 1 assert "The run cannot be used" in capsys.readouterr().out assert tree(run.masks_root) == before @@ -116,3 +128,71 @@ def refuse(self, *args, **kwargs): f"{IMAGE}: no tissue mask written. the plane needs 9 GiB; the limit is 2 GiB" ) assert tree(run.masks_root) == before + + +# --- No masks folder: created and recorded (owner, 4 December 2026) -------------------------- + + +def test_a_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 +): + pytest.importorskip("skimage") + monkeypatch.setattr(IDENTITY_PATCH, lambda: identities()) + run = rgb_run(tmp_path, masks=False) + assert run.masks_root is None + args = ["tissue-mask", "--output", str(run.output_folder), "--to", "HETissue"] + assert main(args) == 0 + printed = capsys.readouterr().out + folder = (tmp_path / "experiment_masks").resolve() + created = [line for line in printed.splitlines() if "Masks folder created" in line] + assert created == [ + f"Masks folder created and registered: {folder}. The preprocessing run now records " + "this folder." + ] + assert (folder / "HETissue" / IMAGE).is_file() + manifest = json.loads((run.output_folder / "run_manifest.json").read_text()) + assert manifest["masks"]["folder"] == str(folder) # recorded as a run with --masks does + from morphobricks_preprocessing.run_inputs import RunInputs + + assert RunInputs.open(run.output_folder).masks_root == folder + assert main(args) == 0 # the same call again: the recorded folder, nothing created + printed = capsys.readouterr().out + assert "Masks folder created" not in printed and "mask already saved to" in printed + + +def test_masks_names_the_folder_to_create_and_a_busy_folder_is_refused( + tmp_path, capsys, monkeypatch +): + pytest.importorskip("skimage") + monkeypatch.setattr(IDENTITY_PATCH, lambda: identities()) + run = rgb_run(tmp_path, masks=False) + busy = tmp_path / "busy" + (busy / "other").mkdir(parents=True) + args = ["tissue-mask", "--output", str(run.output_folder), "--to", "HETissue"] + assert main([*args, "--masks", str(busy)]) == 1 + assert "exists and is not an empty folder" in capsys.readouterr().out + manifest = json.loads((run.output_folder / "run_manifest.json").read_text()) + assert not (manifest.get("masks") or {}).get("folder") + chosen = tmp_path / "chosen" + assert main([*args, "--masks", str(chosen)]) == 0 + assert f"Masks folder created and registered: {chosen.resolve()}." in capsys.readouterr().out + assert (chosen / "HETissue" / IMAGE).is_file() + assert main([*args, "--masks", str(tmp_path / "third")]) == 1 # the run has one now + assert "this run records" in capsys.readouterr().out + assert not (tmp_path / "third").exists() diff --git a/tests/test_cli_usability.py b/tests/test_cli_usability.py new file mode 100644 index 00000000..f10caa41 --- /dev/null +++ b/tests/test_cli_usability.py @@ -0,0 +1,564 @@ +"""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 +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] +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 = ( + "The mask type 'cells' was found but has not been declared. Choose how its pixel " + "values should be interpreted." + ) + # Every representation is offered with what it means; none is guessed from the name. + action = ( + "If every object has its own positive label, declare it as instance labels (replacing " + "OUTPUT with your output folder):\n" + " morphobricks-preprocessing declare-masks --output OUTPUT --type cells=instances\n" + ) + for text in (checked, ran): + assert message in text and action in text + assert "declare-masks --output OUTPUT --ignore cells" in text # owner, 4 Dec 2026 + assert "For a foreground/background mask, use cells=binary instead." in text + assert "For labels grouping several objects, use cells=parent_labels." in text + assert "beside the images" not in checked # masks live in a masks folder, never there + import json + + report = json.loads((out / "discovery_report.json").read_text()) + 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=instances'" in issue.action + assert "--ignore 'Cell outlines'" in issue.action + assert "use 'Cell outlines=binary'" in issue.action + named = physical_issue( + PhysicalIssue(MASK_TYPE_NOT_DECLARED, None, detail="cells"), "/data/my out" + ) + assert "declare-masks --output '/data/my out' --type cells=instances" in named.action + assert "OUTPUT" not in named.action + + +def test_declare_masks_ignore_skips_a_label_image_and_the_run_records_it(tmp_path, capsys): + import json + + from morphobricks_preprocessing.run_inputs import RunInputs + + root, out = _labelled(tmp_path) + capsys.readouterr() + assert main(["declare-masks", "--output", str(out), "--ignore", "cells"]) == 0 + text = capsys.readouterr().out + assert "Mask types the runs skip (ignored_masks.toml): cells." in text + assert (out / "ignored_masks.toml").read_text() == ( + "# Mask types and OME-Zarr label images the runs of this output folder skip.\n" + "# Written by declare-masks --ignore; declare a type to use it again.\n" + 'version = 1\nignore = ["cells"]\n' + ) + assert main(["declare-masks", "--output", str(out), "--ignore", "cells"]) == 0 + assert "Already skipped" in capsys.readouterr().out # a retry writes nothing + assert main(["check", str(root), "--output", str(out)]) == 0 + assert main(["run", str(root), "--output", str(out)]) == 0 + capsys.readouterr() + manifest = json.loads((out / "run_manifest.json").read_text()) + assert manifest["ignored_masks"]["types"] == ["cells"] + run = RunInputs.open(out) # the label images are skipped, not unrecorded + assert run.manifest.masks is None or not run.manifest.masks.get("files") + # The list changed after the run: the run folder is stale until preprocessing runs again. + (out / "ignored_masks.toml").write_text('version = 1\nignore = ["cells", "other"]\n') + with pytest.raises(ValueError, match="RUN_FOLDER_STALE|ignored_masks.toml"): + RunInputs.open(out) + + +def test_declaring_an_ignored_type_takes_it_off_the_list_and_both_at_once_is_refused( + tmp_path, capsys +): + root, out = _labelled(tmp_path) + capsys.readouterr() + assert main(["declare-masks", "--output", str(out), "--ignore", "cells"]) == 0 + capsys.readouterr() + both = ["declare-masks", "--output", str(out), "--type", "cells=instances"] + assert main([*both, "--ignore", "cells"]) == 1 + assert "a declared mask type is not ignored" in capsys.readouterr().out + assert main(both) == 0 + assert "none (the file was removed)" in capsys.readouterr().out + assert not (out / "ignored_masks.toml").exists() + assert main(["run", str(root), "--output", str(out)]) == 0 # cells is used now + assert main(["declare-masks", "--output", str(out)]) == 1 + assert "Give at least one --type" in capsys.readouterr().out + + +def test_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) + 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() + (out / "ignored_masks.toml").write_text('version = 2\nignore = ["cells"]\n') + assert main(["check", str(root), "--output", str(out)]) == 1 + checked = capsys.readouterr().out + assert "The ignored-mask list cannot be read" in checked + # declare-masks reads the list first, so the fix moves the file out before recreating it. + assert "Move ignored_masks.toml out of the output folder and keep it as a backup" in checked + assert f"declare-masks --output {out.as_posix()} --ignore TYPE" in checked + assert main(["declare-masks", "--output", str(out), "--ignore", "x"]) == 1 + refused = capsys.readouterr().out + assert "this release reads version 1" in refused + assert "Move ignored_masks.toml out of the output folder" in refused + (out / "ignored_masks.toml").rename(tmp_path / "ignored_masks.toml.bak") # as it says + assert main(["declare-masks", "--output", str(out), "--ignore", "cells"]) == 0 + assert main(["check", str(root), "--output", str(out)]) == 0 + + +def test_declare_masks_without_a_masks_folder_names_no_placeholder_folder(tmp_path, capsys): + 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")) + run_line = next(line for line in lines if "morphobricks-preprocessing run" in line) + assert run_line.endswith(f"--masks '{tmp_path / 'my masks'}'") + assert all("Add --masks" not in line for line in lines) + + +# --- 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 --comparable and --confirmed-on" in text + assert "confirm, only if it is true, that the samples of repeat rep1" in text + assert "choose the ID" not in text # --accept-ids answered those + + +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 with --id FOLDER=ID, or in the notebook)" in text + assert "needs another identifier because 'files' is reserved" in text + assert "add --id files=files_1" in text and "" not in text + + +# --- 4b. describe --id FOLDER=ID (owner, 4 December 2026) ---------------------------------- + + +def test_describe_id_names_a_forbidden_folder_and_publishes(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + for condition in ("control", "DrugA"): # control is a forbidden ID: no proposal + _ome(root / condition / "rep1" / "img.ome.tif") + command = ["describe", str(root), "--output", str(out), *CHANNELS, "--publish"] + assert main(command) == 1 + text = capsys.readouterr().out + assert "answer them with --id FOLDER=ID, or in the notebook" in text + assert "--accept-ids, " not in text.split("open question")[1].split("\n")[0] + assert "The condition folder 'control' needs another identifier because 'control' is" in text + assert "Keep the folder name and add --id control=ctrl" in text and "" not in text + assert not (out / DESCRIPTION_FILENAME).exists() + assert main([*command, "--id", "control=ctrl"]) == 0 + assert "Experiment description saved to" in capsys.readouterr().out + published = description_from_bytes((out / DESCRIPTION_FILENAME).read_bytes()) + assert published.conditions["ctrl"].source_folder == "control" + assert set(published.conditions) == {"ctrl", "DrugA"} + + +def test_describe_id_refuses_what_the_notebook_refuses_and_names_the_option(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + for condition in ("control", "DrugA"): + _ome(root / condition / "rep1" / "img.ome.tif") + base = ["describe", str(root), "--output", str(out), *CHANNELS, "--publish"] + for given, said in [ + ( + "control=files", + "This name is reserved. Choose another identifier (E_FORBIDDEN_FIELD). For " + "example: --id control=ctrl", + ), + ("control=druga", "only in upper/lower case. Choose a distinct identifier"), + ("control=DrugA", "already been used for another entry. Choose an unused identifier"), + ("nowhere=x", "'nowhere' is not a condition, biological-repeat or technical-repeat"), + ("control", "write it as FOLDER=ID"), + ]: + extra = ["--id", "DrugA=DrugA"] if given.endswith(("druga", "DrugA")) else [] + assert main([*base, *extra, "--id", given]) == 1, given + text = capsys.readouterr().out + assert "Nothing was written. These IDs cannot be used:" in text + assert said in text, (given, text) + assert not out.exists() + + +def test_describe_id_without_channels_shows_the_named_id(tmp_path, capsys): + root = tmp_path / "exp" + _ome(root / "control" / "rep1" / "img.ome.tif") + out = tmp_path / "out" + assert main(["describe", str(root), "--output", str(out), "--id", "control=ctrl"]) == 0 + text = capsys.readouterr().out + assert "control: ID 'ctrl' (yours, --id)" in text + assert "condition control" not in text # its question is answered + + +def test_describe_id_needs_the_level_for_a_label_of_two_levels(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + _ome(root / "a" / "rep1" / "a" / "img.ome.tif") + _ome(root / "b" / "rep1" / "a" / "img.ome.tif") + base = ["describe", str(root), "--output", str(out), *CHANNELS, "--publish"] + assert main([*base, "--id", "a=A1"]) == 1 + text = capsys.readouterr().out + assert "the name 'a' occurs at more than one folder level. Specify which level" in text + assert "--id condition:a=A1 or --id technical:a=A1" in text + assert main([*base, "--id", "condition:a=A1"]) == 0 + published = description_from_bytes((out / DESCRIPTION_FILENAME).read_bytes()) + assert published.conditions["A1"].source_folder == "a" + + +def test_describe_id_is_refused_for_a_published_or_strict_description(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + _ome(root / "CTRL" / "rep1" / "img.ome.tif") + assert ( + main(["describe", str(root), "--output", str(tmp_path / "s"), "--strict", "--id", "CTRL=c"]) + == 1 + ) + assert "--id names the IDs of a new fast-mode description" in capsys.readouterr().out + assert main(["describe", str(root), "--output", str(out), *CHANNELS, "--publish"]) == 0 + capsys.readouterr() + assert main(["describe", str(root), "--output", str(out), "--id", "CTRL=c"]) == 1 + assert "--id names the IDs of a new fast-mode description" in capsys.readouterr().out + + +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 --------------- + + +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 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. diff --git a/tests/test_convert_work_folder.py b/tests/test_convert_work_folder.py index 69557df2..27916549 100644 --- a/tests/test_convert_work_folder.py +++ b/tests/test_convert_work_folder.py @@ -256,5 +256,5 @@ def test_an_owner_file_of_nul_bytes_is_refused_as_possibly_from_a_power_loss( message = result.issues[0].message assert ("possibly left by a power loss" in message) is named assert ("is unreadable" in message) is named - assert ("So it was not made by a conversion" in message) is not named + assert ("has an invalid or missing ownership record" in message) is not named assert _tree(copies) == before diff --git a/tests/test_declare_masks.py b/tests/test_declare_masks.py index 69e90c7b..fc991463 100644 --- a/tests/test_declare_masks.py +++ b/tests/test_declare_masks.py @@ -42,7 +42,7 @@ def test_the_masks_of_a_run_are_declared_run_and_described_from_the_command_line out = str(run.output) assert main(["run", str(run.experiment), "--output", out, "--masks", str(masks)]) == 1 refused = capsys.readouterr().out - assert "not declared" in refused and "declare-masks" in refused + assert "has not been declared" in refused and "declare-masks" in refused assert main(["declare-masks", "--output", out, "--type", "Cells=instances"]) == 0 said = capsys.readouterr().out diff --git a/tests/test_description_write_types.py b/tests/test_description_write_types.py index 1a9b91cb..5bd2a429 100644 --- a/tests/test_description_write_types.py +++ b/tests/test_description_write_types.py @@ -189,7 +189,7 @@ def test_a_numpy_value_is_named_with_its_module_everywhere_the_type_is_shown( out.mkdir() build_experiment(root, _v01(), images=1) check = check_candidate(model, preflight(root, out), None) - assert f"of type {found})" in check.refusals[0].message + assert f"of type {found}, E_TYPE)" in check.refusals[0].message def _non_text_keys() -> list[tuple[Description, str]]: diff --git a/tests/test_entry_identity.py b/tests/test_entry_identity.py new file mode 100644 index 00000000..2d1eb0dc --- /dev/null +++ b/tests/test_entry_identity.py @@ -0,0 +1,85 @@ +"""The requirement closure of an entry's code identity (Spec ADR 0007 "The run record"). + +A conda environment installs ``setuptools`` as an ``.egg-info`` with no ``RECORD``; every entry +output written there was uncertain (never reused) because the closure, every extra included, +reached it. The installers pip, setuptools and wheel are left out of the closure (v0.10.1); any +other library without a ``RECORD`` stays uncertain (ADR 0007 (b)), and the refusal's fix names +that library instead of telling the user to reinstall the brick. +""" + +from __future__ import annotations + +from code_identity_tree import install, install_egg_info +from morphobricks_preprocessing import entry_identity +from morphobricks_preprocessing.entry_errors import ( + UNCERTAIN_CODE, + entry_identity_uncertain, + uncertain_code_fix, +) + + +def test_a_conda_setuptools_egg_info_no_longer_makes_the_identity_uncertain(tmp_path, monkeypatch): + site = tmp_path / "site" + install(site, requires=("setuptools>=60", 'wheel; extra == "build"', "pip")) + install_egg_info(site, "setuptools", "65.6.3", requires=("eggy",)) + install_egg_info(site, "wheel", "0.41.0") + install_egg_info(site, "pip", "24.0") + monkeypatch.syspath_prepend(str(site)) + # The fake egg-info is what metadata finds: without the exclusion it would be uncertain. + assert entry_identity.library_identity("setuptools")["uncertain"] == "RECORD missing" + identity = entry_identity.brick_identity("fakepkg", "fake") + assert identity["uncertain"] is None + assert not {"setuptools", "wheel", "pip", "eggy"} & set(identity["libraries"]) + assert entry_identity.uncertain_library(identity) is None + + +def test_an_installer_the_caller_names_is_still_identified(tmp_path, monkeypatch): + site = tmp_path / "site" + install(site) + install_egg_info(site, "setuptools", "65.6.3") + monkeypatch.syspath_prepend(str(site)) + identity = entry_identity.brick_identity("fakepkg", "fake", libraries=["setuptools"]) + assert identity["uncertain"] == "setuptools: RECORD missing" + + +def test_another_egg_info_library_stays_uncertain_and_the_fix_names_it(tmp_path, monkeypatch): + site = tmp_path / "site" + install(site, requires=("eggy>=2",)) + install_egg_info(site, "eggy", "2.0") + monkeypatch.syspath_prepend(str(site)) + identity = entry_identity.brick_identity("fakepkg", "fake") + assert identity["code"]["verified"] is True # the brick itself is a released install + assert identity["uncertain"] == "eggy: RECORD missing" + library = entry_identity.uncertain_library(identity) + assert library == ("eggy", "2.0", "RECORD missing") + error = entry_identity_uncertain( + "/out", identity["uncertain"], UNCERTAIN_CODE, "fakepkg", library=library + ) + assert "Install a released fakepkg" not in error.message + assert "(eggy: RECORD missing)" in error.message + assert error.fix == ( + "The library eggy 2.0 is installed without a RECORD file (conda and setup.py installs " + "write none), so its files cannot be identified; fakepkg itself needs no change. " + 'Reinstall eggy with pip (pip install --force-reinstall --no-deps "eggy==2.0"), or give ' + "another --output." + ) + + +def test_the_fix_for_the_brick_itself_is_the_adrs(): + assert uncertain_code_fix("fakepkg") == ( + "Install a released fakepkg (not editable, its files as its RECORD lists them), or give " + "another --output." + ) + editable = uncertain_code_fix("fakepkg", ("lib", "1.0", "editable install")) + assert editable.startswith("The library lib is an editable install; fakepkg itself") + # A plain install of the same version would be "already satisfied": pip must reinstall. + assert 'pip install --force-reinstall --no-deps "lib==1.0"' in editable + + +def test_an_uncertain_brick_comes_before_its_libraries(): + brick = { + "uncertain": "demo: editable install", + "code": {"verified": False}, + "libraries": {"eggy": {"version": "2.0", "uncertain": "RECORD missing"}}, + } + assert entry_identity.uncertain_library(brick) is None diff --git a/tests/test_entry_record.py b/tests/test_entry_record.py index 9a6b9053..403aba22 100644 --- a/tests/test_entry_record.py +++ b/tests/test_entry_record.py @@ -12,6 +12,7 @@ import json import os import sys +import warnings import pytest from morphobricks_normalization.contracts import ResolverVersionError @@ -163,12 +164,61 @@ def test_uncertain_identities_are_refused(run): def test_a_first_run_under_an_uncertain_identity_is_published_and_never_reused(run): output = entry.default_output(run.output, "demo") editable = dict(BRICK, uncertain="demo: editable install") - published, record = _compute(run, output, brick=editable) + with pytest.warns(entry.EntryIdentityWarning, match="will never be reused") as caught: + published, record = _compute(run, output, brick=editable) + assert len(caught) == 1 and "(demo: editable install)" in str(caught[0].message) + assert "Install a released demo" in str(caught[0].message) assert published and record["brick"]["uncertain"] == "demo: editable install" with pytest.raises(EntryError, match="computed under an uncertain identity"): entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(3,)) +def test_no_warning_when_the_record_is_not_written(run, tmp_path): + editable = dict(BRICK, uncertain="demo: editable install") + record = _record(run, brick=editable) + folder = tmp_path / "out" + folder.mkdir() + (folder / entry.ENTRY_FILENAME).write_text("{}", encoding="utf-8") + with warnings.catch_warnings(): + warnings.simplefilter("error", entry.EntryIdentityWarning) + with pytest.raises(FileExistsError): + entry.write_entry_record(folder, record) + + +def test_a_certain_first_run_warns_nothing(run): + with warnings.catch_warnings(): + warnings.simplefilter("error", entry.EntryIdentityWarning) + _compute(run, entry.default_output(run.output, "demo")) + + +def test_an_uncertain_library_is_named_on_first_write_and_in_the_refusal(run): + """A released brick with one library installed without RECORD: the fix names the library.""" + libraries = dict( + BRICK["libraries"], + eggy={ + "version": "2.0", + "vcs_commit": None, + "record_sha256": None, + "uncertain": "RECORD missing", + }, + ) + brick = dict(BRICK, libraries=libraries, uncertain="eggy: RECORD missing") + output = entry.default_output(run.output, "demo") + with pytest.warns(entry.EntryIdentityWarning) as caught: + _compute(run, output, brick=brick) + message = str(caught[0].message) + assert "Reinstall eggy with pip" in message and "Install a released demo" not in message + assert entry.identity_warning(_record(run, brick=brick), output).startswith( + f"The output {output} is written, but its code identity is uncertain" + ) + with pytest.raises(EntryError) as raised: + entry.reuse_or_refuse(output, _record(run, brick=brick), supported_resolver_versions=(3,)) + assert raised.value.code == "ENTRY_IDENTITY_UNCERTAIN" + assert "(eggy: RECORD missing)" in raised.value.message + assert raised.value.fix.startswith("The library eggy 2.0 is installed without a RECORD file") + assert "demo itself needs no change" in raised.value.fix + + def test_an_unsupported_resolver_version_is_refused(run): output = entry.default_output(run.output, "demo") _compute(run, output) diff --git a/tests/test_he_tissue_array.py b/tests/test_he_tissue_array.py index 6fd37cb8..bda6e8d6 100644 --- a/tests/test_he_tissue_array.py +++ b/tests/test_he_tissue_array.py @@ -119,13 +119,15 @@ def test_an_input_it_cannot_take_is_refused_before_any_computation( def test_an_unknown_rule_is_refused_before_any_computation(no_computation): - with pytest.raises(ValueError, match="'he_tissue_v2' is not known; the known rules are"): - he_tissue_mask_array(GOOD, rule="he_tissue_v2") + with pytest.raises(ValueError, match="'he_tissue_v3' is not known; the known rules are"): + he_tissue_mask_array(GOOD, rule="he_tissue_v3") @pytest.mark.parametrize("rule", [["he_tissue_v1"], ("he_tissue_v1",), None, 1]) def test_a_rule_that_is_not_one_id_is_a_clear_type_error(rule, no_computation): - with pytest.raises(TypeError, match="The rule is one ID, a str such as he_tissue_v1; got "): + with pytest.raises( + TypeError, match="The rule is one ID, a str such as he_tissue_v1, he_tissue_v2; got " + ): he_tissue_mask_array(GOOD, rule=rule) @@ -133,7 +135,7 @@ def test_its_parameters_are_the_run_routes_and_nothing_more(): signature = inspect.signature(he_tissue_mask_array) assert ( str(signature) - == "(rgb: 'np.ndarray', *, rule: 'str' = 'he_tissue_v1') -> 'TissueMaskArray'" + == "(rgb: 'np.ndarray', *, rule: 'str' = 'he_tissue_v2') -> 'TissueMaskArray'" ) run_route = inspect.signature(helper.he_tissue_mask).parameters["rule"] assert signature.parameters["rule"].default == run_route.default @@ -180,7 +182,8 @@ def test_the_threshold_image_gives_the_mask_its_parts_specify(): | ndimage.binary_dilation(red_cells, _disk(1)) | background ) - found = he_tissue_mask_array(rgb) + # The thresholds of v1 on the image as it is; v2 rescales its white (240) first. + found = he_tissue_mask_array(rgb, rule="he_tissue_v1") assert found.mask.shape == (100, 220) assert np.array_equal(found.mask, ~excluded) for name in ON_THRESHOLD: # one side of each threshold excluded, the other kept @@ -219,13 +222,13 @@ def test_the_record_states_the_rule_its_status_and_the_code_identities_as_found( record = found.record assert isinstance(record, TissueMaskArrayRecord) assert (record.rule_id, record.rule_version, record.status, record.provisional) == ( - "he_tissue_v1", - 1, + "he_tissue_v2", + 2, "provisional", True, ) assert record.operation == "he_tissue_mask" - assert record.rule == helper.current_rule("he_tissue_v1") + assert record.rule == helper.current_rule("he_tissue_v2") assert record.rule_sha256 == rule_sha256(record.rule) # rule_text is the canonical form itself: the exact text its digest is of (issue #345). assert hashlib.sha256(record.rule_text.encode("utf-8")).hexdigest() == record.rule_sha256 diff --git a/tests/test_he_tissue_mask.py b/tests/test_he_tissue_mask.py index ee06ce21..a4685cce 100644 --- a/tests/test_he_tissue_mask.py +++ b/tests/test_he_tissue_mask.py @@ -194,7 +194,7 @@ def test_a_hand_built_rgb_fov_of_a_channels_position_is_refused(tmp_path, monkey run = channels_run(tmp_path) (own,) = run.fovs() no_reads(monkeypatch) - with pytest.raises(ValueError, match="is declared channels; the H&E tissue mask takes a unit"): + with pytest.raises(ValueError, match="was described as separate channels rather than RGB"): run.he_tissue_mask(dataclasses.replace(own, image_type="rgb"), output_mask_id="HETissue") @@ -291,10 +291,10 @@ def test_other_refusals_before_any_read(run, monkeypatch, tmp_path): no_reads(monkeypatch) with pytest.raises(RunInputsError, match="CTRL/rep1/z.tif is not an image of this run"): run.he_tissue_mask(f"{UNIT}/z.tif", output_mask_id="HETissue") - with pytest.raises(ValueError, match="known rules are he_tissue_v1"): - run.he_tissue_mask(IMAGE, output_mask_id="HETissue", rule="he_tissue_v2") + with pytest.raises(ValueError, match="known rules are he_tissue_v1, he_tissue_v2"): + run.he_tissue_mask(IMAGE, output_mask_id="HETissue", rule="he_tissue_v3") # A list of rules is a clear TypeError, not an unhashable one (issue #345). - with pytest.raises(TypeError, match="The rule is one ID, a str such as he_tissue_v1; got list"): + with pytest.raises(TypeError, match="a str such as he_tissue_v1, he_tissue_v2; got list"): run.he_tissue_mask(IMAGE, output_mask_id="HETissue", rule=["he_tissue_v1"]) with pytest.raises(TypeError, match="The rule is one ID, a str"): run.preview_he_tissue_mask(IMAGE, rule=["he_tissue_v1"]) @@ -324,7 +324,9 @@ def test_a_foreign_file_and_an_existing_file_are_refused_before_any_read(run, mo no_reads(monkeypatch) with pytest.raises(ValueError, match="holds masks of the type 'Other' that this helper"): run.he_tissue_mask(IMAGE, output_mask_id="Other") - with pytest.raises(ValueError, match=f"{OUT} exists .* unverified code identity"): + with pytest.raises( + ValueError, match=f"A different mask already exists at {OUT} .* unverified code identity" + ): run.he_tissue_mask(IMAGE, output_mask_id="HETissue") assert tree(run.masks_root) == before @@ -422,7 +424,7 @@ def test_freezing_makes_a_new_mask_under_a_new_id_never_a_relabelled_one( ): provisional = run.he_tissue_mask(IMAGE, output_mask_id="HETissue") before = tree(run.masks_root) - monkeypatch.setitem(helper.RULES, "he_tissue_v1", "frozen") + monkeypatch.setitem(helper.RULES, "he_tissue_v2", "frozen") with pytest.raises(ValueError) as refused: run.he_tissue_mask(IMAGE, output_mask_id="HETissue") assert "differs in: rule, rule_sha256" in str(refused.value) diff --git a/tests/test_he_tissue_rule.py b/tests/test_he_tissue_rule.py index 68732ee9..a23e9a64 100644 --- a/tests/test_he_tissue_rule.py +++ b/tests/test_he_tissue_rule.py @@ -234,8 +234,8 @@ def test_the_rule_record_is_the_designs_and_provisional(): ["remove_pieces_smaller_than_px", 1000], ] assert RULE["connectivity"] == 8 and RULE["disk"] == "x*x + y*y <= r*r" - with pytest.raises(ValueError, match="known rules are he_tissue_v1"): - rule_record("he_tissue_v2", hed_source="x", hed_sha256="0" * 64) + with pytest.raises(ValueError, match="known rules are he_tissue_v1, he_tissue_v2"): + rule_record("he_tissue_v3", hed_source="x", hed_sha256="0" * 64) # B4: the boundary table of §1 ----------------------------------------------------------------- diff --git a/tests/test_he_tissue_v2.py b/tests/test_he_tissue_v2.py new file mode 100644 index 00000000..e8b4a98e --- /dev/null +++ b/tests/test_he_tissue_v2.py @@ -0,0 +1,178 @@ +"""The rule ``he_tissue_v2``: ``he_tissue_v1`` on the plane rescaled to its own white (v0.10.1). + +``he_tissue_v1`` fixes the white at 255. On scans whose glass is grey (Zenodo 4550300's TMA +cores: glass near (127, 135, 145)) every pixel reads as stained, ``H >= 0.05`` everywhere, and +v1 keeps 0 % ("nothing kept: an empty region"). v2 estimates the white per channel as the median +of the brightest 0.1 % of pixels (by ``R + G + B``), rescales with normalization's +``rescale_to_white`` and applies v1's components unchanged. + +- the record: v1's components, version 2, the white stated; v1's record unchanged; +- the estimate, against a plain re-statement of its definition; +- v2 is exactly v1 on the rescaled plane, and v1 itself when the brightest pixels are white; +- a crop of a real core (``tests/data/he_core_1B_D9_crop.npz``, CC-BY-4.0, see + ``tests/data/make_he_core_crop.py``): v1 keeps 0 %, v2 a plausible tissue share, through the + array route and through a run whose TIFF is tagged MINISBLACK with the RGB header override; +- blank slides, white or grey glass: nothing kept. +""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +import numpy as np +import pytest + +pytest.importorskip("skimage") + +from morphobricks_normalization.optical_density import check_white, rescale_to_white # noqa: E402 + +from he_tissue_tree import ( # noqa: E402 + IDENTITY_PATCH, + UNIT, + identities, + pi_style, + rgb_run, + synthetic_he, + threshold_image, +) +from morphobricks_preprocessing import he_tissue_mask as helper # noqa: E402 +from morphobricks_preprocessing import he_tissue_mask_array # noqa: E402 +from morphobricks_preprocessing.he_tissue_rule import ( # noqa: E402 + DEFAULT_RULE, + estimate_white, + rule_record, +) + +CROP = Path(__file__).parent / "data" / "he_core_1B_D9_crop.npz" +CROP_SHA256 = "1d6f85da792938f00b9d64f61016e9a4fbc0cd5981240bf37d6de3f6353dfd14" + + +def record(rule): + return rule_record(rule, hed_source="skimage.color.hed_from_rgb", hed_sha256="0" * 64) + + +def core_crop(): + rgb = np.load(CROP)["rgb"] + assert hashlib.sha256(rgb.tobytes()).hexdigest() == CROP_SHA256 + return rgb + + +def blank(colour, noise, seed=0): + rng = np.random.default_rng(seed) + pixels = rng.normal(colour, noise, (256, 256, 3)) if noise else np.full((256, 256, 3), colour) + return np.clip(np.rint(pixels), 0, 255).astype(np.uint8) + + +# The record ------------------------------------------------------------------------------------- + + +def test_v2_is_v1s_components_with_the_white_estimated(): + v1, v2 = record("he_tissue_v1"), record("he_tissue_v2") + assert DEFAULT_RULE == "he_tissue_v2" + assert (v2["id"], v2["version"], v2["status"]) == ("he_tissue", 2, "provisional") + assert v2["components"] == v1["components"] # no threshold or size changed + assert v2["colour"] == v1["colour"] and v2["combine"] == v1["combine"] + assert v2["input"] == {"image_type": "rgb", "dtype": "uint8", "white": "estimated"} + assert "99.9" in v2["white"]["estimate"] and "median" in v2["white"]["estimate"] + assert v2["white"]["rescale"]["function"] == ( + "morphobricks_normalization.optical_density.rescale_to_white" + ) + # v1 is unchanged: its white fixed, no estimate. + assert v1["version"] == 1 and v1["input"]["white"] == [255, 255, 255] and "white" not in v1 + + +# The estimate ----------------------------------------------------------------------------------- + + +@pytest.mark.parametrize("seed", [0, 1, 2]) +def test_the_white_is_the_median_of_the_brightest_tenth_of_a_percent(seed): + rgb = np.random.default_rng(seed).integers(0, 256, (97, 131, 3), dtype=np.uint8) + flat = rgb.reshape(-1, 3).astype(np.int64) + sums = flat.sum(axis=1) + ordered = np.sort(sums) + position = 0.999 * (len(ordered) - 1) # NumPy's "linear" percentile, written out + below = int(np.floor(position)) + limit = ordered[below] + (position - below) * (ordered[below + 1] - ordered[below]) + expected = tuple(float(np.median(flat[sums >= limit][:, c])) for c in range(3)) + assert estimate_white(rgb) == expected + + +def test_the_white_is_at_least_1_and_a_uniform_plane_is_its_own_white(): + assert estimate_white(np.zeros((8, 8, 3), np.uint8)) == (1.0, 1.0, 1.0) + assert estimate_white(np.full((8, 8, 3), (127, 135, 145), np.uint8)) == (127.0, 135.0, 145.0) + + +# v2 = v1 on the rescaled plane ------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "image", + ["crop", "threshold", "pi1", "pi3", "synthetic"], +) +def test_v2_is_v1_on_the_plane_rescaled_to_its_white(image): + rgb = { + "crop": core_crop, + "threshold": lambda: threshold_image()[0], + "pi1": lambda: pi_style("pi1"), + "pi3": lambda: pi_style("pi3"), + "synthetic": lambda: synthetic_he()[0], + }[image]() + rescaled, _ = rescale_to_white(rgb, check_white(estimate_white(rgb))) + v2 = he_tissue_mask_array(rgb, rule="he_tissue_v2") + v1 = he_tissue_mask_array(rescaled, rule="he_tissue_v1") + assert np.array_equal(v2.mask, v1.mask) + assert dict(v2.record.fractions) == dict(v1.record.fractions) + + +def test_v2_is_v1_itself_when_the_brightest_pixels_are_white(): + rgb = pi_style("pi2") + rgb[:40, :40] = 255 # glass at full white + assert estimate_white(rgb) == (255.0, 255.0, 255.0) + v1 = he_tissue_mask_array(rgb, rule="he_tissue_v1") + v2 = he_tissue_mask_array(rgb, rule="he_tissue_v2") + assert np.array_equal(v1.mask, v2.mask) + + +def test_the_preview_states_the_white_it_rescaled_to(): + rgb = core_crop() + pixels = np.ascontiguousarray(np.moveaxis(rgb, -1, 0)) + v2 = helper.rule_on_plane(pixels, helper.current_rule("he_tissue_v2"), image="crop") + v1 = helper.rule_on_plane(pixels, helper.current_rule("he_tissue_v1"), image="crop") + assert v2.white == estimate_white(rgb) and v1.white is None + assert np.array_equal(v2.rgb, pixels) # the plane read, not the rescaled one + + +# The regression: a real core -------------------------------------------------------------------- + + +def test_v1_keeps_nothing_on_a_grey_glass_core_and_v2_keeps_its_tissue(): + rgb = core_crop() + v1 = he_tissue_mask_array(rgb, rule="he_tissue_v1").record.fractions + assert v1["kept"] == 0.0 and v1["nuclei"] == 1.0 # the reported failure + v2 = he_tissue_mask_array(rgb).record.fractions # the default rule + assert 0.25 <= v2["kept"] <= 0.6 # 0.350: stroma kept + assert 0.3 <= v2["background"] <= 0.7 # 0.515: the glass and the lumen + assert 0.05 <= v2["nuclei"] <= 0.3 # 0.135 + assert v2["red_cells"] < 0.01 + + +@pytest.mark.parametrize( + ("colour", "noise"), + [((255, 255, 255), 0), ((242, 242, 244), 2), ((127, 135, 145), 2), ((127, 135, 145), 0)], +) +def test_a_blank_slide_keeps_nothing(colour, noise): + found = he_tissue_mask_array(blank(colour, noise)) + assert found.record.fractions["kept"] < 0.01 + + +def test_the_run_route_with_the_header_override_keeps_the_cores_tissue(tmp_path, monkeypatch): + monkeypatch.setattr(IDENTITY_PATCH, lambda: identities()) + rgb = core_crop() + # The scanner wrote MINISBLACK for its R, G, B samples: read with the RGB header override. + run = rgb_run(tmp_path, {"a.tif": rgb}, override=True, scanner={"a.tif"}) + result = run.he_tissue_mask(f"{UNIT}/a.tif", output_mask_id="HETissue") + assert result.record["rule"]["version"] == 2 + assert result.record["rgb_header_override"]["image"]["override"] == "used" + assert 0.25 <= result.fractions["kept"] <= 0.6 + assert dict(result.fractions) == dict(he_tissue_mask_array(rgb).record.fractions) diff --git a/tests/test_ignored_masks.py b/tests/test_ignored_masks.py new file mode 100644 index 00000000..06b97501 --- /dev/null +++ b/tests/test_ignored_masks.py @@ -0,0 +1,83 @@ +"""ignored_masks.toml: the strict reader, the canonical text and the manifest entry (v0.10.1).""" + +from __future__ import annotations + +import sys + +import pytest + +from morphobricks_preprocessing.ignored_masks import ( + IGNORED_FILENAME, + IgnoredMasks, + IgnoredMasksError, + ignored_text, + parse_ignored, + read_ignored, + recorded_ignored, +) +from morphobricks_preprocessing.mask_declare import ignore_masks + + +def test_the_text_is_canonical_and_reads_back(): + text = ignored_text(["b", "a", 'q"uote', "b"]) + assert text.endswith('version = 1\nignore = ["a", "b", "q\\"uote"]\n') + assert parse_ignored(text.encode()) == ("a", "b", 'q"uote') + + +@pytest.mark.parametrize( + ("data", "said"), + [ + (b"version = 1\n", "keys version and ignore only"), + (b'version = 1\nignore = ["a"]\nextra = 1\n', "keys version and ignore only"), + (b'version = 2\nignore = ["a"]\n', "reads version 1"), + (b'version = true\nignore = ["a"]\n', "reads version 1"), + (b'version = 1\nignore = "a"\n', "list of names"), + (b'version = 1\nignore = ["a", "a"]\n', "listed twice"), + (b'version = 1\nignore = [" a"]\n', "without leading or trailing spaces"), + (b'version = 1\nignore = ["a/b"]\n', "without '/'"), + (b"\xff", "not UTF-8 TOML"), + (b"version = [", "not UTF-8 TOML"), + ], +) +def test_the_reader_refuses_anything_else(data, said): + with pytest.raises(IgnoredMasksError, match=said.replace("'", ".")): + parse_ignored(data) + + +@pytest.mark.skipif(sys.platform == "win32", reason="symbolic links need privileges on Windows") +def test_no_file_is_nothing_ignored_and_a_link_is_refused(tmp_path): + assert read_ignored(tmp_path) == IgnoredMasks() + target = tmp_path / "elsewhere.toml" + target.write_text('version = 1\nignore = ["a"]\n') + (tmp_path / IGNORED_FILENAME).symlink_to(target) + with pytest.raises(IgnoredMasksError, match="link"): + read_ignored(tmp_path) + + +def test_ignore_masks_adds_removes_declared_and_writes_only_on_change(tmp_path): + assert ignore_masks(tmp_path, ["b", "a"]) == (("a", "b"), True) + assert ignore_masks(tmp_path, ["a"]) == (("a", "b"), False) + assert ignore_masks(tmp_path, (), declared=["a"]) == (("b",), True) + with pytest.raises(IgnoredMasksError, match="declared"): + ignore_masks(tmp_path, ["b"], declared=["b"]) + assert ignore_masks(tmp_path, (), declared=["b"]) == ((), True) + assert not (tmp_path / IGNORED_FILENAME).exists() + with pytest.raises(IgnoredMasksError, match="does not exist"): + ignore_masks(tmp_path / "none", ["a"]) + + +def test_the_manifest_entry_is_checked_as_written_and_read(): + sha = "a" * 64 + assert IgnoredMasks().to_manifest() is None + assert recorded_ignored(None) is None + entry = IgnoredMasks(("a", "b"), sha).to_manifest() + assert recorded_ignored(entry) == {"types": ["a", "b"], "file_sha256": sha} + for bad in ( + {"types": ["b", "a"], "file_sha256": sha}, + {"types": ["a"], "file_sha256": "x"}, + {"types": ["a"]}, + {"types": ["a"], "file_sha256": sha, "more": 1}, + ["a"], + ): + with pytest.raises(ValueError, match="ignored_masks"): + recorded_ignored(bad) diff --git a/tests/test_links.py b/tests/test_links.py index 2318198e..217736b8 100644 --- a/tests/test_links.py +++ b/tests/test_links.py @@ -291,3 +291,45 @@ def test_a_broken_link_in_the_masks_folder_is_named(clean): pre = preflight(clean.experiment, clean.output, masks_folder=clean.masks) issue = _issue(pre.masks.issues, "unreadable_mask") assert issue.is_error and issue.paths == ("Cells/ctrl/rep1/a.tif",) + + +def _says_why_and_what_to_do(issue): + """The refusal says why links out are not followed and what to do instead (4 Dec 2026).""" + assert "not found" in issue.message + assert "fingerprints and records only what is inside it" in issue.message + assert "Move (do not copy) the data into the experiment folder" in issue.action + assert "instant" in issue.action and "remove the links" in issue.action + + +def test_a_file_link_out_says_why_it_is_refused_and_what_to_do(tree): + root, outside = tree + (root / "ctrl/rep1/b.tif").symlink_to(outside / "far.tif") + found = discover_experiment(root) + assert "ctrl/rep1/b.tif" not in found.images + _says_why_and_what_to_do(_issue(found.issues, "link_outside_folder")) + + +def test_a_linked_ome_zarr_store_says_why_it_is_refused_and_what_to_do(tree): + """The owner's case: exp/ctrl/rep1/mosaic.zarr -> a store kept elsewhere.""" + pytest.importorskip("zarr") + from zarr_tree import write_ngff + + root, outside = tree + write_ngff(outside / "mosaic.zarr", np.zeros((3, 4, 4), np.uint16), axes="cyx") + (root / "ctrl/rep1/mosaic.zarr").symlink_to(outside / "mosaic.zarr", target_is_directory=True) + found = discover_experiment(root) + assert "ctrl/rep1/mosaic.zarr" not in found.images + issue = _issue(found.issues, "link_outside_folder") + assert issue.paths == (f"ctrl/rep1/mosaic.zarr -> {(outside / 'mosaic.zarr').resolve()}",) + _says_why_and_what_to_do(issue) + + +def test_a_mask_link_out_tells_to_move_the_mask_into_the_masks_folder(clean): + mask = clean.masks / "Cells/ctrl/rep1/a.tif" + real = clean.masks.parent / "elsewhere.tif" + mask.rename(real) + mask.symlink_to(real) + pre = preflight(clean.experiment, clean.output, masks_folder=clean.masks) + issue = _issue(pre.masks.issues, "link_outside_folder") + assert "Move (do not copy) the data into the masks folder" in issue.action + assert "select that folder as the masks folder" in issue.action diff --git a/tests/test_mask_step.py b/tests/test_mask_step.py index 3060c6c7..55adbb11 100644 --- a/tests/test_mask_step.py +++ b/tests/test_mask_step.py @@ -58,7 +58,7 @@ def test_describe_masks_writes_the_report_the_command_writes(clean, capsys): result.path.unlink() assert main_described(["masks", "--output", str(clean.output)]) == 0 assert without_versions(clean.output / MASK_REPORT_FILENAME) == written - assert f"Report written to {result.path}" in capsys.readouterr().out + assert f"Mask check completed. Relationships saved to {result.path}." in capsys.readouterr().out def test_without_an_experiment_or_a_recorded_run_the_step_is_refused(tmp_path): diff --git a/tests/test_mask_ties.py b/tests/test_mask_ties.py index c784a9af..2a60bf1b 100644 --- a/tests/test_mask_ties.py +++ b/tests/test_mask_ties.py @@ -192,11 +192,12 @@ def test_the_report_and_its_texts_show_the_tie(tmp_path): (written,) = [p for p in data["pairs"] if (p["child"], p["parent"]) == ("Nuclei", "Cells")] assert written["evidence"]["ambiguous_parent"] == 2 assert mask_ambiguous_lines(report) == [ - "Nuclei in Cells: 2 objects of 4 equally in two or more Cells" + "Nuclei in Cells: 2 of 4 Nuclei labels overlap two or more Cells labels equally; no " + "parent was assigned" ] text = mask_report_summary(report) - assert "Objects given no parent (equally in two or more objects" in text - assert "Nuclei in Cells: 2 objects of 4" in text + assert "Objects with no assigned parent because of equal overlap" in text + assert "Nuclei in Cells: 2 of 4 Nuclei labels" in text def test_the_relationship_table_has_the_tied_children(tmp_path): diff --git a/tests/test_notebook_mask_step.py b/tests/test_notebook_mask_step.py index 6f9ace95..b1aab3e3 100644 --- a/tests/test_notebook_mask_step.py +++ b/tests/test_notebook_mask_step.py @@ -161,7 +161,10 @@ def test_a_child_equally_in_two_parents_is_shown_with_no_parent(tmp_path): nb.mask_step_button.click() shown = nb.mask_step_result.value assert "Objects given no parent (a tie, to check)" in shown - assert "
  • nuclei in cells: 4 objects of 4 equally in two or more cells
  • " in shown + assert ( + "
  • nuclei in cells: 4 of 4 nuclei labels overlap two or more cells labels equally; " + "no parent was assigned
  • " in shown + ) def test_a_locked_output_folder_shows_the_lock_card_and_writes_nothing(tmp_path): diff --git a/tests/test_notebook_prerelease.py b/tests/test_notebook_prerelease.py index 4a56698e..06ea9732 100644 --- a/tests/test_notebook_prerelease.py +++ b/tests/test_notebook_prerelease.py @@ -264,10 +264,12 @@ 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 + assert "The published description no longer matches the image headers." in printed def test_the_cli_says_nothing_changed_when_the_headers_are_as_saved(exp, capsys): # noqa: F811 diff --git a/tests/test_notebook_tag_by_repeat_drafts.py b/tests/test_notebook_tag_by_repeat_drafts.py index d24839eb..e54c1131 100644 --- a/tests/test_notebook_tag_by_repeat_drafts.py +++ b/tests/test_notebook_tag_by_repeat_drafts.py @@ -18,7 +18,10 @@ from dataclasses import replace # noqa: E402 from morphobricks_preprocessing.description_file import DRAFT_FILENAME # noqa: E402 -from morphobricks_preprocessing.draft_format import answers_from_bytes, answers_to_bytes # noqa: E402 +from morphobricks_preprocessing.draft_format import ( # noqa: E402 + answers_from_bytes, + answers_to_bytes, +) from test_notebook_channels import set_labels # noqa: E402 from test_notebook_check_save import opened # noqa: E402 from test_notebook_tag_by_repeat import EXTRA # noqa: E402 diff --git a/tests/test_notebook_tissue_mask.py b/tests/test_notebook_tissue_mask.py index 17c74729..56e43987 100644 --- a/tests/test_notebook_tissue_mask.py +++ b/tests/test_notebook_tissue_mask.py @@ -91,7 +91,7 @@ def test_the_preview_writes_nothing_and_shows_the_shares_and_notes(tmp_path, mon ) text = card.numbers.value assert "kept 80.4 % · nuclei 1.6 % · red cells 0.8 % · empty 17.2 %" in text - assert "Sizes are in pixels. Fixed rule he_tissue_v1 (provisional)" in text + assert "Tissue-mask rule: he_tissue_v2 (provisional" in text assert "this mask will not be reused on retry" in text # an unverified identity @@ -108,7 +108,9 @@ def test_the_write_happens_only_on_the_click(tmp_path, monkeypatch): card.button.click() assert f"HETissue/{IMAGE}" in tree(run.masks_root) assert "Written: 1 file(s); already written before: 0." in card.status.value - assert "declare the mask HETissue (source type HETissue) as binary" in card.status.value + assert "declare the mask HETissue as binary" in card.status.value + assert "source_channels" not in card.status.value + assert "region_mask = "HETissue"" in card.status.value assert f"HETissue/{IMAGE}: kept 80.4 %" in card.result.value card.button.click() # the same click again: nothing changes assert "Written: 0 file(s); already written before: 1." in card.status.value diff --git a/tests/test_notebook_ui.py b/tests/test_notebook_ui.py index 08b78c18..7e9fd921 100644 --- a/tests/test_notebook_ui.py +++ b/tests/test_notebook_ui.py @@ -752,7 +752,7 @@ def fail(*args, **kwargs): nb.confirm_button.click() nb.image_type_checked.button.click() plan = nb.plan.value - assert "1 image has planes too large to read whole" in plan + assert "1 image has planes too large to measure whole" in plan assert "will be read in blocks" in plan and "exactly the same" in plan assert "ctrl/rep1/big.tif" in plan and "small.tif" not in plan assert "cannot be read within the memory limit" not in plan diff --git a/tests/test_ome_zarr_chunks.py b/tests/test_ome_zarr_chunks.py new file mode 100644 index 00000000..c0d2d080 --- /dev/null +++ b/tests/test_ome_zarr_chunks.py @@ -0,0 +1,170 @@ +"""OME-Zarr copies in spatial chunks, readable in windows (v0.10.1). + +``convert --store ome-zarr`` wrote each plane as one chunk, so a later brick's windowed route +(``RunInputs.window_reader``) decoded the whole plane for every window and refused the first +patch of a slide (``WindowMemoryError``) after ``check`` had passed. Copies are now written in +chunks of one plane by at most 1024 x 1024 pixels, block by block; ``check`` warns about a +store whose chunks no window reader can serve (``chunks_too_large_for_windows``), and the +reader refuses it when opened, with the same advice. The TIFF slides are written lazily, tile +by tile, and the large single-chunk stores hold metadata only. +""" + +from __future__ import annotations + +import json +import tracemalloc + +import numpy as np +import pytest +import tifffile + +pytest.importorskip("zarr") + +from morphobricks_preprocessing.axes import AxisMapping, prefill_mapping # noqa: E402 +from morphobricks_preprocessing.cli import main # noqa: E402 +from morphobricks_preprocessing.conversion import convert_experiment # noqa: E402 +from morphobricks_preprocessing.ome_zarr_copy import CHUNK_SIDE, chunk_shape # noqa: E402 +from morphobricks_preprocessing.window_chunks import ( # noqa: E402 + CODE, + check_window_chunks, + window_chunk_need, +) +from morphobricks_preprocessing.window_reader import WindowReader, cache_plan # noqa: E402 +from morphobricks_preprocessing.windows import WindowMemoryError, read_window # noqa: E402 +from zarr_tree import Unwritten, write_ngff # noqa: E402 + +C, Y, X, TILE = 2, 3000, 2600, 256 +PLANE = Y * X * 2 # one channel, uint16 +REL = "ctrl/rep1/slide.tif" +COPY = "ctrl/rep1/slide.ome.zarr" +MAPPING = AxisMapping("CYX", ("C", "Y", "X")) +MIB = 2**20 + + +def pixels(c, y0, y1, x0, x1): + """Return the slide's values in a box: a pattern, so every pixel's place is checked.""" + y, x = np.ogrid[y0:y1, x0:x1] + return ((c * 7919 + y * 31 + x * 17) % 65521).astype(np.uint16) + + +def write_slide(path): + """Write the slide tile by tile (never whole in memory), as a scanner's tiled TIFF.""" + + def tiles(): + for c in range(C): + for y in range(0, Y, TILE): + for x in range(0, X, TILE): + tile = np.zeros((TILE, TILE), np.uint16) # edge tiles are padded + part = pixels(c, y, min(y + TILE, Y), x, min(x + TILE, X)) + tile[: part.shape[0], : part.shape[1]] = part + yield tile + + path.parent.mkdir(parents=True, exist_ok=True) + tifffile.imwrite( + path, + tiles(), + shape=(C, Y, X), + dtype=np.uint16, + tile=(TILE, TILE), + photometric="minisblack", + metadata={"axes": "CYX"}, + ) + + +@pytest.fixture(scope="module") +def converted(tmp_path_factory): + tmp = tmp_path_factory.mktemp("slide") + root, dest = tmp / "exp", tmp / "copies" + write_slide(root / REL) + tracemalloc.start() + try: + result = convert_experiment( + root, prefill_mapping("CYX"), dest, store="ome-zarr", memory_limit=8 * MIB + ) + peak = tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + assert result.written and list(result.converted) == [COPY] + assert [i.code for i in result.issues] == ["planes_read_in_blocks"] + return dest, peak + + +def test_the_copy_is_written_in_1024_px_chunks_one_plane_deep(converted): + dest, _ = converted + store = dest / COPY + array = json.loads((store / "0/.zarray").read_text(encoding="utf-8")) + assert array["shape"] == [C, Y, X] + assert array["chunks"] == [1, CHUNK_SIDE, CHUNK_SIDE] == list(chunk_shape((C, Y, X))) + # 3 x 3 chunk files per channel, each full size (an edge chunk too, as Zarr 2 stores it) + found = (store / "0").rglob("[0-9]") + files = sorted(p.relative_to(store / "0").as_posix() for p in found if p.is_file()) + assert files == [f"{c}/{r}/{k}" for c in range(C) for r in range(3) for k in range(3)] + assert {(store / "0" / f).stat().st_size for f in files} == {CHUNK_SIDE * CHUNK_SIDE * 2} + + +def test_the_copy_holds_every_pixel_and_was_never_held_whole(converted): + import zarr + + dest, peak = converted + data = zarr.open(str(dest / COPY / "0"), mode="r") + for c in range(C): + assert np.array_equal(data[c], pixels(c, 0, Y, 0, X)) + assert peak < PLANE / 2 # written block by block: never one plane, let alone the image + + +def test_a_small_plane_is_one_chunk_no_larger_than_itself(): + assert chunk_shape((3, 4, 16, 20)) == (1, 1, 16, 20) + assert chunk_shape((5000, 700)) == (1024, 700) + + +def test_a_window_of_the_copy_is_read_within_the_memory_limit(converted): + dest, _ = converted + path, limit = dest / COPY, 64 * MIB + assert window_chunk_need(path, MAPPING, limit) < limit + assert check_window_chunks(dest, {COPY: MAPPING}, memory_limit=limit) == [] + plan = cache_plan(path, MAPPING, window=(512, 512), margin=(32, 32), channels=[0, 1]) + with WindowReader(path, MAPPING, cache_bytes=plan.cache_bytes, memory_limit=limit) as reader: + bounds = (900, 1700, 1000, 1800) # across four chunks + window = reader.read_window(bounds=bounds, channels=[1, 0]) + assert reader.window_plan(bounds=bounds, channels=[1, 0]).memory_estimate <= limit + expected = np.stack([pixels(c, 900, 1700, 1000, 1800) for c in (1, 0)]) + assert np.array_equal(window, expected) + + +def test_the_same_image_in_one_chunk_per_plane_is_named_and_refused(tmp_path): + # The copy as v0.10.1 wrote it before the fix: the same pixels, one chunk per plane. + data = np.stack([pixels(c, 0, Y, 0, X) for c in range(C)]) + root, rel, limit = tmp_path / "exp", "ctrl/rep1/slide.ome.zarr", 32 * MIB + path = write_ngff(root / rel, data, axes="cyx") + assert window_chunk_need(path, MAPPING, limit) > 4 * PLANE + (issue,) = check_window_chunks(root, {rel: MAPPING}, memory_limit=limit) + assert issue.code == CODE and not issue.is_error and issue.paths == (rel,) + assert "even a window of one pixel" in issue.message + assert "convert the original images again into a new folder" in issue.action + assert "1024 x 1024" in issue.action + with pytest.raises(WindowMemoryError) as opened: + WindowReader(path, MAPPING, cache_bytes=MIB, memory_limit=limit) + text = str(opened.value) + assert f"chunks of {Y} x {X} pixels" in text and "convert the original images" in text + with pytest.raises(WindowMemoryError) as read: # without a reader, the same advice + read_window(path, MAPPING, bounds=(0, 1, 0, 1), channels=[0], memory_limit=limit) + assert f"chunks of {Y} x {X} pixels" in str(read.value) + + +def test_check_warns_about_a_slide_stored_in_one_chunk_per_plane(tmp_path, capsys): + # A 12000 x 12000 slide (metadata only): preprocessing reads it in blocks, so the run's + # check passes, but a 275 MiB chunk is decoded whole for every window: no reader serves it. + root, out = tmp_path / "exp", tmp_path / "out" + for condition in ("a", "b"): + write_ngff(root / condition / "slide.zarr", Unwritten((2, 12000, 12000), "uint16"), "cyx") + describe = ["describe", str(root), "--output", str(out), "--channels", "DNA,ACTIN"] + describe += ["--image-type", "channels", "--accept-ids", "--comparable"] + assert main([*describe, "--confirmed-on", "2026-12-04", "--publish"]) == 0 + capsys.readouterr() + assert main(["check", str(root), "--output", str(out)]) == 0 # a warning, not an error + text = capsys.readouterr().out + assert "2 OME-Zarr images cannot be read in windows within the memory limit of 1.0 GiB" in text + assert " - a/slide.zarr\n - b/slide.zarr" in text + assert "convert the original images again" in text + report = json.loads((out / "discovery_report.json").read_text(encoding="utf-8")) + assert CODE in json.dumps(report) diff --git a/tests/test_plane_memory_names.py b/tests/test_plane_memory_names.py new file mode 100644 index 00000000..f3dc2506 --- /dev/null +++ b/tests/test_plane_memory_names.py @@ -0,0 +1,86 @@ +"""The two plane memory figures, named apart (owner's mosaic run of 4 December 2026). + +For one plane of the formin mosaic (OME-Zarr, 30720 x 36864, 3 channels, uint16, chunks +1 x 1024 x 1024) the run warned that its planes "would need up to 38.0 GiB" while +``xyc_plane_memory`` (the bound ``RunInputs.read_plane`` enforces) gave about 14.8 GiB. Both +are right, and different: the run's figure is one channel read *and measured* (most of it +the histogram's working arrays), the other the pixels of all three channels with no +histogram. The texts now say which is which. The store is written lazily (metadata only). +""" + +from __future__ import annotations + +import numpy as np +import pytest +from morphobricks_normalization.histogram import estimate_histogram_memory + +from morphobricks_preprocessing.axes import AxisMapping +from morphobricks_preprocessing.image_qc import qc_memory +from morphobricks_preprocessing.plane_channels import ( + OPEN_BYTES, + ZARR_COPIES, + read_xyc_plane, + xyc_plane_memory, +) +from morphobricks_preprocessing.planes import ( + PlaneMemoryError, + check_planes, + format_bytes, + plane_layout, +) + +pytest.importorskip("zarr") +from zarr_tree import Unwritten, write_ngff # noqa: E402 + +Y, X, C = 30720, 36864, 3 +CHUNK = 1024 +REL = "ctrl/rep1/formin_mosaic.zarr" +MAPPING = AxisMapping("CYX", ("C", "Y", "X")) +PLANE = Y * X * 2 # one channel, uint16 +CHUNKS = (Y // CHUNK) * (X // CHUNK) * CHUNK * CHUNK * 2 # every chunk one plane touches + + +@pytest.fixture +def mosaic(tmp_path): + root = tmp_path / "exp" + write_ngff(root / REL, Unwritten((C, Y, X), "uint16"), axes="cyx", chunks=(1, CHUNK, CHUNK)) + store_bytes = sum(f.stat().st_size for f in (root / REL).rglob("*") if f.is_file()) + assert store_bytes < 64 * 1024 # metadata only: no chunk is written + return root + + +def test_the_run_figure_is_one_channel_read_and_measured(mosaic): + layout = plane_layout(mosaic / REL, MAPPING) + histogram = estimate_histogram_memory(Y * X, np.dtype("uint16"), range_check=True) + finished = C * 8 * 65536 + assert layout.memory_estimate == ( + CHUNKS + PLANE + histogram + qc_memory(Y, X, False) + finished + ) + assert histogram > 0.8 * layout.memory_estimate # mostly the histogram's arrays + assert format_bytes(layout.memory_estimate) == "38.0 GiB" + + +def test_the_read_plane_figure_is_every_channel_without_a_histogram(mosaic): + memory = xyc_plane_memory(mosaic / REL, MAPPING) + assert memory == (C + 1) * PLANE + ZARR_COPIES * CHUNKS + OPEN_BYTES + assert format_bytes(memory) == "14.8 GiB" + assert format_bytes(xyc_plane_memory(mosaic / REL, MAPPING, 1)) == "10.5 GiB" + + +def test_the_run_warning_names_its_figure_as_one_channel_measured(mosaic): + issues = check_planes(mosaic, {REL: MAPPING}) + (issue,) = issues + assert issue.code == "planes_read_in_blocks" and issue.paths == (REL,) + assert "38.0 GiB" in issue.message and "one channel" in issue.message + assert "one channel and its histogram" in issue.message + assert "all channels without a histogram needs another amount" in issue.message + assert "would need up to 38.0 GiB" in issue.message + assert "raise the memory limit to 38.0 GiB" in issue.action + + +def test_the_read_plane_refusal_names_its_figure_as_pixels_only(mosaic): + with pytest.raises(PlaneMemoryError) as caught: + read_xyc_plane(mosaic / REL, MAPPING) + text = str(caught.value) + assert "all 3 channels" in text and "14.8 GiB" in text + assert "the pixels only: no histogram is computed" in text diff --git a/tests/test_report.py b/tests/test_report.py index 4c9dafa6..e0abf13f 100644 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -124,7 +124,7 @@ def test_run_summaries(experiment): def test_run_summary_when_blocked(experiment): result = run_described(experiment, prefill_mapping("TYX"), bin_count=0) - assert run_summary(result).startswith("The run stopped (1 error") + assert run_summary(result).startswith("Preprocessing stopped (1 error") def test_group_summaries_pool_the_planes(experiment): diff --git a/tests/test_run_description.py b/tests/test_run_description.py index def8459c..7d6e3541 100644 --- a/tests/test_run_description.py +++ b/tests/test_run_description.py @@ -111,7 +111,9 @@ def test_an_invalid_description_stops_the_run_with_its_code_and_path(tmp_path): assert not result.written and not (out / "run_manifest.json").exists() assert result.issues and all(i.is_error for i in result.issues) assert result.issues[0].code.startswith("E_") - assert "morphobricks.toml cannot be used" in result.issues[0].message + message = result.issues[0].message # its plain meaning first, then the path and code + assert "The experiment description (morphobricks.toml) is not an experiment" in message + assert "(at schema, value 'wrong', E_SCHEMA_ID)" in message def test_an_unreadable_records_file_stops_the_run(tmp_path): diff --git a/tests/test_stopped_run_text.py b/tests/test_stopped_run_text.py index a8290d96..aa23bae7 100644 --- a/tests/test_stopped_run_text.py +++ b/tests/test_stopped_run_text.py @@ -27,8 +27,8 @@ def test_a_stopped_api_run_records_that_its_report_was_written(tmp_path): result = run_described(root, prefill_mapping("ZYX"), output_folder=output) # wrong roles assert not result.written and result.report_written text = run_summary(result) - assert text.startswith("The run stopped (") - assert "no table or manifest was written" in text + assert text.startswith("Preprocessing stopped (") + assert "No new histogram table or run manifest was published" in text assert f"Written to {output}: discovery_report.json and discovery_report.txt" in text assert "experiment_design.csv" not in text diff --git a/tests/zarr_tree.py b/tests/zarr_tree.py index cb5a9c39..70485a87 100644 --- a/tests/zarr_tree.py +++ b/tests/zarr_tree.py @@ -15,6 +15,20 @@ def zarr_major() -> int: return int(zarr.__version__.split(".")[0]) +class Unwritten: + """An image's shape and type only: :func:`write_ngff` writes its metadata, no chunk. + + Reading it gives zarr's fill value (0); the store holds no pixel, so an image of any + size (the 30720 x 36864 x 3 mosaic of the owner's 4 December 2026 run) costs a few + kilobytes on disk. + """ + + def __init__(self, shape, dtype): + self.shape = tuple(shape) + self.dtype = np.dtype(dtype) + self.ndim = len(self.shape) + + def write_ngff( # noqa: PLR0913 path, data, @@ -44,7 +58,8 @@ def write_ngff( # noqa: PLR0913 pytest.skip("OME-NGFF 0.5 needs zarr 3") path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) - data = np.asarray(data) + if not isinstance(data, Unwritten): + data = np.asarray(data) group = _group(zarr, path, 3 if version == "0.5" else 2) chunks = chunks or (*(1,) * (data.ndim - 2), *data.shape[-2:]) _array(group, "0", data, chunks) @@ -139,5 +154,6 @@ def _array(group, name, data, chunks): array = group.create_array(name, shape=data.shape, chunks=chunks, dtype=data.dtype) else: array = group.create_dataset(name, shape=data.shape, chunks=chunks, dtype=data.dtype) - array[...] = data + if not isinstance(data, Unwritten): + array[...] = data return array