diff --git a/AGENTS.md b/AGENTS.md index b513a96f..09cfface 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -378,8 +378,11 @@ 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; @@ -1098,7 +1101,7 @@ Technical details go to `logging` (shown in the notebook's "Technical details" p | Histogram range (Q34, P6) | Step 3 **Settings**: the brick's `HistogramSettings` (`minmax` default, or `robust` with adjustable quantiles); recorded in the manifest's `settings.histogram`, any change recomputes every row. Every plane binned with `histogram_with_range_check` (memory estimate with `range_check=True`, through `planes._Binning`); `narrow_histogram_range` warnings from `range_check_issues`, one per channel, with the narrow planes recorded in the manifest's `narrow_histogram_ranges` so kept rows still report them. CSV schema 4 (underflow and overflow columns, zero with `minmax`); schema 3 tables recomputed. CLI `--histogram-range`, `--robust-quantiles`. Normalization brick pinned to v0.3.1 | | Position identity (Q20, D02) | `position_id` = image name without extension, in every CSV row and manifest file entry; FOV key = labels + `position_id`; duplicates in one leaf folder are the error `duplicate_position_id`. CSV columns and schema 2 unchanged; manifest version 1 with an optional key | | Masks (Q32) | Optional masks folder outside the experiment, one subfolder per mask type mirroring the experiment's folders, or the experiment's folders with `_.tif` (both may be mixed; `ambiguous_mask` when a name could fit two images or both layouts), paired by leaf folder + `position_id`; OME-Zarr label images are masks too. Header-only errors (`masks_folder_not_found`, `masks_inside_experiment`, `mask_names_differ_in_case`, `duplicate_mask`, `ambiguous_mask`, `unreadable_mask`, `mask_not_2d`, `mask_size_mismatch`, `mask_pixel_type`) and warnings (`mask_missing`, `mask_without_image`, `mask_outside_type_folder`) in `check`/`run`; manifest key `masks` (optional, version 1). Optional mask step (`masks` command, `scan_masks`): kinds, relations with evidence, direct-parent hierarchy, `mask_relationships.json` (report version 1); default thresholds the user may change (`thresholds=` keyword, one CLI option each, checked by `mask_thresholds`, written in the report); suggestions only, the user names and confirms. SciPy core dependency. Confirmed by the owner: 2D masks at the image's YX, integer/bool pixels, masks folder outside the experiment. Next: notebook step and a file of the user's answers; tag v0.2.0 proposed after merge. Plane identity (issue #36): masks may have Z and/or T named in their own metadata (never guessed: unnamed axes are `mask_not_2d`); the masks of an image share their planes (`mask_planes_differ`) and `run` checks them against the image's confirmed roles (`mask_planes_mismatch`, `mask_plane_issues`), so a 2D mask is refused for a Z-stack or time-lapse; manifest mask entries gain `axes` and `shape` (optional keys, version 1); `read_mask(z=, t=)` reads one plane; `scan_masks` scans plane by plane | -| H&E tissue mask (I1, BM15) | Opt-in only (`he-mask` extra; scikit-image, normalization's `stain` and the helper imported only when called). Fixed rule `he_tissue_v1`, provisional until its acceptance report is accepted; no per-call thresholds; sizes in pixels; colour maths from normalization only. One `uint8` region per image through BM12's publication with BM15's own line and comparator; an unverified code identity writes a mask never reused; freezing needs a new mask ID (design `docs/design/he-tissue-mask.md`, owner decisions of 16 November 2026) | +| H&E tissue mask (I1, BM15) | Opt-in only (`he-mask` extra; scikit-image, normalization's `stain` and the helper imported only when called). Fixed rules, provisional until an acceptance report is accepted: `he_tissue_v1` (white fixed at 255) and, the default since v0.10.1, `he_tissue_v2` (v1 on the plane rescaled to its white, the median of its brightest 0.1 %; v1 kept 0 % on grey-glass scans such as Zenodo 4550300); no per-call thresholds; sizes in pixels; colour maths from normalization only. One `uint8` region per image through BM12's publication with BM15's own line and comparator; an unverified code identity writes a mask never reused; freezing needs a new mask ID (design `docs/design/he-tissue-mask.md`, owner decisions of 16 November 2026) | | Settings (ADR 0011, Q89) | `defaults.toml` (package data) declares the run's (`common`) and Cellpose's (`cellpose`) settings with default, unit and help; `morphobricks_preprocessing.settings` loads, modifies, saves and passes them with the five shared names on the vendored `_brick_settings.py` (never edited; re-vendored from the Spec); the classes, CLI defaults and notebook widgets are copies held equal by `tests/test_settings.py`; no Cellpose CLI option | | Notebook style | Follow the lab's NucleiSky and LabChronicle notebooks (see §7) | | Widget widths | **99%**, never 100% | diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cca45e7..3aaf25eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,30 @@ The design is [`docs/design-v0.4.md`](docs/design-v0.4.md), imported unchanged f are in [docs/plan.md](docs/plan.md) §12. (The v0.3 to v0.4 migration guide was removed in v0.5.1: no run before v0.5.1 is read.) +## Unreleased (v0.10.1) + +### Fixed + +- **The H&E tissue mask kept nothing on scans whose glass is not white.** On the Zenodo 4550300 + H&E TMA cores (glass near (127, 135, 145), photometric tag MINISBLACK read with + `rgb_header_override = true`), `tissue-mask` printed "kept 0.0 % (nothing kept: an empty + region)" for every core, so fiberfeatures measured `roi_area_px = 0` and NaN features. The + channel order, the override and the mask's polarity were correct: rule `he_tissue_v1` fixes the + white at 255, so against it every pixel of these scans has an optical density of at least 0.22, + the background never fires, `H >= 0.05` holds everywhere and the whole plane was "nuclei". + New rule **`he_tissue_v2`** (provisional), the default of `RunInputs.he_tissue_mask`, + `RunInputs.preview_he_tissue_mask`, `he_tissue_mask_array`, `tissue-mask --rule` and the + notebook card: v1 on the plane rescaled to its own white, estimated per channel as the median + of the brightest 0.1 % of pixels (by R + G + B) and applied with normalization's + `rescale_to_white`. v1's thresholds and sizes are unchanged; v1 itself is unchanged and still + offered (`rule="he_tissue_v1"`). Kept share on cores 1B_D9 and 2B_A6: 0.0 % -> 46.8 % and + 44.4 %; on white-glass slides (CMU-1) v2 is within 0.4 points of v1, and identical when the + brightest pixels are 255; blank slides keep nothing. A mask written under v1 is not reused under + v2 (another rule record): use a new output mask ID. `TissueMaskPreview.white` gives the white + used (`None` under v1). Regression fixture: a 320 x 320 crop of core 1B_D9 + (`tests/data/he_core_1B_D9_crop.npz`, CC-BY-4.0, with its generator). Design: + `docs/design/he-tissue-mask.md` ("`he_tissue_v2`"). + ## v0.10.0 (3 December 2026) Minor release with a **breaking change of file format**: the histogram table is diff --git a/README.md b/README.md index 4392d910..dcb2d0bd 100644 --- a/README.md +++ b/README.md @@ -99,8 +99,8 @@ and installs missing requirements into the active kernel. A standalone download installs from GitHub if needed (internet access and Git required). The optional `he-mask` extra installs scikit-image (through `morphobricks-normalization[histology]`) -for the opt-in H&E tissue mask (`tissue-mask`, `RunInputs.he_tissue_mask`; rule `he_tissue_v1`, -provisional); without it, nothing of that helper is imported. `he_tissue_mask_array(rgb)` computes +for the opt-in H&E tissue mask (`tissue-mask`, `RunInputs.he_tissue_mask`; rule `he_tissue_v2` +by default, provisional); without it, nothing of that helper is imported. `he_tissue_mask_array(rgb)` computes the same mask on a `uint8` `(Y, X, 3)` array with no run and writes nothing (no lineage; for runs, use `tissue-mask`); see the [user guide](docs/user_guide.md#an-he-tissue-mask-optional) and [contract §15.4](docs/contract.md#154-the-he-tissue-mask-of-an-array-with-no-run-roadmap-k3). diff --git a/docs/contract.md b/docs/contract.md index 0a46176c..f15066d1 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1220,11 +1220,11 @@ time. An opt-in helper, never run by default, computes a `binary` **region** mask from one declared RGB image with a named, versioned, fixed rule whose colour maths is normalization's (`docs/design/he-tissue-mask.md`). `RunInputs.he_tissue_mask(fov, *, output_mask_id, -rule="he_tissue_v1")` writes it and returns `TissueMaskResult` (`image`, `mask_id`, `path`, +rule="he_tissue_v2")` writes it and returns `TissueMaskResult` (`image`, `mask_id`, `path`, `line`, `published`, `reusable`, `fractions`); `RunInputs.preview_he_tissue_mask(fov, *, -rule="he_tissue_v1")` computes it in memory and returns `TissueMaskPreview` (`E`, `H`, `od`, -`od_floored` exactly as normalization returns them, the components, `fractions`, the rule record -and the code identities); it writes nothing. The command `tissue-mask` and the notebook card +rule="he_tissue_v2")` computes it in memory and returns `TissueMaskPreview` (`E`, `H`, `od`, +`od_floored` exactly as normalization returns them, the components, `fractions`, the rule record, +the code identities and `white`, the white the plane was rescaled to, `None` under v1); it writes nothing. The command `tissue-mask` and the notebook card **Make an H&E tissue mask** call them. scikit-image (the `he-mask` extra: `pip install "morphobricks-preprocessing[he-mask]"`, which installs `morphobricks-normalization[histology]`), normalization's `stain` module and the helper's module @@ -1245,6 +1245,20 @@ means fewer than N pixels, a disk is `x*x + y*y <= r*r`, the structuring element the image border (never padded or wrapped; the opening's erosion counts only pixels inside the image), and every size is in pixels: no pixel size is read or used. +**The rule `he_tissue_v2` (v0.10.1, the default; also provisional)** is `he_tissue_v1` on the plane +rescaled to its own white. v1's white is fixed at 255, so on a scan whose glass is grey (the +Zenodo 4550300 TMA cores, glass near (127, 135, 145)) every pixel reads as stained and v1 keeps +0 %. v2 estimates the white per channel as the median of the pixels whose `R + G + B` is at or +above the 99.9th percentile of `R + G + B` (NumPy, method `linear`), at least 1; rescales the plane +with normalization's `rescale_to_white` (`clip(rint(I * 255 / white), 0, 255)` as `uint8`); and +applies v1's components, thresholds and clean-up unchanged to the rescaled plane (`E`, `H` and +`od` are then the rescaled plane's). When the plane's brightest pixels are white (255) the +rescaling is the identity and v2 equals v1. The white is read from the plane, so a plane with no +glass or empty space takes its brightest tissue as white. The rule record (version 2, +`input.white` `"estimated"`, a `white` entry stating the estimate and the rescaling) is written in +the lineage like v1's; the white itself is not a lineage key (it follows from the source content +digest and the rule record). `he_tissue_v1` stays offered unchanged with `rule="he_tissue_v1"`. + **Inputs, refused before any pixel is read** (a `ValueError` naming the position): the position is resolved by its image path from `RunInputs.fovs()`, and a caller's `image_type`, axes, counts or dtype are ignored; an image that is not the run's (`RunInputsError`); a unit not declared @@ -1295,10 +1309,10 @@ object at any depth is refused in both schemas (it was kept silently before). ### 15.4 The H&E tissue mask of an array, with no run (roadmap K3) -`he_tissue_mask_array(rgb, *, rule="he_tissue_v1") -> TissueMaskArray` (owner decision of +`he_tissue_mask_array(rgb, *, rule="he_tissue_v2") -> TissueMaskArray` (owner decision of 17 November 2026: in preprocessing) computes §15.3's rule on one image array in memory, for users who have pixels but no MorphoBricks run (a script, another brick's folder command). **The -rule is the same provisional `he_tissue_v1`**, and the computation is the run route's own: the +rules are the same provisional `he_tissue_v2` (the default) and `he_tissue_v1`**, and the computation is the run route's own: the array is moved to `(3, Y, X)` and given to the one function `RunInputs.he_tissue_mask` and `preview_he_tissue_mask` call after their read (`he_tissue_mask.rule_on_plane`), never a copy, so the mask is bitwise equal to the file the run route writes for the same pixels (tested on the @@ -1319,11 +1333,12 @@ a pixel type other than `uint8`, or a shape other than `(Y, X, 3)` (R, G, B last (`ImportError` naming `pip install "morphobricks-preprocessing[he-mask]"`). The input checks import nothing of the extra; scikit-image, normalization's `stain` module and the helper's module are imported only past them, never by `import morphobricks_preprocessing`. Like the run -route it takes no pixel size (sizes are pixels), no white (fixed at 255) and no thresholds. +route it takes no pixel size (sizes are pixels), no white (fixed at 255 under v1, estimated from +the plane under v2) and no thresholds. **Result.** `TissueMaskArray` (frozen): `mask`, boolean `(Y, X)`, `True` kept (a region, BM3; being boolean, an in-memory consumer refuses it as an object set, BM4); and `record`, a frozen -`TissueMaskArrayRecord`: `rule_id` (`"he_tissue_v1"`), `operation` (`"he_tissue_mask"`), +`TissueMaskArrayRecord`: `rule_id` (`"he_tissue_v2"` by default), `operation` (`"he_tissue_mask"`), `rule_text` (the complete rule record in its canonical JSON, keys sorted and no spaces: exactly the text `rule_sha256` is the SHA-256 of, as UTF-8; `rule` returns it as a new dict, with `rule_version`, `status` `"provisional"` and `provisional`), `rule_sha256`, `code` (BM15's code diff --git a/docs/design/he-tissue-mask.md b/docs/design/he-tissue-mask.md index 753407da..9631ac0f 100644 --- a/docs/design/he-tissue-mask.md +++ b/docs/design/he-tissue-mask.md @@ -184,6 +184,65 @@ changes v1. The complete rule record (below) and its SHA-256 are written to the tuned per image, and nothing is tuned silently. The preview and the "% kept" figure are how the user judges whether the rule suits their slides. +### `he_tissue_v2`: the white estimated from the plane (v0.10.1) + +**Why (3 December 2026).** On the Zenodo 4550300 H&E TMA cores (set B of criterion 3; 2048 x 2048 +`uint8` RGB, photometric tag wrongly MINISBLACK, read with `rgb_header_override = true`), +`tissue-mask` kept **0.0 %** of every core, so fiberfeatures measured `roi_area_px = 0`. The +channels are R, G, B in order (the override is applied before the rule) and the mask is not +inverted: the scanner's glass is near **(127, 135, 145)**, not 255, and the brightest pixel of +1B_D9 is (138, 154, 154). Against v1's fixed white of 255 every pixel has `OD >= 0.22`, so the +background (`max(OD) < 0.08`) never fires and `H >= 0.05` holds everywhere: the whole plane was +"nuclei" (`fractions` `nuclei` 1.0). + +**The rule.** `he_tissue_v2` is v1 on the plane rescaled to its own white: + +1. the white, per channel: the median of the pixels whose `R + G + B` is at or above the 99.9th + percentile of `R + G + B` (NumPy `percentile`, method `linear`), raised to at least 1 + (`he_tissue_rule.estimate_white`; counting only, no colour maths); +2. the plane rescaled with normalization's `rescale_to_white` (N69: + `clip(rint(I * 255 / white), 0, 255)` as `uint8`, `rint` half to even); +3. v1's components, thresholds and clean-up, unchanged, on the rescaled plane (`E` and `H` from + `he_eosin`, `OD` against 255). + +No threshold or size of v1 changed (the record's `components` are v1's). The record is version 2, +`input.white` `"estimated"`, with a `white` entry stating steps 1 and 2; v1 is unchanged and +still offered (`rule="he_tissue_v1"`). v2 is the default of `RunInputs.he_tissue_mask`, +`preview_he_tissue_mask`, `he_tissue_mask_array`, `tissue-mask` and the notebook card. Both are +provisional; the acceptance criteria above apply to v2 as they did to v1. The estimated white is +in the preview (`TissueMaskPreview.white`), not in the lineage line, whose source digest and rule +record determine it (the BM15 line keys are unchanged). + +**Measured (3 December 2026, scikit-image 0.26.0, normalization v0.10.0).** Kept share: + +| Image | v1 kept | v2 white | v2 kept | v2 background | v2 nuclei | +| --- | --- | --- | --- | --- | --- | +| Zenodo `1B_D9_WB.tif` (SHA-256 `8c74cadd…`) | 0.00 % | (130, 138, 149) | 46.8 % | 41.9 % | 11.3 % | +| Zenodo `2B_A6_WB.tif` (SHA-256 `6e49f686…`) | 0.00 % | (127, 134, 142) | 44.4 % | 52.6 % | 2.9 % | +| Zenodo `1B_F3_WB.tif` | 0.00 % | (136, 147, 168) | 52.6 % | 28.4 % | 19.1 % | +| Zenodo `2B_G5_WB.tif` | 0.00 % | (141, 143, 153) | 40.6 % | 44.7 % | 14.8 % | +| Zenodo `2B_H2_WB.tif` | 0.00 % | (141, 142, 152) | 38.3 % | 44.7 % | 17.0 % | +| Zenodo `2B_G3_WB.tif` | 0.00 % | (141, 143, 152) | 29.8 % | 66.4 % | 3.8 % | +| Zenodo `2B_E9_WB.tif` (a thin strip of tissue) | 0.00 % | (127, 134, 143) | 7.2 % | 85.8 % | 7.0 % | + +(the seven cores of the record's `validation2.zip`, SHA-256 `f7eb874b…`). On CMU-1 (set A, white +glass), 33 tiles of 1024 x 1024 at level 1 with at least 5 % tissue: the estimated white is +251 to 255 in every channel and v2's kept share is within 0.4 points of v1's on every tile; the 12 +level-1 tiles of 512 x 512 with the least near-white (2 to 7 %): Dice of v1 and v2 masks 0.978 to +0.998. Blank slides (uniform 255, glass at 242 or at (127, 135, 145) with noise): 0 % kept under +both rules. The PI-1 to PI-4 images (owner's, not public) were not rerun; their v1 numbers above +stand, and v2 equals v1 on any plane whose brightest 0.1 % are white. + +**Limitation.** The white is read from the plane: a plane with no glass, lumen or fat (tissue +from edge to edge) takes its brightest tissue as white, and pale tissue then moves towards +background. The preview and the printed kept share show it; `rule="he_tissue_v1"` is the choice +for such planes on a white-balanced scanner. + +**Regression fixture.** `tests/data/he_core_1B_D9_crop.npz`: rows 500-819, columns 80-399 of +`1B_D9_WB.tif` (CC-BY-4.0, Eliceiri, Li, Keikhosravi 2021, doi 10.5281/zenodo.4550300), written by +`tests/data/make_he_core_crop.py` from the checked zip. v1 keeps 0 % of it, v2 35.0 % +(`tests/test_he_tissue_v2.py`, also through a run with the header override). + ### The canonical rule record The rule is defined once, as an immutable record in the helper's module, and written whole into diff --git a/docs/user_guide.md b/docs/user_guide.md index 1d4ade7c..568a4ac2 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1385,8 +1385,12 @@ pip install "morphobricks-preprocessing[he-mask]" morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preprocessing --to HETissue ``` -- It is a **fixed rule**, `he_tissue_v1`, and it is **provisional**: its numbers are not frozen - until an acceptance report is accepted. It is not a trained segmentation. Its colour maths is +- It is a **fixed rule**, `he_tissue_v2` by default, and it is **provisional**: its numbers are + not frozen until an acceptance report is accepted. `he_tissue_v2` first measures each image's + white from its brightest pixels (the glass), so scans whose glass is grey rather than white + work; `--rule he_tissue_v1` keeps the white fixed at 255 (it keeps nothing on such scans). An + image with no glass or empty space at all takes its brightest tissue as white: check the + "kept" share. It is not a trained segmentation. Its colour maths is the normalization brick's (the eosin and hematoxylin maps of the `he_eosin` preset and the optical density per channel), and all its sizes are **in pixels**: the same rule on images of another magnification leaves out pieces of another physical size. Look at the preview (in the @@ -1409,7 +1413,7 @@ morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preproce source_type = "HETissue" representation = "binary" source_channels = ["R", "G", "B"] - display_name = "H&E tissue (he_tissue_v1)" + display_name = "H&E tissue (he_tissue_v2)" ``` For example fiberfeatures `MaskRequest("HETissue", "region")`. It is never a set of cells: do diff --git a/pyproject.toml b/pyproject.toml index ffde5b95..44d4b17e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -440,6 +440,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.code_identity" = "io" "morphobricks_preprocessing.he_tissue_rule" = "pure" "morphobricks_preprocessing.he_tissue_mask" = "orchestration" +"morphobricks_preprocessing.he_tissue_run_facts" = "orchestration" "morphobricks_preprocessing.he_tissue_array" = "orchestration" "morphobricks_preprocessing.run_inputs_tissue" = "orchestration" "morphobricks_preprocessing.cli_tissue_mask" = "ui" diff --git a/src/morphobricks_preprocessing/cli_tissue_mask.py b/src/morphobricks_preprocessing/cli_tissue_mask.py index dfc86b1a..2539f678 100644 --- a/src/morphobricks_preprocessing/cli_tissue_mask.py +++ b/src/morphobricks_preprocessing/cli_tissue_mask.py @@ -1,16 +1,16 @@ """The command line's ``tissue-mask``: the opt-in H&E tissue mask helper (Spec ADR 0005 BM15). -``tissue-mask --output FOLDER --to NEW_ID`` writes, for every image of the run in ``--output`` -whose unit is declared ``rgb`` (or only the ``--image`` paths given, repeatable), its H&E tissue -mask as the new ``binary`` region mask ``NEW_ID`` (``RunInputs.he_tissue_mask``, rule -``he_tissue_v1``, provisional): nuclei, red blood cells and empty space left out, sizes in -pixels. The outputs go to the run's masks folder, each with its line of ``mask_lineage.jsonl``; -the image is never changed and nothing is overwritten. A same call again is a no-op, unless a -code identity is unverified: such a mask is written but never reused, so a retry is refused. -The command prints what it wrote, the kept share, and the next steps (declare the mask -``binary``, run preprocessing and the masks step again, use it as a region). It stops at the -first refusal (exit status 1), naming it; the images written before it stay written. Without -scikit-image it names the extra to install and writes nothing (exit status 1). +``tissue-mask --output FOLDER --to NEW_ID`` writes, for every image of the run in ``--output`` whose +unit is declared ``rgb`` (or only the ``--image`` paths given, repeatable), its H&E tissue mask as +the new ``binary`` region mask ``NEW_ID`` (``RunInputs.he_tissue_mask``, rule ``he_tissue_v2`` by +default, provisional): nuclei, red blood cells and empty space left out, sizes in pixels. The +outputs go to the run's masks folder, each with its line of ``mask_lineage.jsonl``; the image is +never changed and nothing is overwritten. A same call again is a no-op, unless a code identity is +unverified: such a mask is written but never reused, so a retry is refused. The command prints what +it wrote, the kept share, and the next steps (declare the mask ``binary``, run preprocessing and the +masks step again, use it as a region). It stops at the first refusal (exit status 1), naming it; the +images written before it stay written. Without scikit-image it names the extra to install and writes +nothing (exit status 1). """ from __future__ import annotations @@ -20,7 +20,7 @@ from .plane_errors import PlaneReadError from .run_inputs import RunInputs from .run_inputs_tissue import ( - HE_TISSUE_V1, + HE_TISSUE_V2, NOT_REUSED, PROVISIONAL_NOTE, rgb_positions, @@ -66,8 +66,9 @@ def add_tissue_mask_parser(commands: argparse._SubParsersAction) -> argparse.Arg ) tissue.add_argument( "--rule", - default=HE_TISSUE_V1, - help=f"the fixed rule (default and only rule: {HE_TISSUE_V1}, provisional)", + default=HE_TISSUE_V2, + help=f"the fixed rule (default {HE_TISSUE_V2}, the white estimated from each image; or " + "he_tissue_v1, the white fixed at 255; both provisional)", ) return tissue diff --git a/src/morphobricks_preprocessing/he_tissue_array.py b/src/morphobricks_preprocessing/he_tissue_array.py index 6e8ed867..fb3bdfef 100644 --- a/src/morphobricks_preprocessing/he_tissue_array.py +++ b/src/morphobricks_preprocessing/he_tissue_array.py @@ -1,11 +1,11 @@ """The H&E tissue mask of an image array in memory, with no run (contract §15.4; roadmap K3). -``he_tissue_mask_array(rgb)`` computes the fixed rule ``he_tissue_v1`` (**provisional**) on one -``uint8`` ``(Y, X, 3)`` R, G, B array and returns the boolean mask (``True`` kept) with a small -immutable record of what computed it. It is for standalone users (a script, another brick's +``he_tissue_mask_array(rgb)`` computes a fixed rule (``he_tissue_v2`` by default, **provisional**) +on one ``uint8`` ``(Y, X, 3)`` R, G, B array and returns the boolean mask (``True`` kept) with a +small immutable record of what computed it. It is for standalone users (a script, another brick's folder command) who have pixels but no MorphoBricks run. The computation is the run route's own -(:func:`.he_tissue_mask.rule_on_plane`, called with the array moved to ``(3, Y, X)``), never a -copy, so the two masks are bitwise equal for the same pixels. +(:func:`.he_tissue_mask.rule_on_plane`, called with the array moved to ``(3, Y, X)``), never a copy, +so the two masks are bitwise equal for the same pixels. **Not a run artifact (Spec ADR 0005 BM15).** BM15 governs a derived region mask *written in a run*: a file in the masks folder with its ``mask_lineage.jsonl`` line, declared by the user and @@ -38,7 +38,7 @@ import numpy as np -HE_TISSUE_V1 = "he_tissue_v1" +HE_TISSUE_V2 = "he_tissue_v2" """The default rule, as in ``RunInputs.he_tissue_mask`` (provisional; :mod:`.he_tissue_rule`).""" IN_MEMORY = "" """The label of the plane in the shared computation: an array, not an image of a run.""" @@ -68,7 +68,7 @@ class TissueMaskArrayRecord: Attributes ---------- rule_id - The rule asked for (``"he_tissue_v1"``). + The rule asked for (``"he_tissue_v2"`` by default). operation The rule's operation (``"he_tissue_mask"``), as in the run route's lineage. rule_text @@ -113,12 +113,12 @@ def rule(self) -> dict: @property def rule_version(self) -> int: - """The rule record's ``version`` (``1`` for ``he_tissue_v1``).""" + """The rule record's ``version`` (``2`` for ``he_tissue_v2``).""" return self.rule["version"] @property def status(self) -> str: - """The rule record's ``status``: ``"provisional"`` for ``he_tissue_v1``.""" + """The rule record's ``status``: ``"provisional"`` for both rules.""" return self.rule["status"] @property @@ -154,14 +154,14 @@ class TissueMaskArray: record: TissueMaskArrayRecord -def he_tissue_mask_array(rgb: np.ndarray, *, rule: str = HE_TISSUE_V1) -> TissueMaskArray: +def he_tissue_mask_array(rgb: np.ndarray, *, rule: str = HE_TISSUE_V2) -> TissueMaskArray: """Compute the H&E tissue mask of one ``uint8`` ``(Y, X, 3)`` R, G, B array in memory. - The rule ``he_tissue_v1`` is **provisional** and fixed: it leaves out nuclei, red blood - cells and empty space, sizes in pixels, colour maths from normalization. The computation is - ``RunInputs.he_tissue_mask``'s own, so the mask is bitwise equal to the run route's for the - same pixels. Nothing is written and no run is read; for MorphoBricks runs use the run route, - which writes the mask with its lineage. + The rule (``he_tissue_v2`` by default) is **provisional** and fixed: it leaves out nuclei, + red blood cells and empty space, sizes in pixels, colour maths from normalization. The + computation is ``RunInputs.he_tissue_mask``'s own, so the mask is bitwise equal to the run + route's for the same pixels. Nothing is written and no run is read; for MorphoBricks runs use + the run route, which writes the mask with its lineage. Parameters ---------- @@ -169,7 +169,8 @@ def he_tissue_mask_array(rgb: np.ndarray, *, rule: str = HE_TISSUE_V1) -> Tissue A plain ``numpy.ndarray`` of pixel type ``uint8`` and shape ``(Y, X, 3)``, the last axis R, G, B. Nothing is converted and no axis is guessed. rule - The rule ID; ``"he_tissue_v1"`` is the only one. + The rule ID: ``"he_tissue_v2"`` (the default: the white estimated from the plane) or + ``"he_tissue_v1"`` (the white fixed at 255). Returns ------- diff --git a/src/morphobricks_preprocessing/he_tissue_mask.py b/src/morphobricks_preprocessing/he_tissue_mask.py index 971b38eb..15979ef9 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: @@ -305,7 +312,7 @@ def resolved_fov(run: RunInputs, fov: object) -> Fov: return found -def preview(run: RunInputs, fov: object, *, rule: str = HE_TISSUE_V1) -> TissueMaskPreview: +def preview(run: RunInputs, fov: object, *, rule: str = DEFAULT_RULE) -> TissueMaskPreview: """Compute one position's tissue mask in memory (``RunInputs.preview_he_tissue_mask``).""" found = resolved_fov(run, fov) record = current_rule(rule) @@ -313,7 +320,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``). @@ -469,8 +476,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 +492,7 @@ def rule_on_plane( fractions=MappingProxyType(fractions), rule=MappingProxyType(record), code=code_identities(), + white=white, ) @@ -510,30 +519,6 @@ def _optical_density(pixels: np.ndarray) -> tuple[np.ndarray, float]: return od, floored -def _override(run: RunInputs, found: Fov) -> dict[str, object]: - """Return the unit's declared RGB header override and this image's recorded item.""" - recorded = run.manifest.experiment_description or {} - for unit in recorded.get("units", ()): - key = (unit.get("repeat"), unit.get("condition"), unit.get("technical_repeat")) - if key == (found.repeat_group, found.condition_id, found.technical_repeat_id): - items = unit.get("rgb_header_override_images", ()) - image = next((i for i in items if i.get("image") == found.relative_path), None) - return {"declared": unit.get("rgb_header_override") is True, "image": image} - raise RunInputsError(f"The run records no unit for {found.relative_path}. Run it again.") - - -def _pixel_size(run: RunInputs, image: str) -> dict | None: - """Return the recorded X and Y sizes (information only), or None when neither has one.""" - sizes = run.pixel_sizes(image) - found = {role: sizes.get(role) for role in ("X", "Y")} - if all(size is None or size.value is None for size in found.values()): - return None - return { - role: None if size is None else {k: v for k, v in size.to_dict().items() if k != "role"} - for role, size in found.items() - } - - def _planned( run: RunInputs, found: Fov, relative: str, output_id: str, record: Mapping[str, Any] ) -> dict: @@ -553,8 +538,8 @@ def _planned( "scikit_image_version": skimage_module().__version__, "scipy_version": scipy.__version__, "image_type": found.image_type, - "rgb_header_override": _override(run, found), - "pixel_size": _pixel_size(run, found.relative_path), + "rgb_header_override": override_record(run, found), + "pixel_size": pixel_size_record(run, found.relative_path), "fractions": None, "helper": HELPER, "helper_version": __version__, diff --git a/src/morphobricks_preprocessing/he_tissue_rule.py b/src/morphobricks_preprocessing/he_tissue_rule.py index 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/notebook_tissue_mask.py b/src/morphobricks_preprocessing/notebook_tissue_mask.py index c26ff730..4577417c 100644 --- a/src/morphobricks_preprocessing/notebook_tissue_mask.py +++ b/src/morphobricks_preprocessing/notebook_tissue_mask.py @@ -159,7 +159,7 @@ def _children(self) -> list[widgets.Widget]: return [ ui.help_text( "Writes a new region mask that leaves out nuclei, red blood cells and " - "empty space of H&E images, with a fixed rule (he_tissue_v1, " + "empty space of H&E images, with a fixed rule (he_tissue_v2, " "provisional; not a trained segmentation). The images are only read and nothing " "is overwritten. Each file gets a line in mask_lineage.jsonl. Declare the " "new mask as binary, run again and describe the masks before a brick uses it." diff --git a/src/morphobricks_preprocessing/run_inputs_tissue.py b/src/morphobricks_preprocessing/run_inputs_tissue.py index 6c4367cf..58da03c5 100644 --- a/src/morphobricks_preprocessing/run_inputs_tissue.py +++ b/src/morphobricks_preprocessing/run_inputs_tissue.py @@ -15,21 +15,21 @@ from .he_tissue_mask import TissueMaskPreview, TissueMaskResult from .run_inputs import Fov -HE_TISSUE_V1 = "he_tissue_v1" -"""The default rule (provisional; :mod:`.he_tissue_rule`).""" +HE_TISSUE_V2 = "he_tissue_v2" +"""The default rule (provisional; :mod:`.he_tissue_rule`; ``he_tissue_v1`` on request).""" class TissueMaskInputs: """The H&E tissue mask helper of ``RunInputs`` (mixed into it).""" def he_tissue_mask( - self, fov: Fov | str, *, output_mask_id: str, rule: str = HE_TISSUE_V1 + self, fov: Fov | str, *, output_mask_id: str, rule: str = HE_TISSUE_V2 ) -> TissueMaskResult: """Write one RGB position's H&E tissue mask as a new ``binary`` region mask. The position is resolved from this run by its image path (a ``Fov``'s other attributes - are ignored). The rule ``he_tissue_v1`` is **provisional** and fixed: it leaves out - nuclei, red blood cells and empty space, sizes in pixels, colour maths from + are ignored). The rule (``he_tissue_v2`` by default) is **provisional** and fixed: it + leaves out nuclei, red blood cells and empty space, sizes in pixels, colour maths from normalization. The output goes to ``//...`` with its line of ``mask_lineage.jsonl``; declare it ``representation = "binary"``, run preprocessing and the masks step again, and use it as a region: in memory, never pass it as @@ -42,7 +42,8 @@ def he_tissue_mask( output_mask_id The new mask ID (experiment-v1 section 3.2), typed by the user. rule - The rule ID; ``"he_tissue_v1"`` is the only one. + The rule ID: ``"he_tissue_v2"`` (the default: the white estimated from the + plane) or ``"he_tissue_v1"`` (the white fixed at 255). Returns ------- @@ -63,7 +64,7 @@ def he_tissue_mask( return he_tissue_mask(self, fov, output_mask_id=output_mask_id, rule=rule) def preview_he_tissue_mask( - self, fov: Fov | str, *, rule: str = HE_TISSUE_V1 + self, fov: Fov | str, *, rule: str = HE_TISSUE_V2 ) -> TissueMaskPreview: """Compute one RGB position's H&E tissue mask in memory; nothing is written. @@ -84,7 +85,7 @@ def preview_he_tissue_mask( PROVISIONAL_NOTE = ( - "Sizes are in pixels. Fixed rule he_tissue_v1 (provisional), not a trained segmentation." + "Sizes are in pixels. Fixed rule he_tissue_v2 (provisional), not a trained segmentation." ) NOT_REUSED = "this mask will not be reused on retry" """Said whenever a code identity is unverified (the mask is written but never reused).""" diff --git a/tests/data/he_core_1B_D9_crop.npz b/tests/data/he_core_1B_D9_crop.npz new file mode 100644 index 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_brick_api_surface.py b/tests/test_brick_api_surface.py index 7beb473d..dcdedac4 100644 --- a/tests/test_brick_api_surface.py +++ b/tests/test_brick_api_surface.py @@ -84,11 +84,11 @@ "histograms": "(self) -> 'tuple[PlaneRecord, ...]'", # Spec ADR 0005 BM15: the opt-in H&E tissue mask helper (imported lazily, he-mask extra). "he_tissue_mask": ( - "(self, fov: 'Fov | str', *, output_mask_id: 'str', rule: 'str' = 'he_tissue_v1') " + "(self, fov: 'Fov | str', *, output_mask_id: 'str', rule: 'str' = 'he_tissue_v2') " "-> 'TissueMaskResult'" ), "preview_he_tissue_mask": ( - "(self, fov: 'Fov | str', *, rule: 'str' = 'he_tissue_v1') -> 'TissueMaskPreview'" + "(self, fov: 'Fov | str', *, rule: 'str' = 'he_tissue_v2') -> 'TissueMaskPreview'" ), "description": "(self) -> 'Description'", "section_digests": "(self) -> 'dict[str, str]'", diff --git a/tests/test_cli_tissue_mask.py b/tests/test_cli_tissue_mask.py index 9bfee5ca..87fb9f7a 100644 --- a/tests/test_cli_tissue_mask.py +++ b/tests/test_cli_tissue_mask.py @@ -44,7 +44,7 @@ def test_it_writes_every_rgb_image_and_names_the_next_steps(tmp_path, capsys, mo args = ["tissue-mask", "--output", str(run.output_folder), "--to", "HETissue"] assert main(args) == 0 printed = capsys.readouterr().out - assert "Fixed rule he_tissue_v1 (provisional)" in printed + assert "Fixed rule he_tissue_v2 (provisional)" in printed assert f"{IMAGE}: HETissue/{IMAGE} (written), kept 80.4 %" in printed assert "declare the mask HETissue (source type HETissue) as binary" in printed assert "run preprocessing and the masks step again" in printed diff --git a/tests/test_he_tissue_array.py b/tests/test_he_tissue_array.py index 6fd37cb8..bda6e8d6 100644 --- a/tests/test_he_tissue_array.py +++ b/tests/test_he_tissue_array.py @@ -119,13 +119,15 @@ def test_an_input_it_cannot_take_is_refused_before_any_computation( def test_an_unknown_rule_is_refused_before_any_computation(no_computation): - with pytest.raises(ValueError, match="'he_tissue_v2' is not known; the known rules are"): - he_tissue_mask_array(GOOD, rule="he_tissue_v2") + with pytest.raises(ValueError, match="'he_tissue_v3' is not known; the known rules are"): + he_tissue_mask_array(GOOD, rule="he_tissue_v3") @pytest.mark.parametrize("rule", [["he_tissue_v1"], ("he_tissue_v1",), None, 1]) def test_a_rule_that_is_not_one_id_is_a_clear_type_error(rule, no_computation): - with pytest.raises(TypeError, match="The rule is one ID, a str such as he_tissue_v1; got "): + with pytest.raises( + TypeError, match="The rule is one ID, a str such as he_tissue_v1, he_tissue_v2; got " + ): he_tissue_mask_array(GOOD, rule=rule) @@ -133,7 +135,7 @@ def test_its_parameters_are_the_run_routes_and_nothing_more(): signature = inspect.signature(he_tissue_mask_array) assert ( str(signature) - == "(rgb: 'np.ndarray', *, rule: 'str' = 'he_tissue_v1') -> 'TissueMaskArray'" + == "(rgb: 'np.ndarray', *, rule: 'str' = 'he_tissue_v2') -> 'TissueMaskArray'" ) run_route = inspect.signature(helper.he_tissue_mask).parameters["rule"] assert signature.parameters["rule"].default == run_route.default @@ -180,7 +182,8 @@ def test_the_threshold_image_gives_the_mask_its_parts_specify(): | ndimage.binary_dilation(red_cells, _disk(1)) | background ) - found = he_tissue_mask_array(rgb) + # The thresholds of v1 on the image as it is; v2 rescales its white (240) first. + found = he_tissue_mask_array(rgb, rule="he_tissue_v1") assert found.mask.shape == (100, 220) assert np.array_equal(found.mask, ~excluded) for name in ON_THRESHOLD: # one side of each threshold excluded, the other kept @@ -219,13 +222,13 @@ def test_the_record_states_the_rule_its_status_and_the_code_identities_as_found( record = found.record assert isinstance(record, TissueMaskArrayRecord) assert (record.rule_id, record.rule_version, record.status, record.provisional) == ( - "he_tissue_v1", - 1, + "he_tissue_v2", + 2, "provisional", True, ) assert record.operation == "he_tissue_mask" - assert record.rule == helper.current_rule("he_tissue_v1") + assert record.rule == helper.current_rule("he_tissue_v2") assert record.rule_sha256 == rule_sha256(record.rule) # rule_text is the canonical form itself: the exact text its digest is of (issue #345). assert hashlib.sha256(record.rule_text.encode("utf-8")).hexdigest() == record.rule_sha256 diff --git a/tests/test_he_tissue_mask.py b/tests/test_he_tissue_mask.py index ee06ce21..6b8b89c8 100644 --- a/tests/test_he_tissue_mask.py +++ b/tests/test_he_tissue_mask.py @@ -291,10 +291,10 @@ def test_other_refusals_before_any_read(run, monkeypatch, tmp_path): no_reads(monkeypatch) with pytest.raises(RunInputsError, match="CTRL/rep1/z.tif is not an image of this run"): run.he_tissue_mask(f"{UNIT}/z.tif", output_mask_id="HETissue") - with pytest.raises(ValueError, match="known rules are he_tissue_v1"): - run.he_tissue_mask(IMAGE, output_mask_id="HETissue", rule="he_tissue_v2") + with pytest.raises(ValueError, match="known rules are he_tissue_v1, he_tissue_v2"): + run.he_tissue_mask(IMAGE, output_mask_id="HETissue", rule="he_tissue_v3") # A list of rules is a clear TypeError, not an unhashable one (issue #345). - with pytest.raises(TypeError, match="The rule is one ID, a str such as he_tissue_v1; got list"): + with pytest.raises(TypeError, match="a str such as he_tissue_v1, he_tissue_v2; got list"): run.he_tissue_mask(IMAGE, output_mask_id="HETissue", rule=["he_tissue_v1"]) with pytest.raises(TypeError, match="The rule is one ID, a str"): run.preview_he_tissue_mask(IMAGE, rule=["he_tissue_v1"]) @@ -422,7 +422,7 @@ def test_freezing_makes_a_new_mask_under_a_new_id_never_a_relabelled_one( ): provisional = run.he_tissue_mask(IMAGE, output_mask_id="HETissue") before = tree(run.masks_root) - monkeypatch.setitem(helper.RULES, "he_tissue_v1", "frozen") + monkeypatch.setitem(helper.RULES, "he_tissue_v2", "frozen") with pytest.raises(ValueError) as refused: run.he_tissue_mask(IMAGE, output_mask_id="HETissue") assert "differs in: rule, rule_sha256" in str(refused.value) diff --git a/tests/test_he_tissue_rule.py b/tests/test_he_tissue_rule.py index 68732ee9..a23e9a64 100644 --- a/tests/test_he_tissue_rule.py +++ b/tests/test_he_tissue_rule.py @@ -234,8 +234,8 @@ def test_the_rule_record_is_the_designs_and_provisional(): ["remove_pieces_smaller_than_px", 1000], ] assert RULE["connectivity"] == 8 and RULE["disk"] == "x*x + y*y <= r*r" - with pytest.raises(ValueError, match="known rules are he_tissue_v1"): - rule_record("he_tissue_v2", hed_source="x", hed_sha256="0" * 64) + with pytest.raises(ValueError, match="known rules are he_tissue_v1, he_tissue_v2"): + rule_record("he_tissue_v3", hed_source="x", hed_sha256="0" * 64) # B4: the boundary table of §1 ----------------------------------------------------------------- diff --git a/tests/test_he_tissue_v2.py b/tests/test_he_tissue_v2.py new file mode 100644 index 00000000..e8b4a98e --- /dev/null +++ b/tests/test_he_tissue_v2.py @@ -0,0 +1,178 @@ +"""The rule ``he_tissue_v2``: ``he_tissue_v1`` on the plane rescaled to its own white (v0.10.1). + +``he_tissue_v1`` fixes the white at 255. On scans whose glass is grey (Zenodo 4550300's TMA +cores: glass near (127, 135, 145)) every pixel reads as stained, ``H >= 0.05`` everywhere, and +v1 keeps 0 % ("nothing kept: an empty region"). v2 estimates the white per channel as the median +of the brightest 0.1 % of pixels (by ``R + G + B``), rescales with normalization's +``rescale_to_white`` and applies v1's components unchanged. + +- the record: v1's components, version 2, the white stated; v1's record unchanged; +- the estimate, against a plain re-statement of its definition; +- v2 is exactly v1 on the rescaled plane, and v1 itself when the brightest pixels are white; +- a crop of a real core (``tests/data/he_core_1B_D9_crop.npz``, CC-BY-4.0, see + ``tests/data/make_he_core_crop.py``): v1 keeps 0 %, v2 a plausible tissue share, through the + array route and through a run whose TIFF is tagged MINISBLACK with the RGB header override; +- blank slides, white or grey glass: nothing kept. +""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +import numpy as np +import pytest + +pytest.importorskip("skimage") + +from morphobricks_normalization.optical_density import check_white, rescale_to_white # noqa: E402 + +from he_tissue_tree import ( # noqa: E402 + IDENTITY_PATCH, + UNIT, + identities, + pi_style, + rgb_run, + synthetic_he, + threshold_image, +) +from morphobricks_preprocessing import he_tissue_mask as helper # noqa: E402 +from morphobricks_preprocessing import he_tissue_mask_array # noqa: E402 +from morphobricks_preprocessing.he_tissue_rule import ( # noqa: E402 + DEFAULT_RULE, + estimate_white, + rule_record, +) + +CROP = Path(__file__).parent / "data" / "he_core_1B_D9_crop.npz" +CROP_SHA256 = "1d6f85da792938f00b9d64f61016e9a4fbc0cd5981240bf37d6de3f6353dfd14" + + +def record(rule): + return rule_record(rule, hed_source="skimage.color.hed_from_rgb", hed_sha256="0" * 64) + + +def core_crop(): + rgb = np.load(CROP)["rgb"] + assert hashlib.sha256(rgb.tobytes()).hexdigest() == CROP_SHA256 + return rgb + + +def blank(colour, noise, seed=0): + rng = np.random.default_rng(seed) + pixels = rng.normal(colour, noise, (256, 256, 3)) if noise else np.full((256, 256, 3), colour) + return np.clip(np.rint(pixels), 0, 255).astype(np.uint8) + + +# The record ------------------------------------------------------------------------------------- + + +def test_v2_is_v1s_components_with_the_white_estimated(): + v1, v2 = record("he_tissue_v1"), record("he_tissue_v2") + assert DEFAULT_RULE == "he_tissue_v2" + assert (v2["id"], v2["version"], v2["status"]) == ("he_tissue", 2, "provisional") + assert v2["components"] == v1["components"] # no threshold or size changed + assert v2["colour"] == v1["colour"] and v2["combine"] == v1["combine"] + assert v2["input"] == {"image_type": "rgb", "dtype": "uint8", "white": "estimated"} + assert "99.9" in v2["white"]["estimate"] and "median" in v2["white"]["estimate"] + assert v2["white"]["rescale"]["function"] == ( + "morphobricks_normalization.optical_density.rescale_to_white" + ) + # v1 is unchanged: its white fixed, no estimate. + assert v1["version"] == 1 and v1["input"]["white"] == [255, 255, 255] and "white" not in v1 + + +# The estimate ----------------------------------------------------------------------------------- + + +@pytest.mark.parametrize("seed", [0, 1, 2]) +def test_the_white_is_the_median_of_the_brightest_tenth_of_a_percent(seed): + rgb = np.random.default_rng(seed).integers(0, 256, (97, 131, 3), dtype=np.uint8) + flat = rgb.reshape(-1, 3).astype(np.int64) + sums = flat.sum(axis=1) + ordered = np.sort(sums) + position = 0.999 * (len(ordered) - 1) # NumPy's "linear" percentile, written out + below = int(np.floor(position)) + limit = ordered[below] + (position - below) * (ordered[below + 1] - ordered[below]) + expected = tuple(float(np.median(flat[sums >= limit][:, c])) for c in range(3)) + assert estimate_white(rgb) == expected + + +def test_the_white_is_at_least_1_and_a_uniform_plane_is_its_own_white(): + assert estimate_white(np.zeros((8, 8, 3), np.uint8)) == (1.0, 1.0, 1.0) + assert estimate_white(np.full((8, 8, 3), (127, 135, 145), np.uint8)) == (127.0, 135.0, 145.0) + + +# v2 = v1 on the rescaled plane ------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "image", + ["crop", "threshold", "pi1", "pi3", "synthetic"], +) +def test_v2_is_v1_on_the_plane_rescaled_to_its_white(image): + rgb = { + "crop": core_crop, + "threshold": lambda: threshold_image()[0], + "pi1": lambda: pi_style("pi1"), + "pi3": lambda: pi_style("pi3"), + "synthetic": lambda: synthetic_he()[0], + }[image]() + rescaled, _ = rescale_to_white(rgb, check_white(estimate_white(rgb))) + v2 = he_tissue_mask_array(rgb, rule="he_tissue_v2") + v1 = he_tissue_mask_array(rescaled, rule="he_tissue_v1") + assert np.array_equal(v2.mask, v1.mask) + assert dict(v2.record.fractions) == dict(v1.record.fractions) + + +def test_v2_is_v1_itself_when_the_brightest_pixels_are_white(): + rgb = pi_style("pi2") + rgb[:40, :40] = 255 # glass at full white + assert estimate_white(rgb) == (255.0, 255.0, 255.0) + v1 = he_tissue_mask_array(rgb, rule="he_tissue_v1") + v2 = he_tissue_mask_array(rgb, rule="he_tissue_v2") + assert np.array_equal(v1.mask, v2.mask) + + +def test_the_preview_states_the_white_it_rescaled_to(): + rgb = core_crop() + pixels = np.ascontiguousarray(np.moveaxis(rgb, -1, 0)) + v2 = helper.rule_on_plane(pixels, helper.current_rule("he_tissue_v2"), image="crop") + v1 = helper.rule_on_plane(pixels, helper.current_rule("he_tissue_v1"), image="crop") + assert v2.white == estimate_white(rgb) and v1.white is None + assert np.array_equal(v2.rgb, pixels) # the plane read, not the rescaled one + + +# The regression: a real core -------------------------------------------------------------------- + + +def test_v1_keeps_nothing_on_a_grey_glass_core_and_v2_keeps_its_tissue(): + rgb = core_crop() + v1 = he_tissue_mask_array(rgb, rule="he_tissue_v1").record.fractions + assert v1["kept"] == 0.0 and v1["nuclei"] == 1.0 # the reported failure + v2 = he_tissue_mask_array(rgb).record.fractions # the default rule + assert 0.25 <= v2["kept"] <= 0.6 # 0.350: stroma kept + assert 0.3 <= v2["background"] <= 0.7 # 0.515: the glass and the lumen + assert 0.05 <= v2["nuclei"] <= 0.3 # 0.135 + assert v2["red_cells"] < 0.01 + + +@pytest.mark.parametrize( + ("colour", "noise"), + [((255, 255, 255), 0), ((242, 242, 244), 2), ((127, 135, 145), 2), ((127, 135, 145), 0)], +) +def test_a_blank_slide_keeps_nothing(colour, noise): + found = he_tissue_mask_array(blank(colour, noise)) + assert found.record.fractions["kept"] < 0.01 + + +def test_the_run_route_with_the_header_override_keeps_the_cores_tissue(tmp_path, monkeypatch): + monkeypatch.setattr(IDENTITY_PATCH, lambda: identities()) + rgb = core_crop() + # The scanner wrote MINISBLACK for its R, G, B samples: read with the RGB header override. + run = rgb_run(tmp_path, {"a.tif": rgb}, override=True, scanner={"a.tif"}) + result = run.he_tissue_mask(f"{UNIT}/a.tif", output_mask_id="HETissue") + assert result.record["rule"]["version"] == 2 + assert result.record["rgb_header_override"]["image"]["override"] == "used" + assert 0.25 <= result.fractions["kept"] <= 0.6 + assert dict(result.fractions) == dict(he_tissue_mask_array(rgb).record.fractions) diff --git a/tests/test_notebook_tissue_mask.py b/tests/test_notebook_tissue_mask.py index 17c74729..fcd965c1 100644 --- a/tests/test_notebook_tissue_mask.py +++ b/tests/test_notebook_tissue_mask.py @@ -91,7 +91,7 @@ def test_the_preview_writes_nothing_and_shows_the_shares_and_notes(tmp_path, mon ) text = card.numbers.value assert "kept 80.4 % · nuclei 1.6 % · red cells 0.8 % · empty 17.2 %" in text - assert "Sizes are in pixels. Fixed rule he_tissue_v1 (provisional)" in text + assert "Sizes are in pixels. Fixed rule he_tissue_v2 (provisional)" in text assert "this mask will not be reused on retry" in text # an unverified identity