From b928f59fb054e4ebdfb99ad29083ff3b85c52538 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 13:05:51 +0000 Subject: [PATCH 1/3] Pin preprocessing v0.7.0 and normalization v0.7.1 Preprocessing v0.7.0 (8865b72; core and zarr extra; was v0.6.1) and normalization v0.7.1 (fcfaeac; was v0.7.0), the requirement string preprocessing v0.7.0's pyproject pins (owner decision D-h). setup.py, AGENTS.md, docs/normalization.md, docs/normalization_contract.md and a new [Unreleased] CHANGELOG entry name the tags. Preprocessing v0.7.0 words the resolver's A_SCOPE_INCOMPLETE as "present in k of n images" (was "acquisitions", its #321): the four tests that quoted the old word, and docs/configuration_reference.md, now quote the new text. No golden changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- AGENTS.md | 2 +- docs/configuration_reference.md | 2 +- docs/normalization.md | 2 +- docs/normalization_contract.md | 2 +- notebooks/CellPatcher/CHANGELOG.md | 20 ++++++++++++++++++++ setup.py | 14 ++++++++------ tests/test_cell_mask_request.py | 2 +- tests/test_channel_ids.py | 4 ++-- tests/test_condition_repeat_tree.py | 2 +- tests/test_ngff_labels.py | 2 +- 10 files changed, 37 insertions(+), 15 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3385e957..1919cc1e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,7 @@ | Tests | `python tools/check.py` (pytest, Ruff and the MorphoBricks code rules against `tools/code_rules_baseline.json`, design v0.4 §9); `PYTHONPATH=src python -m pytest -q` for the tests alone | | Environment | `python -m pip install -e .` (add extras as needed: `.[test]`, `.[notebook]`, `.[torch]`) or `conda env create -f environment.yaml` | -Key dependencies: `numpy`, `scipy`, `tifffile`, `imageio`, and the MorphoBricks bricks `morphobricks-preprocessing` and `morphobricks-normalization` from GitHub at pinned tags (normalization `v0.7.0`; preprocessing `v0.6.1` — Spec ADR 0005 steps 2 and 2b: resolver contract v3, `read_objects`, the conversion helpers; v0.6.1 records the verified mask fingerprint) (core, required; normalization is declared at the tag the preprocessing tag pins, owner decision D-h, checked by `tests/test_dependency_pins.py`; histograms, the plane table, plane IDs, pooling and normalization parameters are imported from `morphobricks_normalization`, not from their deprecated preprocessing paths). Optional extras: `ipywidgets`, `matplotlib`, `pillow`, `tqdm`, `joblib`, `jl-hidecode` (notebook extra); `torch` (optional `cellpatcher.torch_dataset` adapter only — never a core dependency); `morphobricks-preprocessing[zarr]` at the same tag (`zarr` extra, formerly `preprocessing`: OME-Zarr images and OME-NGFF label masks). +Key dependencies: `numpy`, `scipy`, `tifffile`, `imageio`, and the MorphoBricks bricks `morphobricks-preprocessing` and `morphobricks-normalization` from GitHub at pinned tags (normalization `v0.7.1`; preprocessing `v0.7.0` — Spec ADR 0005 steps 2 and 2b: resolver contract v3, `read_objects`, the conversion helpers; v0.6.1 records the verified mask fingerprint; v0.7.0 raises `RunStoppedError` for a stopped run) (core, required; normalization is declared at the tag the preprocessing tag pins, owner decision D-h, checked by `tests/test_dependency_pins.py`; histograms, the plane table, plane IDs, pooling and normalization parameters are imported from `morphobricks_normalization`, not from their deprecated preprocessing paths). Optional extras: `ipywidgets`, `matplotlib`, `pillow`, `tqdm`, `joblib`, `jl-hidecode` (notebook extra); `torch` (optional `cellpatcher.torch_dataset` adapter only — never a core dependency); `morphobricks-preprocessing[zarr]` at the same tag (`zarr` extra, formerly `preprocessing`: OME-Zarr images and OME-NGFF label masks). Current health snapshot (2026-11-16, v0.7.1 release prep: preprocessing `v0.6.0` (then `v0.6.1`, see the CHANGELOG) and normalization `v0.7.0` installed from their tags in a fresh venv, Linux): `.[test,zarr,notebook]` with CPU `torch` 2.15.0: 3000 passed, 0 skipped on Python 3.11 before #123, and 3004 passed, 0 skipped on Python 3.13 after it (`python tools/check.py`, code rules and Ruff clean; the smaller extras were not run locally). CI also runs `.[test]` on `windows-latest` (`pytest-windows`): 2899 passed, 42 skipped after #123, every skip an extra that job does not install (zarr, notebook, torch). Preprocessing refuses Z>1 inputs (2-D planes only), so the tests that built Z-stacks use T. diff --git a/docs/configuration_reference.md b/docs/configuration_reference.md index a24e7145..7c902cae 100644 --- a/docs/configuration_reference.md +++ b/docs/configuration_reference.md @@ -146,7 +146,7 @@ Controls how patch arrays are extracted from images and optionally resized. | `resize_order` | `int` | `1` | Spline interpolation order for resizing (0 = nearest, 1 = bilinear, 3 = bicubic). Must be `>= 0`. | | `apply_mask` | `bool` | `False` | **Cell mode only.** When `True`, pixels outside the selected cell label are set to `mask_fill_value` before resize/export. | | `mask_fill_value` | `float` | `0.0` | Fill value for pixels outside the selected label when `apply_mask=True`. | -| `split_channels` | `bool` or `list[str]` | `False` | When `True`, every region becomes one single-channel patch per channel of its image instead of one multichannel patch (requires a `C` axis in `common.image_axes`). A list of **canonical channel IDs** (for example `["DNA"]` or `["DNA", "ACTIN"]`) gives one patch per named channel only, in each image's C order. Channels are chosen by ID only, never by position (owner decision of 13 November 2026): a list of indices such as `[1]` is not a valid value. Each ID is the C index it has **in each image**, by the image's own channel IDs: in a folder or tree run those of the run's description (CP-3), where an ID some image lacks, or no image has, is refused by the run's resolver before anything is read (`A_SCOPE_INCOMPLETE`, "present in k of n acquisitions"; no subset is taken); for in-memory images `image_metadata[i]["channel_ids"]`, one ID per C index (an image without them, or without a named ID, is refused before any patch is made). Every split patch's `channel_id` column names its channel. Channel patches keep the region's coordinates and `position_id`, and get `c` = channel index (a `c` level of `patch_id`; see "Patch identity" below). Filters are evaluated on the whole multichannel region before splitting; masking and resizing are applied before splitting too. | +| `split_channels` | `bool` or `list[str]` | `False` | When `True`, every region becomes one single-channel patch per channel of its image instead of one multichannel patch (requires a `C` axis in `common.image_axes`). A list of **canonical channel IDs** (for example `["DNA"]` or `["DNA", "ACTIN"]`) gives one patch per named channel only, in each image's C order. Channels are chosen by ID only, never by position (owner decision of 13 November 2026): a list of indices such as `[1]` is not a valid value. Each ID is the C index it has **in each image**, by the image's own channel IDs: in a folder or tree run those of the run's description (CP-3), where an ID some image lacks, or no image has, is refused by the run's resolver before anything is read (`A_SCOPE_INCOMPLETE`, "present in k of n images" since preprocessing v0.7.0; no subset is taken); for in-memory images `image_metadata[i]["channel_ids"]`, one ID per C index (an image without them, or without a named ID, is refused before any patch is made). Every split patch's `channel_id` column names its channel. Channel patches keep the region's coordinates and `position_id`, and get `c` = channel index (a `c` level of `patch_id`; see "Patch identity" below). Filters are evaluated on the whole multichannel region before splitting; masking and resizing are applied before splitting too. | > `apply_mask=True` is only supported in `mode="cell"` and requires masks to be provided. diff --git a/docs/normalization.md b/docs/normalization.md index 8dc348b9..9882d6a7 100644 --- a/docs/normalization.md +++ b/docs/normalization.md @@ -14,7 +14,7 @@ before. ## The workflow -1. **Install** CellPatcher: the preprocessing (v0.6.1) and normalization (v0.7.0) bricks are core +1. **Install** CellPatcher: the preprocessing (v0.7.0) and normalization (v0.7.1) bricks are core dependencies. OME-Zarr images need the optional extra `pip install "cellpatcher[zarr]"` (the notebook's first cell installs it on Google Colab). 2. **Describe the experiment and run the preprocessing notebook** on your experiment folder: publish diff --git a/docs/normalization_contract.md b/docs/normalization_contract.md index e7847403..ffe36bb1 100644 --- a/docs/normalization_contract.md +++ b/docs/normalization_contract.md @@ -48,7 +48,7 @@ brick's | Rule | Detail | |---|---| -| Dependencies | `morphobricks-preprocessing` (`v0.6.1` since CellPatcher v0.7.1; `v0.6.0` in v0.7.0, Spec ADR 0005 steps 2 and 2b; `v0.5.6` in v0.6.2; `v0.5.5` in v0.6.1; `v0.5.3` in v0.6.0; `v0.5.2` in v0.5.0; `v0.5.1` in v0.4.0; `v0.5.0` in v0.3.0; `v0.4.0` in v0.2.0, `v0.4.0rc5` in v0.2.0rc3, `v0.4.0rc4` in v0.2.0rc2, `v0.4.0rc2` in v0.2.0rc1) and `morphobricks-normalization` (`v0.7.0` since CellPatcher v0.7.0, the tag preprocessing v0.6.0 and v0.6.1 pin; `v0.6.1` in CellPatcher v0.6.1 and v0.6.2, the tag preprocessing v0.5.5 and v0.5.6 pin; `v0.6.0` in CellPatcher v0.6.0, the tag preprocessing v0.5.3 pins; `v0.5.0` in CellPatcher v0.5.0, the tag preprocessing v0.5.2 pins; `v0.4.0` in CellPatcher v0.4.0, the tag preprocessing v0.5.1 pins; `v0.3.4` in v0.2.0 and v0.3.0: the tag preprocessing `v0.5.0` pins; `v0.3.3` in v0.2.0rc3, `v0.3.2` before) are core dependencies, pinned to tags in `setup.py`; normalization at the tag the preprocessing tag pins (owner decision D-h, checked by `tests/test_dependency_pins.py`). The `zarr` extra (`pip install "cellpatcher[zarr]"`, formerly `preprocessing`) installs `morphobricks-preprocessing[zarr]` at the same tag, for OME-Zarr images. Histograms, the plane table, plane IDs, pooling and normalization parameters, which moved to the normalization brick, are imported from `morphobricks_normalization`. | +| Dependencies | `morphobricks-preprocessing` (unreleased: `v0.7.0`, `RunStoppedError`; `v0.6.1` in CellPatcher v0.7.1; `v0.6.0` in v0.7.0, Spec ADR 0005 steps 2 and 2b; `v0.5.6` in v0.6.2; `v0.5.5` in v0.6.1; `v0.5.3` in v0.6.0; `v0.5.2` in v0.5.0; `v0.5.1` in v0.4.0; `v0.5.0` in v0.3.0; `v0.4.0` in v0.2.0, `v0.4.0rc5` in v0.2.0rc3, `v0.4.0rc4` in v0.2.0rc2, `v0.4.0rc2` in v0.2.0rc1) and `morphobricks-normalization` (unreleased: `v0.7.1`, the tag preprocessing v0.7.0 pins; `v0.7.0` in CellPatcher v0.7.0 and v0.7.1, the tag preprocessing v0.6.0 and v0.6.1 pin; `v0.6.1` in CellPatcher v0.6.1 and v0.6.2, the tag preprocessing v0.5.5 and v0.5.6 pin; `v0.6.0` in CellPatcher v0.6.0, the tag preprocessing v0.5.3 pins; `v0.5.0` in CellPatcher v0.5.0, the tag preprocessing v0.5.2 pins; `v0.4.0` in CellPatcher v0.4.0, the tag preprocessing v0.5.1 pins; `v0.3.4` in v0.2.0 and v0.3.0: the tag preprocessing `v0.5.0` pins; `v0.3.3` in v0.2.0rc3, `v0.3.2` before) are core dependencies, pinned to tags in `setup.py`; normalization at the tag the preprocessing tag pins (owner decision D-h, checked by `tests/test_dependency_pins.py`). The `zarr` extra (`pip install "cellpatcher[zarr]"`, formerly `preprocessing`) installs `morphobricks-preprocessing[zarr]` at the same tag, for OME-Zarr images. Histograms, the plane table, plane IDs, pooling and normalization parameters, which moved to the normalization brick, are imported from `morphobricks_normalization`. | | Version | Installed from GitHub at a pinned commit or tag, recorded in `setup.py` and raised deliberately. | | Formats | Since v0.2.0 (CP-1) the preprocessing run is read through the brick's `RunInputs` (its design v0.4 §6), which needs `run_manifest.json` manifest version `2` (preprocessing v0.4), or `3` for a run with the brick's `--verify-content` (preprocessing v0.4.0rc5, CellPatcher v0.2.0rc3), or `4` for a described run (preprocessing v0.5.0, CellPatcher v0.3.0, which refuses a run without a published description: `A_DESCRIPTION_REQUIRED`); since preprocessing v0.5.1 only `4` is read, and since preprocessing v0.5.2 (the W3 pins) only `5`, whose file entries record their `channel_ids` (an older manifest is refused, `preprocessing_run_refused`, never converted) and `RunInputs.open` itself refuses a run without a description, and the `plane_histograms.csv` version that brick reads; CellPatcher pins no version of its own. Any run `RunInputs` refuses is an error. | | Needed for | Normalization (every scope), OME-Zarr images and labels, and plane-by-plane image reading. | diff --git a/notebooks/CellPatcher/CHANGELOG.md b/notebooks/CellPatcher/CHANGELOG.md index 27f95b88..f4421353 100644 --- a/notebooks/CellPatcher/CHANGELOG.md +++ b/notebooks/CellPatcher/CHANGELOG.md @@ -74,6 +74,26 @@ Release v0.3.0 Pin preprocessing v0.4.0rc4; prepare v0.2.0rc2 --- +## [Unreleased] - Preprocessing v0.7.0, normalization v0.7.1 + +For v0.7.2 or v0.8.0. + +### Changed +- **Dependencies:** pins preprocessing `v0.7.0` (`8865b72`; core and `zarr` extra; was `v0.6.1`) and + normalization `v0.7.1` (`fcfaeac`; was `v0.7.0`), the tag preprocessing `v0.7.0` pins (owner decision D-h). + Preprocessing v0.7.0 adds `RunStoppedError` and `RunReportUnreadableError` (#322), reports Spec `v29` + (`R_HETEROGENEOUS_LAYOUT_NOT_ENABLED`) as the run's single refusal, caps an `unreadable_planes` message at 20 + planes per image (the report keeps them all) and words its coverage messages by the unit they count: the + resolver's `A_SCOPE_INCOMPLETE` says "present in k of n images" (was "acquisitions"), the run's + `partial_channel_coverage` warning says "imaging units". Normalization v0.7.1 writes a signed zero `-0.0` as + `0.0` (its written text only; no API, schema or message change). No run format changes: runs of preprocessing + v0.6.1 are read as they are. +- CellPatcher's code does not change for them. Four tests that quoted the resolver's old word now quote + "images" (`test_cell_mask_request.py`, `test_channel_ids.py`, `test_condition_repeat_tree.py`, + `test_ngff_labels.py`), and `docs/configuration_reference.md` quotes the new text. No golden changes: the parity + golden `tests/fixtures/v062_parity/digests.json` and `tests/fixtures/shared_labeller/golden.json` pass unchanged + (no golden case writes a `-0.0`). + ## [Unreleased] - write_array writes a TIFF as planes, laid out from the axes it is given (#131) For v0.7.2. Follows #129/#130. diff --git a/setup.py b/setup.py index 40f150c5..4488599c 100644 --- a/setup.py +++ b/setup.py @@ -17,16 +17,18 @@ # checks). Pinned to its tag and raised deliberately; the ``zarr`` extra # below adds its OME-Zarr reader at the same tag. v0.6.0 is Spec ADR 0005 # steps 2 and 2b (resolver contract v3, RunInputs.read_objects, the - # conversion helpers); v0.6.1 fixes the checked-fingerprint race. + # conversion helpers); v0.6.1 fixes the checked-fingerprint race; v0.7.0 + # adds RunStoppedError / RunReportUnreadableError for a stopped run (#322). "morphobricks-preprocessing @ git+https://github.com/CellMigrationLab/" - "morphobricks-preprocessing@v0.6.1", + "morphobricks-preprocessing@v0.7.0", # CellPatcher imports the normalization brick directly (plane histograms, # the plane table, pooling, normalization parameters, SINGLE), so it # declares it, at the tag the preprocessing tag above pins (owner - # decision D-h; tests/test_dependency_pins.py checks that they agree). v0.7.0 adds - # regions.check_region and contracts.refuse_resolver_version (Spec ADR 0005). + # decision D-h; tests/test_dependency_pins.py checks that they agree). v0.7.0 added + # regions.check_region and contracts.refuse_resolver_version (Spec ADR 0005); + # v0.7.1 writes a signed zero as 0.0 (no API or message change). "morphobricks-normalization @ git+https://github.com/CellMigrationLab/" - "morphobricks-normalization.git@v0.7.0", + "morphobricks-normalization.git@v0.7.1", ], extras_require={ "test": [ @@ -63,7 +65,7 @@ # is a core dependency. "zarr": [ "morphobricks-preprocessing[zarr] @ git+https://github.com/CellMigrationLab/" - "morphobricks-preprocessing@v0.6.1", + "morphobricks-preprocessing@v0.7.0", ], }, ) diff --git a/tests/test_cell_mask_request.py b/tests/test_cell_mask_request.py index 3c143073..54a9cd19 100644 --- a/tests/test_cell_mask_request.py +++ b/tests/test_cell_mask_request.py @@ -170,7 +170,7 @@ def test_an_undeclared_mask_id_is_present_in_0_of_n(v08, monkeypatch): with pytest.raises(PreprocessingCheckError) as raised: _tree(v08, _cell_config(v08.output, mask_id="Cells")) assert _codes(raised) == ["A_SCOPE_INCOMPLETE"] - assert "'Cells' is present in 0 of 4 acquisitions" in str(raised.value) + assert "'Cells' is present in 0 of 4 images" in str(raised.value) def test_p28_a_mask_the_mask_step_has_not_checked_is_refused_by_the_resolver(tmp_path, monkeypatch): diff --git a/tests/test_channel_ids.py b/tests/test_channel_ids.py index ccb3d7c3..fc8cc1aa 100644 --- a/tests/test_channel_ids.py +++ b/tests/test_channel_ids.py @@ -71,13 +71,13 @@ def test_a_multichannel_patch_has_no_channel_id(tmp_path): @pytest.mark.parametrize("ids", [["NUCLEUS"], ["DNA", "NUCLEUS"]]) def test_an_unknown_channel_id_is_refused_by_the_resolver_before_anything_is_written(tmp_path, ids): - # Resolver contract v1: an ID no image has is present in 0 of n acquisitions (A_SCOPE_INCOMPLETE); + # Resolver contract v1: an ID no image has is present in 0 of n images (A_SCOPE_INCOMPLETE); # nothing is selected, not even the known ID. run = _described_run(tmp_path, "v13") with pytest.raises(PreprocessingCheckError) as raised: _tree(run, tmp_path / "out", ids) assert [issue.code for issue in raised.value.issues] == ["A_SCOPE_INCOMPLETE"] - assert "'NUCLEUS' is present in 0 of 90 acquisitions" in str(raised.value) + assert "'NUCLEUS' is present in 0 of 90 images" in str(raised.value) assert not (tmp_path / "out").exists() diff --git a/tests/test_condition_repeat_tree.py b/tests/test_condition_repeat_tree.py index f279e163..f2c0b462 100644 --- a/tests/test_condition_repeat_tree.py +++ b/tests/test_condition_repeat_tree.py @@ -168,7 +168,7 @@ def test_tree_random_mode_mask_root_needs_a_mask_for_every_image(tmp_path): cfg = CellPatcherConfig(mode="random") cfg.random.n_patches = 3 cfg.random.patch_size = 8 - with pytest.raises(ValueError, match=r"(?s)present in 1 of 2 acquisitions.*control/img.tif.*A_SCOPE_INCOMPLETE"): + with pytest.raises(ValueError, match=r"(?s)present in 1 of 2 images.*control/img.tif.*A_SCOPE_INCOMPLETE"): _tree(image_root, config=cfg, mask_root_path=mask_root, representations={"mask": "binary"}) write_array(mask_root / "control" / "img_mask.tif", np.ones((64, 64), dtype=np.uint8), axes="YX") diff --git a/tests/test_ngff_labels.py b/tests/test_ngff_labels.py index 023a0a0a..a8112164 100644 --- a/tests/test_ngff_labels.py +++ b/tests/test_ngff_labels.py @@ -110,7 +110,7 @@ def test_every_image_needs_a_label_image_of_the_type(tmp_path): _image(tmp_path, labels={"cells": _labels((16, 16), [(1, 2, 2)])}) write_array(tmp_path / "control" / "b.tif", np.ones((16, 16), dtype=np.uint16), axes="YX") # The TIFF has no label image: in cell mode the run's resolver refuses the object set (CP-2). - with pytest.raises(PreprocessingCheckError, match="'cells' is present in 1 of 2 acquisitions") as raised: + with pytest.raises(PreprocessingCheckError, match="'cells' is present in 1 of 2 images") as raised: _tree(tmp_path, _cell_config()) assert [issue.code for issue in raised.value.issues] == ["A_SCOPE_INCOMPLETE"] From 39f8c53c7c7348efd56307acf9d17d4fd9c9c4f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 13:11:07 +0000 Subject: [PATCH 2/3] Pass a stopped preprocessing run's refusal on unchanged (#126, from #128) Reworks draft PR #128 onto the preprocessing v0.7.0 pin. On a folder where preprocessing stopped without writing a run (Spec v29, R_HETEROGENEOUS_LAYOUT_NOT_ENABLED), RunInputs.open raises RunStoppedError; open_run's PreprocessingCheckError (chained from it) now holds first an issue whose code and message are the error's own code (RUN_FOLDER_STOPPED) and str(), with no action of CellPatcher's, then the error's issues unchanged and in order. RunReportUnreadableError gives one issue with its code (RUN_FOLDER_REPORT_UNREADABLE) and message, naming the report. Spec ADR 0005, construction and propagation: no rewording, no CellPatcher code around RUN_FOLDER_STOPPED (#128 added a preprocessing_run_refused issue after the stopped run's issues; that is gone). CellPatcher never reads discovery_report.json. A folder with neither a run nor a stopped run's report says to give a written run or run preprocessing first; a stale written run keeps its re-run advice. tests/test_stopped_run.py (from #128, with string-equal code and message checks, a guard that no discovery_report.json is read and a source scan for RUN_FOLDER_ literals); docs/normalization.md and the CHANGELOG. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- docs/normalization.md | 1 + notebooks/CellPatcher/CHANGELOG.md | 17 ++- src/cellpatcher/run_open.py | 39 ++++++- tests/test_stopped_run.py | 176 +++++++++++++++++++++++++++++ 4 files changed, 230 insertions(+), 3 deletions(-) create mode 100644 tests/test_stopped_run.py diff --git a/docs/normalization.md b/docs/normalization.md index 9882d6a7..0af5537f 100644 --- a/docs/normalization.md +++ b/docs/normalization.md @@ -194,6 +194,7 @@ planes and what to do: | *The preprocessing run in ... cannot be used: The experiment holds ... that the preprocessing run did not record* (`unrecorded_files`) | Since preprocessing v0.4.0rc2: images or masks were added to the experiment (or masks folder) after the run. None is left out: run preprocessing again on the experiment as it is, or exclude the images there. | | *... the zarr package is not installed* (`zarr_extra_missing`) | The run holds OME-Zarr images: `pip install "cellpatcher[zarr]"`. | | *The preprocessing run in ... cannot be used* (`preprocessing_run_refused`) | The preprocessing brick's `RunInputs` refuses the run (since v0.2.0): no `run_manifest.json` next to the table, a run written before preprocessing v0.4.0, a table or description changed since the run, or an image or mask changed or missing since the run where CellPatcher reads it. Run preprocessing v0.5 on the experiment as it is now; an experiment only moved or copied (times kept) since its run is read where it is now when CellPatcher is given that folder and its masks folder (since CP-2a). | +| *RUN_FOLDER_STOPPED: the preprocessing run in ... stopped with ...* (`RUN_FOLDER_STOPPED`), then preprocessing's own errors | Since preprocessing v0.7.0 (issue #126): preprocessing stopped in that folder without writing a run, for example Spec `v29` (RGB units beside fluorescence units, `R_HETEROGENEOUS_LAYOUT_NOT_ENABLED`). CellPatcher passes preprocessing's `RunStoppedError` on unchanged (its code and message, then the stopped run's errors with their codes, messages, paths and suggested actions, in order; Spec ADR 0005) and adds no advice of its own: do what those errors say. A report preprocessing cannot read there is `RUN_FOLDER_REPORT_UNREADABLE`, naming the report, also unchanged. CellPatcher never reads `discovery_report.json`. A folder with neither a run nor a stopped run's report is `preprocessing_run_refused` (give a written run, or run preprocessing first). | | *The preprocessing run in ... has no published experiment description* (`A_DESCRIPTION_REQUIRED`) | Every run needs one (Spec ADR 0002 AR10): describe the experiment and publish its description in the preprocessing notebook, run preprocessing again and give CellPatcher that run. | | *normalization.plane_histograms/manifest names ...* (`not_the_run_output`) | Only the run's own files, unrenamed in its output folder, are read. Give that folder's `plane_histograms.csv` (and leave `manifest` empty). | | *... these images of the run have no repeat group* (`missing_repeat_group`) / *... several repeat groups to the images of one condition and biological-repeat folder* (`repeat_group_conflict`) | The `biological_repeat` scope pools the repeat groups of the run's description: run preprocessing again with its published description. `normalization.experiment_design` was removed (the derived `experiment_design.csv` is never read). | diff --git a/notebooks/CellPatcher/CHANGELOG.md b/notebooks/CellPatcher/CHANGELOG.md index f4421353..b4af0c03 100644 --- a/notebooks/CellPatcher/CHANGELOG.md +++ b/notebooks/CellPatcher/CHANGELOG.md @@ -74,10 +74,25 @@ Release v0.3.0 Pin preprocessing v0.4.0rc4; prepare v0.2.0rc2 --- -## [Unreleased] - Preprocessing v0.7.0, normalization v0.7.1 +## [Unreleased] - Preprocessing v0.7.0, normalization v0.7.1; a stopped preprocessing run's refusal passed on (#126) For v0.7.2 or v0.8.0. +### Fixed +- **#126: a run preprocessing stopped on purpose is refused with preprocessing's own refusal, unchanged, and no + advice of CellPatcher's.** On an output folder where preprocessing stopped without writing a run (Spec `v29`: RGB + units beside fluorescence units, `R_HETEROGENEOUS_LAYOUT_NOT_ENABLED`), v0.7.1 refused with + `preprocessing_run_refused` ("holds no run_manifest.json") and advised running preprocessing again, which stops + the same way. Preprocessing v0.7.0's `RunInputs.open` raises `RunStoppedError` there; CellPatcher's + `PreprocessingCheckError` (chained `from` it) now holds first an issue with its code `RUN_FOLDER_STOPPED` and + its message, exactly, with an empty suggested action, then its `issues` (the stopped run's errors), unchanged and + in order (Spec ADR 0005, construction and propagation: no rewording, no code of CellPatcher's around it). A run + report preprocessing cannot read (`RunReportUnreadableError`) gives one issue with its code + `RUN_FOLDER_REPORT_UNREADABLE` and message, naming the report. CellPatcher reads no `discovery_report.json`. A + folder with neither a run nor a stopped run's report says to give a written run or run preprocessing first (no + "again"); a written run that is stale (an image changed since, an older manifest) keeps the advice to run + preprocessing again, which fixes it. `tests/test_stopped_run.py`. Reworked from draft PR #128. + ### Changed - **Dependencies:** pins preprocessing `v0.7.0` (`8865b72`; core and `zarr` extra; was `v0.6.1`) and normalization `v0.7.1` (`fcfaeac`; was `v0.7.0`), the tag preprocessing `v0.7.0` pins (owner decision D-h). diff --git a/src/cellpatcher/run_open.py b/src/cellpatcher/run_open.py index 06fa195b..8be3fc07 100644 --- a/src/cellpatcher/run_open.py +++ b/src/cellpatcher/run_open.py @@ -169,7 +169,11 @@ def open_run( ``unrecorded_files`` (images or masks the run did not record), ``zarr_extra_missing`` or ``preprocessing_run_refused``, with the brick's reason, when ``RunInputs`` refuses the run, or - ``unreadable_plane_histograms`` when its table cannot be read. + ``unreadable_plane_histograms`` when its table cannot be read. A folder where + preprocessing stopped without writing a run (``RunStoppedError``) gives + ``RUN_FOLDER_STOPPED`` with preprocessing's message, then the stopped run's own + error issues, all unchanged; a report preprocessing cannot read there gives + ``RUN_FOLDER_REPORT_UNREADABLE`` (:func:`_refusal_issues`, issue #126). """ from morphobricks_normalization.csv_io import CsvFormatError from morphobricks_preprocessing.manifest import ManifestFormatError @@ -190,7 +194,7 @@ def open_run( except (RunInputsError, ManifestFormatError) as exc: # ManifestFormatError: a manifest of another version (preprocessing v0.5.1 reads version 4 only, # older runs are refused, never converted) or not a manifest at all. - raise PreprocessingCheckError([_refusal_issue(exc, folder)]) from exc + raise PreprocessingCheckError(_refusal_issues(exc, folder)) from exc except CsvFormatError as exc: raise PreprocessingCheckError([ error( @@ -208,6 +212,37 @@ def open_run( """The code of a run without a published experiment description (Spec ADR 0002 AR10, AR11 (1)).""" +def _refusal_issues(exc: Exception, folder: Path) -> list[ValidationIssue]: + """Return the issues for ``RunInputs.open`` refusing the run in *folder*. + + Where preprocessing stopped on purpose without writing a run (Spec ``v29``: + ``R_HETEROGENEOUS_LAYOUT_NOT_ENABLED``), ``RunInputs.open`` raises ``RunStoppedError`` + (``RUN_FOLDER_STOPPED``, preprocessing contract §9.1) with the stopped run's error issues; a + report it cannot read is ``RunReportUnreadableError`` (``RUN_FOLDER_REPORT_UNREADABLE``). + Both are passed on unchanged (Spec ADR 0005, construction and propagation): the first issue + has the error's ``code`` and ``str()`` as its code and message, with no prefix, suffix or + advice of CellPatcher's (an empty action), followed for a stopped run by its ``issues``, + unchanged and in order. CellPatcher's own advice to run preprocessing again would loop there + (issue #126), so it adds none, and it never reads the run report itself. + """ + from morphobricks_preprocessing import MANIFEST_FILENAME, RunReportUnreadableError, RunStoppedError + from morphobricks_preprocessing.validation import error + + if isinstance(exc, RunStoppedError): + return [error(exc.code, str(exc), [str(folder)]), *exc.issues] + if isinstance(exc, RunReportUnreadableError): + return [error(exc.code, str(exc), [str(exc.path)])] + if not (folder / MANIFEST_FILENAME).exists(): # no run written there, and no stopped run's report + return [error( + "preprocessing_run_refused", + f"The preprocessing run in {folder} cannot be used: {exc}", + [str(folder)], + "Give CellPatcher the output folder of a preprocessing run that was written (it holds " + "run_manifest.json), or run preprocessing on the experiment first.", + )] + return [_refusal_issue(exc, folder)] # a written run: stale, older or changed since + + def _refusal_issue(exc: Exception, folder: Path) -> ValidationIssue: """Return the issue for ``RunInputs.open`` refusing the run in *folder*, by its reason. diff --git a/tests/test_stopped_run.py b/tests/test_stopped_run.py new file mode 100644 index 00000000..e948c790 --- /dev/null +++ b/tests/test_stopped_run.py @@ -0,0 +1,176 @@ +"""A run preprocessing stopped on purpose is refused with preprocessing's own refusal, unchanged (issue #126). + +Found by the S3.4 adversarial suite (MorphoFeature draft PR #240, row A07). Spec fixture ``v29`` puts RGB +units beside fluorescence units; preprocessing stops it on purpose (``R_HETEROGENEOUS_LAYOUT_NOT_ENABLED``) +and writes no run, only its report. CellPatcher said "Run preprocessing again", which stops the same way: +its advice looped. Since preprocessing v0.7.0, ``RunInputs.open`` raises ``RunStoppedError`` +(``RUN_FOLDER_STOPPED``, preprocessing contract §9.1) there, and ``RunReportUnreadableError`` +(``RUN_FOLDER_REPORT_UNREADABLE``) for a report it cannot read. Spec ADR 0005 (construction and +propagation): CellPatcher passes each on with its code and message unchanged, adds no advice of its own, +and passes a stopped run's issues on unchanged and in order. It never reads ``discovery_report.json``. +""" + +import json +from pathlib import Path + +import pytest +import tifffile + +from cellpatcher.config import CellPatcherConfig, GridConfig +from cellpatcher.orchestration import run_patching_condition_repeat_tree +from cellpatcher.run_open import open_run +from cellpatcher.statistics import PreprocessingCheckError + +VALID = Path(__file__).parent / "spec_fixtures" / "fixtures" / "valid" +SRC = Path(__file__).resolve().parents[1] / "src" / "cellpatcher" + + +def _v29_stopped(tmp_path): + """Run preprocessing on Spec v29, as the G4 suite does; return (experiment, output, its errors).""" + from morphobricks_preprocessing import run_experiment + from morphobricks_preprocessing.axes import prefill_mapping + from morphobricks_preprocessing.testing_described import description_of, write_described_tree + + (fixture,) = VALID.glob("v29_*.toml") + parsed, data = description_of(fixture.read_bytes()) + experiment, output = tmp_path / "experiment", tmp_path / "output" + write_described_tree(experiment, None, parsed) + output.mkdir() + (output / "morphobricks.toml").write_bytes(data) + result = run_experiment(experiment, prefill_mapping("CYX"), output_folder=output) + assert not result.written and not (output / "run_manifest.json").exists() + return experiment, output, [issue for issue in result.issues if issue.is_error] + + +def _tree_run(experiment, output, target): + config = CellPatcherConfig(mode="grid", grid=GridConfig(tile_size=4)) + config.common.preprocessing_run, config.common.output_dir = str(output), str(target) + config.export.enabled = True + return run_patching_condition_repeat_tree(experiment, config=config, combine_metadata=True) + + +def _fields(issue): + return (issue.severity, issue.code, issue.message, issue.paths, issue.action) + + +def test_v29_passes_run_stopped_error_on_unchanged_with_no_advice_of_cellpatchers(tmp_path): + from morphobricks_preprocessing import RunInputs, RunStoppedError + + experiment, output, refused = _v29_stopped(tmp_path) + assert [issue.code for issue in refused] == ["R_HETEROGENEOUS_LAYOUT_NOT_ENABLED"] # v29's single refusal + with pytest.raises(RunStoppedError) as stopped: # what CellPatcher passes on + RunInputs.open(output) + + with pytest.raises(PreprocessingCheckError) as raised: + _tree_run(experiment, output, tmp_path / "patches") + first, *rest = raised.value.issues + # The error itself: its code and its message, compared as strings, no action of CellPatcher's. + assert first.code == RunStoppedError.code == "RUN_FOLDER_STOPPED" + assert first.message == str(stopped.value) + assert first.action == "" and first.paths == (str(output),) + # Then the stopped run's issues, equal to RunStoppedError.issues and to the run's own errors, in order. + assert tuple(rest) == stopped.value.issues + assert [_fields(issue) for issue in rest] == [_fields(issue) for issue in refused] + assert isinstance(raised.value.__cause__, RunStoppedError) + # No text of CellPatcher's own: every message and action is preprocessing's. + assert "cannot be used" not in str(raised.value) + assert not (tmp_path / "patches").exists() + + +def test_the_issues_come_from_run_stopped_error_not_from_reading_the_report(tmp_path, monkeypatch): + # The issues passed on are RunStoppedError's, in its order and unchanged (paths not re-sorted), and + # CellPatcher opens no discovery_report.json of its own. + from morphobricks_preprocessing import RunInputs, RunStoppedError + from morphobricks_preprocessing.validation import Severity, ValidationIssue + + raised_issues = ( + ValidationIssue(Severity.ERROR, "B_SECOND", "second, listed first.", ("z.tif", "a.tif"), "Fix B."), + ValidationIssue(Severity.ERROR, "A_FIRST", "first, listed second.", (), ""), + ) + message = "RUN_FOLDER_STOPPED: stopped, as preprocessing words it." + + def stopped(*_args, **_kwargs): + raise RunStoppedError(message, raised_issues) + + def no_report_read(self, *args, **kwargs): + if self.name == "discovery_report.json": + raise AssertionError("CellPatcher read discovery_report.json") + return original(self, *args, **kwargs) + + original = Path.read_text + monkeypatch.setattr(RunInputs, "open", stopped) + monkeypatch.setattr(Path, "read_text", no_report_read) + (tmp_path / "discovery_report.json").write_bytes(b"this is not read") + with pytest.raises(PreprocessingCheckError) as raised: + open_run(tmp_path) + first, *rest = raised.value.issues + assert (first.code, first.message, first.action) == ("RUN_FOLDER_STOPPED", message, "") + assert tuple(rest) == raised_issues + + +@pytest.mark.parametrize( + "report", + [ + "not json", + json.dumps({"report_version": "2", "status": "stopped", "issues": [{"code": "X", "severity": "error"}]}), + json.dumps({"report_version": "1", "step": "run", "status": "stopped", "provisional": False, "issues": []}), + ], +) +def test_an_unreadable_report_gives_preprocessings_refusal_unchanged(tmp_path, report): + # Nothing is guessed from a report preprocessing cannot read: its code and message, naming the report. + from morphobricks_preprocessing import RunInputs, RunReportUnreadableError + + path = tmp_path / "discovery_report.json" + path.write_text(report, encoding="utf-8") + with pytest.raises(RunReportUnreadableError) as unreadable: + RunInputs.open(tmp_path) + with pytest.raises(PreprocessingCheckError) as raised: + open_run(tmp_path) + (issue,) = raised.value.issues + assert issue.code == RunReportUnreadableError.code == "RUN_FOLDER_REPORT_UNREADABLE" + assert issue.message == str(unreadable.value) + assert issue.paths == (str(path),) and issue.action == "" + + +def test_a_folder_without_a_run_or_report_says_to_run_preprocessing_first_not_again(tmp_path): + with pytest.raises(PreprocessingCheckError) as raised: + open_run(tmp_path) + assert [issue.code for issue in raised.value.issues] == ["preprocessing_run_refused"] + assert "holds no run_manifest.json" in str(raised.value) + assert "again" not in raised.value.issues[0].action.lower() + + +@pytest.mark.parametrize("step, status, provisional", [("run", "written", False), ("check", "stopped", False), + ("run", "stopped", True)]) +def test_a_report_of_no_stopped_run_gives_the_plain_missing_run_refusal(tmp_path, step, status, provisional): + # A written, check or provisional report names no stopped run: the plain refusal of a folder without a run. + report = {"report_version": "1", "step": step, "status": status, "provisional": provisional, "issues": [ + {"code": "X", "severity": "error", "message": "m", "paths": [], "action": "a"}]} + (tmp_path / "discovery_report.json").write_text(json.dumps(report), encoding="utf-8") + with pytest.raises(PreprocessingCheckError) as raised: + open_run(tmp_path) + assert [issue.code for issue in raised.value.issues] == ["preprocessing_run_refused"] + assert "holds no run_manifest.json" in str(raised.value) + assert "again" not in raised.value.issues[0].action.lower() + + +def test_a_stale_run_still_advises_running_preprocessing_again(tmp_path): + # A run whose image changed since it was written is one a re-run fixes: that advice stays. + from morphobricks_preprocessing.testing_described import make_described_run + + (fixture,) = VALID.glob("v13_*.toml") + run = make_described_run(tmp_path / "run", fixture.read_bytes()) + image = next(run.experiment.rglob("*.tif")) + tifffile.imwrite(image, tifffile.imread(image)[:, :4, :4], photometric="minisblack", metadata={"axes": "CYX"}) + with pytest.raises(PreprocessingCheckError) as raised: + open_run(run.output) + assert [issue.code for issue in raised.value.issues] == ["preprocessing_run_refused"] + assert "Run preprocessing again" in raised.value.issues[0].action + + +def test_cellpatcher_constructs_no_run_folder_code_and_reads_no_run_report(): + # Construction is preprocessing's alone (Spec ADR 0005): no RUN_FOLDER_* text and no report reader here. + for path in SRC.rglob("*.py"): + text = path.read_text(encoding="utf-8") + assert '"RUN_FOLDER_' not in text and "'RUN_FOLDER_" not in text, path + assert "discovery_report.json" not in text, path From da47ad4d6730b5e923fb8c59b061f0691a81dd4f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 13:12:20 +0000 Subject: [PATCH 3/3] Keep decision D47 and document why (#124) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Owner decision of 17 November 2026 on #124: keep D47. In memory an integer cell-mode mask is instance labels used as stored, so a 0/1 integer region is one object: an in-memory array carries no representation and its values cannot tell a region from labels, and CellPatcher labels no mask (Spec ADR 0005 BM2/BM4). A described file run declares the representation and refuses a binary mask as objects unless binary_mask_policy is set. docs/plan.md §13 records D47 with its reason and the rejected alternative; docs/patching_modes.md and run_patching's docstring warn that a region in cell mode is one large patch and say to pass instance labels. No behaviour change; tests/test_cell_strategy.py pins it through run_patching. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- docs/patching_modes.md | 10 +++++++++- docs/plan.md | 19 +++++++++++++++++++ notebooks/CellPatcher/CHANGELOG.md | 11 ++++++++++- src/cellpatcher/pipeline.py | 4 ++-- tests/test_cell_strategy.py | 19 +++++++++++++++++++ 5 files changed, 59 insertions(+), 4 deletions(-) diff --git a/docs/patching_modes.md b/docs/patching_modes.md index 42f78692..280864c4 100644 --- a/docs/patching_modes.md +++ b/docs/patching_modes.md @@ -39,6 +39,14 @@ In memory (`run_patching`, the object scan and `CellSegmentationStrategy` called integer NumPy array, used as stored: a boolean, float or other array, a list or None is `A_MASK_NOT_INSTANCES`, and `binary_mask_policy` is refused. Labels above the int32 maximum are refused. +> **An in-memory 0/1 mask is one object (decision D47, kept on 17 November 2026, issue #124).** An array in +> memory carries no representation, and its values cannot tell a region from instance labels, so CellPatcher +> takes every integer array as instance labels and never labels it: a 0/1 or 0/255 integer mask is **one** +> object, however many separate regions it has. A region such as a tissue mask passed to cell mode therefore +> gives one large patch, without a refusal. Pass instance labels (preprocessing's `label_binary` in memory, or its recorded +> `binary_to_instances` conversion), or use a described file run, where a mask declared `binary` is refused as +> objects unless `binary_mask_policy` is set. See `docs/plan.md` §13, D47. + Key parameters to know: - `patch_size` @@ -64,7 +72,7 @@ Notes: Common pitfalls: - Wrong `image_axes` / `mask_axes`. -- Passing a binary mask: give instance labels in memory; in a file run declare it `binary` and set `binary_mask_policy="connected_components"` (whose computed labels are not the mask's values). +- Passing a binary mask: give instance labels in memory (a 0/1 integer array is one object, D47); in a file run declare it `binary` and set `binary_mask_policy="connected_components"` (whose computed labels are not the mask's values). - Picking a global patch size without scanning first. - Expecting border-touching objects when `exclude_border=True` (default): it skips objects whose *bounding boxes* touch the image border, not patches. diff --git a/docs/plan.md b/docs/plan.md index e0cc3f71..16605d1b 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -661,3 +661,22 @@ Reviewed in October 2026. `Normalization_Scale_C` pair per channel; earlier tables are still read on load (N47). 15. **[D15] Filters.** *Decided:* keep filters on raw values. 16. **[D16] Changed images.** *Decided:* block the run. + +Decision recorded later, kept here with its reason: + +- **[D47] An in-memory integer mask is instance labels, used as stored** (owner decision of + 2026-10-26; *kept* by the owner on 17 November 2026, issue #124). In memory (`run_patching`, + the object scan, `CellSegmentationStrategy`) a cell-mode mask is a plain integer NumPy array + whose every non-zero value is one object, so a 0/1 or 0/255 integer mask is **one** object + (label 1 or 255), however many separate regions it has. *Why it is kept:* an in-memory array + carries no representation, and its pixels cannot prove instance semantics (Spec ADR 0005, P05: + a 0/1 `instances` mask is valid), so CellPatcher has nothing to tell a region from a one-object + label image by; guessing from the values would label some masks silently, which ADR 0005 BM2/BM4 + forbid (CellPatcher labels no mask). The representation is declared where it exists: in a + described file run, a mask declared `binary` is refused as objects (`A_MASK_NOT_INSTANCES`) + unless the request sets `binary_mask_policy` explicitly. A boolean or float array is still + refused in memory (`A_MASK_NOT_INSTANCES`). *Consequence, documented for users:* a region (for + example a tissue mask) passed in memory to cell mode becomes one large "cell"; pass instance + labels instead (preprocessing's `label_binary` in memory, or its recorded + `binary_to_instances` conversion). The rejected alternative was a `representation=` argument on every in-memory call (a breaking API + change). `tests/test_cell_strategy.py` pins the behaviour through `run_patching`. diff --git a/notebooks/CellPatcher/CHANGELOG.md b/notebooks/CellPatcher/CHANGELOG.md index b4af0c03..05461541 100644 --- a/notebooks/CellPatcher/CHANGELOG.md +++ b/notebooks/CellPatcher/CHANGELOG.md @@ -74,7 +74,7 @@ Release v0.3.0 Pin preprocessing v0.4.0rc4; prepare v0.2.0rc2 --- -## [Unreleased] - Preprocessing v0.7.0, normalization v0.7.1; a stopped preprocessing run's refusal passed on (#126) +## [Unreleased] - Preprocessing v0.7.0, normalization v0.7.1; a stopped preprocessing run's refusal passed on (#126); D47 documented (#124) For v0.7.2 or v0.8.0. @@ -93,6 +93,15 @@ For v0.7.2 or v0.8.0. "again"); a written run that is stale (an image changed since, an older manifest) keeps the advice to run preprocessing again, which fixes it. `tests/test_stopped_run.py`. Reworked from draft PR #128. +### Documented +- **#124: decision D47 is kept and documented** (owner decision of 17 November 2026). In memory (`run_patching`, + the object scan, `CellSegmentationStrategy`) an integer cell-mode mask is instance labels used as stored, so a + 0/1 integer region is one object, however many separate regions it has: an in-memory array carries no + representation and its values cannot tell a region from labels, and CellPatcher labels no mask (Spec ADR 0005). + `docs/plan.md` §13 records D47 with its reason; `docs/patching_modes.md` and `run_patching`'s docstring warn + that a region passed to cell mode gives one large patch and to pass instance labels instead. No behaviour change; + `tests/test_cell_strategy.py` pins it through `run_patching`. + ### Changed - **Dependencies:** pins preprocessing `v0.7.0` (`8865b72`; core and `zarr` extra; was `v0.6.1`) and normalization `v0.7.1` (`fcfaeac`; was `v0.7.0`), the tag preprocessing `v0.7.0` pins (owner decision D-h). diff --git a/src/cellpatcher/pipeline.py b/src/cellpatcher/pipeline.py index c35b20c6..32e0d153 100644 --- a/src/cellpatcher/pipeline.py +++ b/src/cellpatcher/pipeline.py @@ -804,8 +804,8 @@ def run_patching(images=None, masks=None, config=None, image_metadata=None, frac A single label array or a list/tuple of label arrays, one per image. * ``mode='cell'`` — **required**. Integer label map where each unique - non-zero value is a separate cell, used as given (decision D47: a 0/1 - integer mask is one object), a plain NumPy array; labels above int32 are refused. + non-zero value is a separate cell, used as given (decision D47: a 0/1 integer mask, a region + too, is one object; pass instance labels), a plain NumPy array; labels above int32 are refused. Nothing is converted in memory (Spec ADR 0005 BM4): any other mask is refused with ``A_MASK_NOT_INSTANCES``, and ``cell.binary_mask_policy`` too (:mod:`cellpatcher.mask_policy`). * ``mode='random'`` — **optional**. When provided, patches are diff --git a/tests/test_cell_strategy.py b/tests/test_cell_strategy.py index ae519d04..0a386ec1 100644 --- a/tests/test_cell_strategy.py +++ b/tests/test_cell_strategy.py @@ -348,3 +348,22 @@ def test_cell_strategy_4d_labels_produces_non_2d_selected_raises(): s = CellSegmentationStrategy(CellConfig(), mask_axes="TCYX") with pytest.raises(ValueError, match="have T planes.*Set common.t_policy"): s.generate_regions(image_shape=(5, 5), labels=labels) + + +def test_d47_an_in_memory_region_is_one_object_through_run_patching(): + # Decision D47, kept by the owner on 17 November 2026 (issue #124; docs/plan.md §13): an in-memory + # array carries no representation, so a 0/1 integer region of two separate blobs is instance label 1, + # one object, through the public run_patching too: never labelled, never refused. + from cellpatcher.config import CellPatcherConfig + from cellpatcher.pipeline import run_patching + + region = np.zeros((32, 32), dtype=np.uint8) + region[2:8, 2:8] = 1 + region[20:30, 18:28] = 1 + config = CellPatcherConfig(mode="cell") + config.cell.patch_size = 8 + config.cell.exclude_border = False + result = run_patching(images=np.zeros((32, 32), np.uint16), masks=region, config=config, + image_metadata=[{"position_id": "P"}]) + assert [patch.label_id for patch in result.patches] == [1] + assert result.patches[0].area_px == 36 + 100