From 6137b12023589cabb2ab0f7c59a05cf3f7675e35 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 18:28:58 +0000 Subject: [PATCH 01/15] #395: a channel keeps one mutual swap partner A third channel whose nearest channel is already paired in a mutual swap no longer overwrites that partner's pairing; it stays a plain swap finding, so one channel is never reported in two incompatible swaps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- .../channel_identity.py | 4 ++++ tests/test_channel_identity.py | 23 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/morphobricks_preprocessing/channel_identity.py b/src/morphobricks_preprocessing/channel_identity.py index 6690deb7..a304c52a 100644 --- a/src/morphobricks_preprocessing/channel_identity.py +++ b/src/morphobricks_preprocessing/channel_identity.py @@ -396,6 +396,10 @@ def _findings( partner = places.get(other) if found.mutual or found.nearest_absent or partner is None: continue + if (taken := findings.get(other)) is not None and taken.mutual: + # A channel has one swap partner: the first pair (sorted order) keeps it, and this + # channel stays a plain swap finding (#395). + continue ratio = settings.partner_ratio if not _leans(places[key], found.nearest, limit, ratio): continue diff --git a/tests/test_channel_identity.py b/tests/test_channel_identity.py index 09693469..8186658f 100644 --- a/tests/test_channel_identity.py +++ b/tests/test_channel_identity.py @@ -110,6 +110,29 @@ def test_two_swapped_channels_give_one_mutual_swap(): assert "swapped" in issue.message and "nearest" not in issue.message.casefold() +def test_a_channel_keeps_one_swap_partner(): + """#395: A and C look alike, and B is swapped with both in one unit: one pair, not two.""" + ref = {"A": (800.0, 100.0, 4000.0), "B": (4000.0, 500.0, 20000.0), "C": (800.0, 100.0, 4000.0)} + swapped = {"A": ref["B"], "B": ref["A"], "C": ref["B"]} + units = [Unit("ctrl", "rep1", f"t{i}") for i in range(5)] + summaries = [ + summary(unit, i, swapped if unit.technical_repeat == "t0" else ref) + for unit in units + for i in range(2) + ] + report = check_channel_identity(summaries) + found = {f.channel: (f.code, f.nearest, f.mutual) for f in report.findings} + assert found == { + "A": (POSSIBLE_CHANNEL_SWAP, "B", True), + "B": (POSSIBLE_CHANNEL_SWAP, "A", True), + "C": (POSSIBLE_CHANNEL_SWAP, "B", False), + } + messages = [issue.message for issue in report.validation_issues()] + assert sum("look swapped" in m for m in messages) == 1 + assert "channels A and B look swapped" in messages[0] + assert check_channel_identity(summaries[::-1]).findings == report.findings + + def test_a_dim_channel_is_unlike_the_others_but_no_swap(): def dim(unit, stains): if unit == SWAPPED: From 240a50a0ab97985a901535acaa6c0976d76f56a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 18:29:45 +0000 Subject: [PATCH 02/15] #428: key cached preview planes by the confirmed roles The same file read through other roles names other pixels for the same coordinates, so the roles (axes, roles, singleton roles) are now part of the PreviewCache key, for reads and for the discard after a rewrite. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- src/morphobricks_preprocessing/preview.py | 20 ++++++++++++++++++-- tests/test_preview.py | 20 ++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/morphobricks_preprocessing/preview.py b/src/morphobricks_preprocessing/preview.py index 96b3f1a1..caba3725 100644 --- a/src/morphobricks_preprocessing/preview.py +++ b/src/morphobricks_preprocessing/preview.py @@ -302,6 +302,21 @@ class StripOptions: memory_limit: int = DEFAULT_MEMORY_LIMIT +def _plane_key( + path: str | os.PathLike, + mapping: AxisMapping, + where: tuple[Fingerprint, int, int | None, int | None], + side: int, +) -> Hashable: + """Return the cache key of one reduced plane. + + The confirmed roles decide which pixels a coordinate names, so they are part of the key: + the same file read through other roles is another plane (#428). + """ + roles = (mapping.axes, mapping.roles, mapping.singleton_roles) + return (os.fspath(path), roles, *where, side) + + def _cached_plane( path: str | os.PathLike, mapping: AxisMapping, @@ -310,7 +325,7 @@ def _cached_plane( ) -> ReducedPlane: """Return channel ``c`` reduced, from the cache when the same file content was read.""" fingerprint, c, z, t = where - key = (os.fspath(path), fingerprint, c, z, t, options.side) + key = _plane_key(path, mapping, where, options.side) plane = options.cache.get(key) if options.cache is not None else None if plane is None: channel = c if mapping.index_of("C") is not None else None @@ -379,7 +394,8 @@ def channel_strip( except PreviewRefused: if options.cache is not None: # nor kept: a plane read across a rewrite is not that file for c in range(layout.channel_count): - options.cache.discard((os.fspath(path), fingerprint, c, z, t, options.side)) + where = (fingerprint, c, z, t) + options.cache.discard(_plane_key(path, mapping, where, options.side)) raise return ChannelStrip(os.fspath(path), z, t, tuple(panels), strip_png([p.panel for p in panels])) diff --git a/tests/test_preview.py b/tests/test_preview.py index f7135a1c..af5dd368 100644 --- a/tests/test_preview.py +++ b/tests/test_preview.py @@ -220,6 +220,26 @@ def test_the_cache_serves_the_same_content_and_rereads_a_changed_file(tmp_path, assert reads == [0, 1, 2, 0, 1, 2] and len(options.cache) == 6 +def test_the_cache_keeps_planes_read_through_other_roles_apart(tmp_path, monkeypatch): + """#428: one file, two unnamed dimensions read as ZC or CZ, one shared cache.""" + data = np.arange(4, dtype=np.uint16).reshape(2, 2, 1, 1) * 10 + np.zeros((2, 2, 8, 8), "u2") + path = tmp_path / "qq.tif" + tifffile.imwrite(path, data, photometric="minisblack", metadata={"axes": "QQYX"}) + reads = [] + original = preview.read_source_plane + monkeypatch.setattr( + preview, "read_source_plane", lambda *a, **k: reads.append(k["c"]) or original(*a, **k) + ) + options = StripOptions(cache=PreviewCache()) + shown = {} + for roles in ("ZCYX", "CZYX", "ZCYX"): + mapping = AxisMapping("QQYX", roles) + strip = channel_strip(path, "qq.tif", review_for("qq.tif", mapping), options) + shown[roles] = [int(panel.plane.pixels[0, 0]) for panel in strip.panels] + assert shown == {"ZCYX": [20, 30], "CZYX": [10, 30]} # middle Z is 1: a[1, c] or a[c, 1] + assert reads == [0, 1, 0, 1] # the same roles again read nothing + + def test_the_cache_drops_the_least_recently_used_plane(): plane = preview.ReducedPlane(np.zeros((2, 2), np.uint8), 1, (2, 2), None, None, None) cache = PreviewCache(size=2) From 7b639e61d507f4c131c3159a17e0dc0bc8882943 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 18:30:56 +0000 Subject: [PATCH 03/15] #433: refuse a view of fewer than one channel before any read ViewRequest and header_channels now raise a ValueError naming the value when the number of channels to draw is not a whole number of at least 1, instead of an IndexError, AttributeError or ZeroDivisionError after reading. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- src/morphobricks_preprocessing/header_preview.py | 7 ++++++- src/morphobricks_preprocessing/image_view.py | 13 +++++++++++++ tests/test_image_viewer.py | 14 ++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/morphobricks_preprocessing/header_preview.py b/src/morphobricks_preprocessing/header_preview.py index 97407e18..8a5eec6c 100644 --- a/src/morphobricks_preprocessing/header_preview.py +++ b/src/morphobricks_preprocessing/header_preview.py @@ -265,8 +265,13 @@ def header_channels( PreviewUnavailable Without a named channel axis, or over the caps. PlaneReadError, OSError, ValueError, IndexError, MemoryError - When the file cannot be read. + When the file cannot be read; ValueError also when ``shown`` is not a whole number of + at least 1. """ + if isinstance(shown, bool) or not isinstance(shown, int) or shown < 1: + raise ValueError( # before any read (#433) + f"The number of channels to draw must be a whole number of at least 1, not {shown!r}." + ) if not meta.readable: raise PreviewUnavailable(f"the header cannot be read: {meta.error or 'unknown reason'}") mapping, projected, c_axis = _channel_layout(meta) diff --git a/src/morphobricks_preprocessing/image_view.py b/src/morphobricks_preprocessing/image_view.py index 082a5592..8335974c 100644 --- a/src/morphobricks_preprocessing/image_view.py +++ b/src/morphobricks_preprocessing/image_view.py @@ -100,6 +100,11 @@ def middle_slice(length: int) -> int: class ViewRequest: """Which plane of an image to draw, and how. + Raises + ------ + ValueError + When ``shown`` is not a whole number of at least 1. + Attributes ---------- z, t @@ -125,6 +130,14 @@ class ViewRequest: memory_limit: int = DEFAULT_MEMORY_LIMIT expected: Fingerprint | None = None + def __post_init__(self) -> None: + # Refused before any read: no channel to draw is not a picture (#433). + if isinstance(self.shown, bool) or not isinstance(self.shown, int) or self.shown < 1: + raise ValueError( + f"The number of channels to draw must be a whole number of at least 1, " + f"not {self.shown!r}." + ) + def read_view( path: str | os.PathLike, diff --git a/tests/test_image_viewer.py b/tests/test_image_viewer.py index aaa9a17e..1295e5e7 100644 --- a/tests/test_image_viewer.py +++ b/tests/test_image_viewer.py @@ -16,8 +16,10 @@ from morphobricks_preprocessing.axes import AxisMapping from morphobricks_preprocessing.fingerprint import Fingerprint +from morphobricks_preprocessing.header_preview import header_channels from morphobricks_preprocessing.image_tree import ImageEntry, choices, entries_of, resolve from morphobricks_preprocessing.image_view import ViewRequest, read_view, view_lengths +from morphobricks_preprocessing.metadata import inspect_image from morphobricks_preprocessing.preview import PreviewRefused from morphobricks_preprocessing.report_view import report_html @@ -124,6 +126,18 @@ def test_at_most_six_channels_are_drawn_and_the_view_says_so(tmp_path): assert [t.c for t in one.tiles] == [None] and one.shown_text == "the only channel" +@pytest.mark.parametrize("shown", [0, -1, True, 1.5, "2"]) +def test_a_view_of_no_channel_is_refused_before_any_read(tmp_path, monkeypatch, shown): + """#433: ``shown`` below 1 (or not a whole number) is a ValueError, not a crash later.""" + write(tmp_path / "a.tif", "CYX", (2, 8, 8)) + meta = inspect_image(tmp_path / "a.tif", "a.tif") + monkeypatch.setattr(tifffile.TiffFile, "asarray", lambda *a, **k: pytest.fail("read")) + with pytest.raises(ValueError, match="at least 1"): + ViewRequest(shown=shown) + with pytest.raises(ValueError, match="at least 1"): + header_channels(tmp_path / "a.tif", meta, 64, shown) + + def test_a_view_is_refused_for_another_revision_and_without_y_and_x(tmp_path): path = tmp_path / "a.tif" write(path, "CYX", (2, 8, 8)) From 35a01b2c73ae4f2e54106ce62908b929c6f23bec Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 18:32:51 +0000 Subject: [PATCH 04/15] #469: show a plane that cannot be read as the H&E card's and CLI's refusal The tissue-mask preview and write, and the tissue-mask command, now catch PlaneReadError (PlaneMemoryError, CompressionNotBoundedError) and OSError with the other refusals: the card replaces its working status with the message and hides an earlier preview, and the command prints the image's refusal and exits 1 instead of a traceback. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- .../cli_tissue_mask.py | 4 ++- .../notebook_tissue_mask.py | 8 ++++-- tests/test_cli_tissue_mask.py | 21 +++++++++++++++ tests/test_notebook_tissue_mask.py | 27 +++++++++++++++++++ 4 files changed, 57 insertions(+), 3 deletions(-) diff --git a/src/morphobricks_preprocessing/cli_tissue_mask.py b/src/morphobricks_preprocessing/cli_tissue_mask.py index 67c9b577..dfc86b1a 100644 --- a/src/morphobricks_preprocessing/cli_tissue_mask.py +++ b/src/morphobricks_preprocessing/cli_tissue_mask.py @@ -17,6 +17,7 @@ import argparse +from .plane_errors import PlaneReadError from .run_inputs import RunInputs from .run_inputs_tissue import ( HE_TISSUE_V1, @@ -87,7 +88,8 @@ def tissue_mask_command(args: argparse.Namespace) -> int: for image in images: try: result = run.he_tissue_mask(image, output_mask_id=args.to, rule=args.rule) - except (ValueError, ImportError) as exc: # every refusal (RunInputsError included) + # Every refusal: RunInputsError, a missing extra, and a plane that cannot be read (#469). + except (ValueError, ImportError, PlaneReadError, OSError) as exc: print(f"{image}: no tissue mask written. {exc}") if written: print(f"{plural(len(written), 'image')} before it stay written.") diff --git a/src/morphobricks_preprocessing/notebook_tissue_mask.py b/src/morphobricks_preprocessing/notebook_tissue_mask.py index e6626a3f..dcb18918 100644 --- a/src/morphobricks_preprocessing/notebook_tissue_mask.py +++ b/src/morphobricks_preprocessing/notebook_tissue_mask.py @@ -35,6 +35,7 @@ from .manifest import MANIFEST_FILENAME from .mask_conversion import _check_case_collision, _check_output_id from .notebook_render import blocked_line +from .plane_errors import PlaneReadError from .run_inputs import RunInputs from .run_inputs_tissue import NOT_REUSED, PROVISIONAL_NOTE, tissue_next_steps @@ -43,6 +44,8 @@ """The preview's tint of each excluded component, drawn in this order (the proof of concept's).""" PREVIEW_SIDE = 512 """The largest side of the preview picture; the numbers come from the full-resolution mask.""" +REFUSALS = (ValueError, ImportError, PlaneReadError, OSError) +"""The refusals a preview or a write shows as its message: a plane that cannot be read too.""" def unusable_reason(fov: object) -> str | None: @@ -263,9 +266,10 @@ def preview(self) -> object | None: if self._run is None or not self.preview_image.value: return None self.numbers.value = ui.working("Computing the preview…") + ui.set_visible(self.picture, False) # an earlier image's preview is not this one's try: found = self._run.preview_he_tissue_mask(self.preview_image.value) - except (ValueError, ImportError) as exc: + except REFUSALS as exc: self.numbers.value = ui.status("error", "No preview.", [str(exc)]) return None self.picture.value = png_bytes(tinted(found.rgb, found.components)) @@ -293,7 +297,7 @@ def write(self) -> list | None: try: for image in self.positions.value: results.append(self._run.he_tissue_mask(image, output_mask_id=self.name.value)) - except (ValueError, ImportError) as exc: + except REFUSALS as exc: self.status.value = ui.status( "error", f"No tissue mask was written for {image}.", diff --git a/tests/test_cli_tissue_mask.py b/tests/test_cli_tissue_mask.py index 90d05858..9bfee5ca 100644 --- a/tests/test_cli_tissue_mask.py +++ b/tests/test_cli_tissue_mask.py @@ -95,3 +95,24 @@ def test_without_scikit_image_it_names_the_extra_and_writes_nothing(tmp_path, ca assert main(args) == 1 assert 'pip install "morphobricks-preprocessing[he-mask]"' in capsys.readouterr().out assert tree(run.masks_root) == before + + +def test_a_plane_that_cannot_be_read_exits_1_with_its_message(tmp_path, capsys, monkeypatch): + """#469: a PlaneMemoryError is a refusal of that image, not a traceback.""" + from morphobricks_preprocessing.plane_errors import PlaneMemoryError + from morphobricks_preprocessing.run_inputs import RunInputs + + def refuse(self, *args, **kwargs): + raise PlaneMemoryError("the plane needs 9 GiB; the limit is 2 GiB") + + # What RunInputs.read_plane raises when the plane does not fit the memory limit. + for name in ("he_tissue_mask", "preview_he_tissue_mask"): + monkeypatch.setattr(RunInputs, name, refuse) + run = rgb_run(tmp_path) + before = tree(run.masks_root) + assert main(["tissue-mask", "--output", str(run.output_folder), "--to", "HETissue"]) == 1 + printed = capsys.readouterr().out + assert printed.splitlines()[-1] == ( + f"{IMAGE}: no tissue mask written. the plane needs 9 GiB; the limit is 2 GiB" + ) + assert tree(run.masks_root) == before diff --git a/tests/test_notebook_tissue_mask.py b/tests/test_notebook_tissue_mask.py index 77ce027a..0b5a52c2 100644 --- a/tests/test_notebook_tissue_mask.py +++ b/tests/test_notebook_tissue_mask.py @@ -161,3 +161,30 @@ def test_a_mask_id_with_spaces_keeps_the_button_disabled_and_writes_nothing(tmp_ assert tree(run.masks_root) == before card.name.value = " " assert card.button.disabled and "type the new mask ID" in card.blocker.value + + +def test_a_plane_that_cannot_be_read_is_a_refusal_not_a_working_status(tmp_path, monkeypatch): + """#469: a PlaneMemoryError ends the preview and the write with its message.""" + from morphobricks_preprocessing.plane_errors import PlaneMemoryError + + def refuse(self, *args, **kwargs): + raise PlaneMemoryError("the plane needs 9 GiB; the limit is 2 GiB") + + # What RunInputs.read_plane raises when the plane does not fit the memory limit. + for name in ("he_tissue_mask", "preview_he_tissue_mask"): + monkeypatch.setattr(cards.RunInputs, name, refuse) + monkeypatch.setattr(cards.importlib.util, "find_spec", lambda name: True) # the extra + run = rgb_run(tmp_path) + card = cards.TissueMaskCard() + card.refresh(run.output_folder) + card.picture.layout.display = None # an earlier preview on the page + before = tree(run.masks_root) + card.preview_button.click() + assert "No preview." in card.numbers.value and "9 GiB" in card.numbers.value + assert "Computing" not in card.numbers.value and card.picture.layout.display == "none" + card.positions.value = (IMAGE,) + card.name.value = "HETissue" + card.write() + assert f"No tissue mask was written for {IMAGE}." in card.status.value + assert "9 GiB" in card.status.value and "unexpected" not in card.status.value + assert tree(run.masks_root) == before From 464490f65eaee9220efb96c31a47077e737a620e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 18:33:48 +0000 Subject: [PATCH 05/15] #481: refuse converting a declared mask the run recorded no file of The Convert a mask card showed a green 'The mask is converted.' for a source with no recorded files. It now shows a red card naming the mask ID and source type and writes nothing. The button is not disabled ahead of time: the card refreshes on the description only, so the manifest is read at the click, never a stale copy. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- .../notebook_mask_conversion.py | 26 ++++++++++++++++--- tests/test_notebook_mask_conversion.py | 16 ++++++++++++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/morphobricks_preprocessing/notebook_mask_conversion.py b/src/morphobricks_preprocessing/notebook_mask_conversion.py index 4bd1b473..eae294c2 100644 --- a/src/morphobricks_preprocessing/notebook_mask_conversion.py +++ b/src/morphobricks_preprocessing/notebook_mask_conversion.py @@ -192,11 +192,31 @@ def convert(self) -> list[MaskConversionResult] | None: self._update_button() return None - def _convert(self, operation: str, mask_id: str, name: str) -> list[MaskConversionResult]: - """Run the helper on every image with a file of the mask; show the outputs.""" + def _convert( + self, operation: str, mask_id: str, name: str + ) -> list[MaskConversionResult] | None: + """Run the helper on every image with a file of the mask; show the outputs. + + A declared mask the run recorded no file of is refused: nothing converted is not a + conversion (#481). The run's manifest is read at the click, so it is never stale. + """ run = RunInputs.open(self.output_folder) + images = images_with_mask(run, mask_id) + if not images: + declared = run.description().masks.get(mask_id) + what = f"source type {declared.source_type}" if declared else "not declared" + self.status.value = ui.status( + "error", + "The mask was not converted.", + [ + f"The run recorded no {mask_id} mask file ({what}); nothing was written.", + "Put this mask's files in the masks folder, run the masks step again, " + "then convert.", + ], + ) + return None results = [] - for image in images_with_mask(run, mask_id): + for image in images: if operation == BINARY_TO_INSTANCES: results.append(run.binary_to_instances(image, mask_id, output_mask_id=name)) else: diff --git a/tests/test_notebook_mask_conversion.py b/tests/test_notebook_mask_conversion.py index ee63f423..07222344 100644 --- a/tests/test_notebook_mask_conversion.py +++ b/tests/test_notebook_mask_conversion.py @@ -93,3 +93,19 @@ def test_the_notebook_shows_the_card_under_describe_the_masks(): assert isinstance(nb.mask_conversion, cards.MaskConversionCard) page = nb.run_step() assert nb.mask_conversion.card in page.children[1].children + + +def test_a_declared_mask_without_recorded_files_is_refused_not_converted(tmp_path): + """#481: a source the run recorded no file of is a red card, never a green one.""" + run, _, masks = run_with(tmp_path, declared=(("Unfiled", "unfiled", "binary"),)) + card = cards.MaskConversionCard() + card.refresh(run.output_folder) + card.source.value = "Unfiled" + card.name.value = "UnfiledObjects" + before = tree(masks) + card.button.click() + assert "The mask was not converted." in card.status.value + assert "The run recorded no Unfiled mask file (source type unfiled)" in card.status.value + assert "converted." not in card.status.value.replace("not converted.", "") + assert card.result.value == "" and tree(masks) == before # no output, no lineage line + assert not card.button.disabled # the click reads the manifest again: retry after the run From 2c01604001f34ae985c89e5c8ca1721af0075c9e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 18:34:35 +0000 Subject: [PATCH 06/15] #514: an empty row fold drops the rows of its last fold RowFold.arrange returned early when no row folded and kept the previous fold's rows (and their images and callbacks) in its hidden box and its line. It now empties both first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- .../notebook_row_fold.py | 3 +++ tests/test_notebook_row_fold.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/morphobricks_preprocessing/notebook_row_fold.py b/src/morphobricks_preprocessing/notebook_row_fold.py index a77f80c4..c7d8d62a 100644 --- a/src/morphobricks_preprocessing/notebook_row_fold.py +++ b/src/morphobricks_preprocessing/notebook_row_fold.py @@ -118,6 +118,9 @@ def arrange(self, rows: Sequence[tuple[widgets.Widget, str]]) -> list[widgets.Wi folded = [row for row, status in rows if status == UNCHANGED] self.count = len(folded) if not folded: + # Drop the last fold's rows: they are no longer this card's (#514). + self.folded.children = () + self.line.value = "" return shown self.folded.children = folded self.line.value = ( diff --git a/tests/test_notebook_row_fold.py b/tests/test_notebook_row_fold.py index e300c9b6..ac993477 100644 --- a/tests/test_notebook_row_fold.py +++ b/tests/test_notebook_row_fold.py @@ -21,6 +21,7 @@ CHANGED, NEW, UNCHANGED, + RowFold, reopen_units, row_status, ) @@ -60,6 +61,20 @@ def test_a_row_folds_only_when_every_folder_is_as_saved_and_it_is_answered(): assert row_status(None, rep1, True) == "" and reopen_units(None) is None +def test_a_fold_with_nothing_unchanged_keeps_no_earlier_row(): + """#514: unchanged rows, then all changed: the fold holds none of the old rows.""" + import ipywidgets as widgets + + fold = RowFold("folder") + rows = [widgets.HTML("a"), widgets.HTML("b")] + shown = fold.arrange([(row, UNCHANGED) for row in rows]) + assert fold.folded.children == tuple(rows) and "2 unchanged folders" in fold.line.value + shown = fold.arrange([(row, CHANGED) for row in rows]) + assert fold.count == 0 and fold.bar not in shown and fold.folded not in shown + assert fold.folded.children == () and fold.line.value == "" + assert fold.arrange([]) == [] and fold.folded.children == () + + def stepper(root, masks, out): nb = PreprocessingNotebook(str(root), output_folder=str(out)) nb.welcome() From 282ba0ae43e620861bd6939fa06d8ccc09ecb863 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 18:35:33 +0000 Subject: [PATCH 07/15] #521: rebuild the quick-scan role row when the image's shape changes The row was rebuilt only for other axis letters, so an image with the same letters and other lengths kept the previous image's lengths in its labels. It is now keyed by the letters and the shape; the roles chosen for the letters are kept. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- .../notebook_scan_axes.py | 9 ++++-- tests/test_notebook_scan_axes.py | 29 +++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/morphobricks_preprocessing/notebook_scan_axes.py b/src/morphobricks_preprocessing/notebook_scan_axes.py index ea060f96..a4974bc9 100644 --- a/src/morphobricks_preprocessing/notebook_scan_axes.py +++ b/src/morphobricks_preprocessing/notebook_scan_axes.py @@ -101,6 +101,7 @@ def _build_scan_axes(self) -> None: self._scan_roles: dict[str, AxisMapping] = {} self._scan_boxes: list[widgets.Dropdown] = [] self._scan_row_axes: str | None = None + self._scan_row_shape: tuple[int, ...] | None = None # the lengths the labels give self._scan_applied: object | None = None self._scan_filling = False self.scan_roles_row = widgets.HBox( @@ -119,7 +120,7 @@ def _build_scan_axes(self) -> None: def _reset_scan_axes(self) -> None: """Forget the roles chosen at an earlier scan: a new scan proposes afresh.""" - self._scan_roles, self._scan_row_axes = {}, None + self._scan_roles, self._scan_row_axes, self._scan_row_shape = {}, None, None self.scan_axes_line.value = self.scan_type_line.value = "" # The row ------------------------------------------------------------------------------- @@ -134,7 +135,9 @@ def _scan_roles_follow(self) -> None: if meta is None or not meta.readable: ui.set_visible(self.scan_roles_card, False) return - if meta.axes != self._scan_row_axes: + # The labels give the lengths: another shape with the same letters is rebuilt, the + # roles chosen for those letters kept (#521). + if (meta.axes, tuple(meta.shape)) != (self._scan_row_axes, self._scan_row_shape): self._build_scan_row(meta) self.scan_type_note.value = scan_type_html([meta], one=True) ui.set_visible(self.scan_roles_card, True) @@ -142,7 +145,7 @@ def _scan_roles_follow(self) -> None: def _build_scan_row(self, meta: TiffMetadata) -> None: """Build one list per dimension of the image, holding the role proposed or chosen.""" mapping = self._scan_roles.get(meta.axes) or prefill_mapping(meta.axes) - self._scan_row_axes = meta.axes + self._scan_row_axes, self._scan_row_shape = meta.axes, tuple(meta.shape) self._scan_boxes, cells = [], [] for axis, role, length in zip(meta.axes, mapping.roles, meta.shape, strict=True): box = widgets.Dropdown( diff --git a/tests/test_notebook_scan_axes.py b/tests/test_notebook_scan_axes.py index 2e7dad4f..e1562983 100644 --- a/tests/test_notebook_scan_axes.py +++ b/tests/test_notebook_scan_axes.py @@ -82,6 +82,35 @@ def test_a_role_changed_at_the_scan_redraws_the_pictures_right_there(tmp_path): assert nb.confirmed_mapping is None and nb.preflight is None # still only a proposal +def test_another_shape_with_the_same_axes_shows_its_own_lengths_and_keeps_the_roles(tmp_path): + """#521: CYX (2, 8, 8), then CYX (4, 16, 16): the labels follow, the chosen roles stay.""" + root = tmp_path / "exp" + for folder, shape in (("ctrl/rep1", (2, 8, 8)), ("drug/rep1", (4, 16, 16))): + (root / folder).mkdir(parents=True) + data = np.zeros(shape, np.uint16) + np.arange(shape[0], dtype=np.uint16)[:, None, None] + tifffile.imwrite( + root / folder / "a.tif", data, photometric="minisblack", metadata={"axes": "CYX"} + ) + nb = PreprocessingNotebook(str(root), output_folder=str(tmp_path / "out")) + nb.steps() + nb.scan_button.click() + + def lengths(): + text = _text(" ".join(cell.children[0].value for cell in nb.scan_roles_row.children)) + return re.findall(r"length (\d+)", text) + + nb.scan_viewer.select("ctrl/rep1/a.tif") + assert lengths() == ["2", "8", "8"] + nb._scan_boxes[0].value = "Z" # chosen for the CYX arrangement + nb.scan_viewer.select("drug/rep1/a.tif") + assert lengths() == ["4", "16", "16"] + assert [box.value for box in nb._scan_boxes] == ["Z", "Y", "X"] + boxes = list(nb._scan_boxes) + nb.scan_viewer.refresh() # the same image again: the row is not rebuilt + assert nb._scan_boxes == boxes + assert nb.confirmed_mapping is None # still only a proposal + + def test_a_plain_stack_gets_its_picture_once_the_user_says_what_its_dimensions_are(tmp_path): nb = scanned(tmp_path, shape=(3, 16, 16), named=False) viewer = nb.scan_viewer From 74eadf1afea19877cc4b4a9a6a72a5d41e7c0542 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 18:36:37 +0000 Subject: [PATCH 08/15] #523: keep only the log lines the technical-details panel shows _LogCapture.lines is now a deque of the latest 500 lines, the ones the panel showed; older records are dropped instead of held for the whole session. Direct appends of tracebacks keep working. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- src/morphobricks_preprocessing/notebook_ui.py | 14 +++++++++++--- tests/test_notebook_log_capture.py | 15 +++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/morphobricks_preprocessing/notebook_ui.py b/src/morphobricks_preprocessing/notebook_ui.py index 0a0473d2..f363dbf0 100644 --- a/src/morphobricks_preprocessing/notebook_ui.py +++ b/src/morphobricks_preprocessing/notebook_ui.py @@ -32,6 +32,7 @@ from __future__ import annotations import logging +from collections import deque from pathlib import Path from morphobricks_normalization.ranges import HistogramSettings @@ -99,6 +100,9 @@ from .planes import PlaneLayout from .run import Preflight, RunResult +_LOG_LINES = 500 +"""The log lines the "Technical details" panel shows and keeps.""" + __all__ = [ "EXCLUDABLE_CODES", "HISTOGRAM_RANGE_OPTIONS", @@ -470,15 +474,19 @@ def _histogram_settings_or_none(self) -> HistogramSettings | None: return None def _show_log(self) -> None: - self.details.value = "\n".join(self.log.lines[-500:]) + self.details.value = "\n".join(self.log.lines) class _LogCapture(logging.Handler): - """Collects the package's log messages for the "Technical details" panel.""" + """Collects the package's log messages for the "Technical details" panel. + + Only the latest ``_LOG_LINES`` are kept, the ones the panel shows: older ones are dropped, + not held for the whole session (#523). + """ def __init__(self): # noqa: ANN204 super().__init__(logging.DEBUG) - self.lines: list[str] = [] + self.lines: deque[str] = deque(maxlen=_LOG_LINES) self.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")) def emit(self, record: logging.LogRecord) -> None: diff --git a/tests/test_notebook_log_capture.py b/tests/test_notebook_log_capture.py index 5a500bba..066fe8bf 100644 --- a/tests/test_notebook_log_capture.py +++ b/tests/test_notebook_log_capture.py @@ -45,3 +45,18 @@ def test_a_warning_still_reaches_the_last_resort_handler_without_root_handlers(m child.warning("loud warning") assert "loud warning" in stream.getvalue() assert "quiet detail" not in stream.getvalue() + + +def test_the_capture_keeps_only_the_latest_500_lines_in_order(): + """#523: the panel shows the latest 500 lines; older ones are not held either.""" + capture = notebook_ui._LogCapture() + capture.setFormatter(logging.Formatter("%(message)s")) + with capture.attached(): + child = logging.getLogger("morphobricks_preprocessing.projection_marker") + for number in range(600): + child.debug("line %d", number) + capture.lines.append("Traceback: a direct append still works") + assert len(capture.lines) == 500 + assert list(capture.lines) == [f"line {n}" for n in range(101, 600)] + [ + "Traceback: a direct append still works" + ] From f68e4c205bfc13946e7befa580e8079d28c1a5a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 18:38:37 +0000 Subject: [PATCH 09/15] #524: a run that writes its table forgets the earlier statistics and answer The results were cleared only when the table's path changed, so a rerun to the same path kept the old statistics, tiles, plot and the 'use the planes that have the channel' answer for a new table. The clearing is now _forget_comparison(), called by a path change and by every run that wrote its table. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- .../notebook_results.py | 20 +++++++++++++++---- .../notebook_run.py | 2 ++ tests/test_notebook_extra_stain.py | 20 +++++++++++++++++++ 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/morphobricks_preprocessing/notebook_results.py b/src/morphobricks_preprocessing/notebook_results.py index 7c54b4aa..00cefee7 100644 --- a/src/morphobricks_preprocessing/notebook_results.py +++ b/src/morphobricks_preprocessing/notebook_results.py @@ -174,16 +174,28 @@ def _browse_csv(self) -> None: def _csv_changed(self) -> None: # Results of another table must not stay on screen next to the new path. - self.stats_status.value = self.stats_tiles.value = self.statistics.value = "" - self.stats_next.value = "" - ui.set_visible(self.statistics_card, False) - ui.set_visible(self.distribution_card, False) + self._forget_comparison() + + def _forget_comparison(self) -> None: + """Clear the statistics, checks and partial-presence answer of the table shown before. + + Called when another table is chosen and after a run wrote its table, even to the same + path (#524): the table is new either way. + """ + self.stats_status.value = self.stats_next.value = "" + self._hide_statistics() self.table_checks.clear() # A choice about one table's planes is never carried over to another table. The # question is hidden first, so resetting the answer calculates nothing. ui.set_visible(self.partial_box, False) self.partial_choice.value = REFUSE + def _hide_statistics(self) -> None: + """Hide the statistics, the tiles and the distributions shown before.""" + self.stats_tiles.value = self.statistics.value = "" + ui.set_visible(self.statistics_card, False) + ui.set_visible(self.distribution_card, False) + def _partial_changed(self) -> None: """Calculate again with the user's answer to the partial-presence question.""" if ui.is_visible(self.partial_box): diff --git a/src/morphobricks_preprocessing/notebook_run.py b/src/morphobricks_preprocessing/notebook_run.py index fa056cdb..57817365 100644 --- a/src/morphobricks_preprocessing/notebook_run.py +++ b/src/morphobricks_preprocessing/notebook_run.py @@ -461,6 +461,8 @@ def _finish_run(self, result: RunResult) -> None: self._show_run_checks(result.csv_path) self._show_log() if result.written: + # A new table, even at the same path: its earlier statistics and answers go (#524). + self._forget_comparison() self.csv_file.value = str(result.csv_path) self.stats_status.value = ui.status( "info", diff --git a/tests/test_notebook_extra_stain.py b/tests/test_notebook_extra_stain.py index 0cdbe151..d615ea58 100644 --- a/tests/test_notebook_extra_stain.py +++ b/tests/test_notebook_extra_stain.py @@ -91,3 +91,23 @@ def test_choosing_another_table_resets_the_answer_without_calculating(tmp_path): assert not ui.is_visible(nb.partial_box) assert nb.stats_status.value == "" assert not ui.is_visible(nb.statistics_card) + + +def test_a_rerun_to_the_same_table_forgets_the_statistics_and_the_answer(tmp_path): + """#524: the path is the same, the table is new: nothing of the earlier one stays.""" + nb, out = extra_stain_notebook(tmp_path) + assert nb.run().written + nb.level.value = "condition" + nb.show_statistics() + nb.partial_choice.value = SUBSET + assert ui.is_visible(nb.statistics_card) and "Your choice" in nb.stats_status.value + before = nb.csv_file.value + assert nb.run().written + assert nb.csv_file.value == before == str(out / "plane_histograms.csv") + assert nb.partial_choice.value == REFUSE and not ui.is_visible(nb.partial_box) + assert not ui.is_visible(nb.statistics_card) and not ui.is_visible(nb.distribution_card) + assert nb.statistics.value == nb.stats_tiles.value == "" + assert "The table the run just wrote is selected" in nb.stats_status.value + nb.show_statistics() # asked again, never answered with the earlier table's choice + assert "Partial channel presence" in nb.stats_status.value + assert ui.is_visible(nb.partial_box) and nb.partial_choice.value == REFUSE From 0daa4f1e8118a08989e62c0fae4be884a9c8125d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 18:41:22 +0000 Subject: [PATCH 10/15] #527: hide the earlier statistics when the percentiles are refused An invalid percentile list (out of 0-100, NaN, inf) returned before the old table, tiles and plot were hidden, so they stayed on screen under a choice they were not calculated with. The refusal and the missing-table branch now hide them with _hide_statistics(); the table's checks and the partial-presence answer are kept, since the table did not change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- .../notebook_results.py | 9 ++--- tests/test_notebook_statistics_refused.py | 37 +++++++++++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) create mode 100644 tests/test_notebook_statistics_refused.py diff --git a/src/morphobricks_preprocessing/notebook_results.py b/src/morphobricks_preprocessing/notebook_results.py index 00cefee7..f762644b 100644 --- a/src/morphobricks_preprocessing/notebook_results.py +++ b/src/morphobricks_preprocessing/notebook_results.py @@ -225,9 +225,7 @@ def show_statistics(self) -> None: self.stats_status.value = ui.status( "warn", "This histogram table does not exist.", [str(path)] ) - self.statistics.value = "" - ui.set_visible(self.statistics_card, False) - ui.set_visible(self.distribution_card, False) + self._hide_statistics() return try: percentiles = [float(q) for q in self.percentiles.value.replace(";", ",").split(",")] @@ -239,13 +237,12 @@ def show_statistics(self) -> None: "The percentiles cannot be read.", ["Use numbers from 0 to 100 separated by commas, for example 1, 99.8."], ) + self._hide_statistics() # the earlier ones are not of these percentiles (#527) return self._busy(self.statistics_button, "Calculating…") self._stats_wait = Wait(self.stats_status) self._stats_wait.start("Reading the histogram table") - self.stats_tiles.value = self.statistics.value = "" - ui.set_visible(self.statistics_card, False) - ui.set_visible(self.distribution_card, False) + self._hide_statistics() try: self._calculate_statistics(path, percentiles) except Exception as exc: diff --git a/tests/test_notebook_statistics_refused.py b/tests/test_notebook_statistics_refused.py new file mode 100644 index 00000000..bf643967 --- /dev/null +++ b/tests/test_notebook_statistics_refused.py @@ -0,0 +1,37 @@ +"""Refused percentiles hide the statistics calculated before (#527). + +The old table, tiles and plot were calculated with other percentiles: they must not stay on +screen under the refused choice. The widgets are driven headless. +""" + +import numpy as np +import pytest + +from test_notebook_ui import confirmed +from tiff_tree import write_data + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +from morphobricks_preprocessing import notebook_style as ui # noqa: E402 + + +def test_refused_percentiles_hide_the_earlier_statistics(tmp_path): + root = tmp_path / "exp" + rng = np.random.default_rng(0) + for rel in ["ctrl/rep1/a.tif", "ctrl/rep1/b.tif", "drug/rep1/a.tif"]: + write_data(root / rel, rng.integers(0, 200, (3, 2, 16, 16), dtype=np.uint8), axes="TCYX") + nb = confirmed(root, output_folder=str(tmp_path / "out")) + assert nb.run().written + nb.percentiles.value = "1, 99.8" + nb.statistics_button.click() + assert ui.is_visible(nb.statistics_card) and nb.stats_tiles.value + for refused in ("1,120", "nan", "1, inf", "invalid"): + nb.percentiles.value = refused + nb.statistics_button.click() + assert "The percentiles cannot be read." in nb.stats_status.value + assert not ui.is_visible(nb.statistics_card) and not ui.is_visible(nb.distribution_card) + assert nb.statistics.value == nb.stats_tiles.value == nb.stats_next.value == "" + nb.percentiles.value = "1, 99.8" + nb.statistics_button.click() + assert ui.is_visible(nb.statistics_card) and nb.statistics.value.count("ctrl") == 2 From 475c06e0d54686737ef8f6f0ed865d36d42394cd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 18:41:22 +0000 Subject: [PATCH 11/15] Changelog: quick fixes B (#395, #428, #433, #469, #481, #514, #521, #523, #524, #527) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89c36057..4b6647a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,17 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased +- **Quick fixes B (24 November 2026): channel QC, previews, notebook cards and state, results lifecycle.** + - **A channel keeps one swap partner in the channel-identity check (#395).** When two channels of a unit look alike and a third is swapped with both, the third no longer overwrites its partner's mutual pair: the first pair (sorted order) keeps it, and the other channel stays a plain `possible_channel_swap` finding, so one channel is never in two "look swapped" warnings. Warning-only, as before. `tests/test_channel_identity.py`. + - **Cached preview planes are keyed by the confirmed roles (#428).** `PreviewCache` keys held the path, fingerprint and coordinates but not the roles, so one file read as `ZCYX` and then `CZYX` showed the first reading's pixels. The key now holds the mapping's axes, roles and singleton roles (also for the discard after a rewrite). `tests/test_preview.py`. + - **A view of fewer than one channel is refused before any read (#433).** `ViewRequest(shown=...)` and `header_channels(..., shown)` raise a `ValueError` naming the value when it is not a whole number of at least 1, instead of an `IndexError`, `AttributeError` or `ZeroDivisionError` after reading. `tests/test_image_viewer.py`. + - **A plane that cannot be read is the H&E tissue-mask card's and command's refusal (#469).** The preview and the write of the card, and `tissue-mask`, now catch `PlaneReadError` (`PlaneMemoryError`, `CompressionNotBoundedError`) and `OSError`: the card replaces "Computing the preview…" with the message and hides an earlier preview; the command prints the image's refusal and exits 1, without a traceback. `tests/test_notebook_tissue_mask.py`, `tests/test_cli_tissue_mask.py`. + - **Converting a declared mask the run recorded no file of is refused (#481).** The *Convert a mask* card said "The mask is converted." with nothing written; it now shows a red card naming the mask ID and its source type, and writes nothing. The run's manifest is read at the click (the card refreshes on the description only), so no stale state disables the button. `tests/test_notebook_mask_conversion.py`. + - **An empty row fold drops its earlier rows (#514).** `RowFold.arrange` kept the last fold's rows (and their images and callbacks) in its hidden box when nothing folded; it now empties the box and its line. `tests/test_notebook_row_fold.py`. + - **The quick-scan role row follows the image's shape (#521).** An image with the same axis letters but other lengths kept the earlier image's lengths in the labels; the row is now rebuilt for another shape, and the roles chosen for those letters are kept. `tests/test_notebook_scan_axes.py`. + - **The technical-details log keeps only the lines it shows (#523).** `_LogCapture.lines` is a `deque` of the latest 500 lines instead of every record of the session. `tests/test_notebook_log_capture.py`. + - **A run that writes its table forgets the earlier statistics and answer, even at the same path (#524).** The statistics, tiles, plot, table checks and the partial-presence answer were cleared only when the table's path changed; a rerun to the same path kept them for a new table. `_forget_comparison()` now clears them on a path change and after every run that wrote its table. `tests/test_notebook_extra_stain.py`. + - **Refused percentiles hide the earlier statistics (#527).** Percentiles out of 0 to 100 (or NaN, inf) left the previous table, tiles and plot on screen; they are now hidden with the refusal (also for a missing table). The table's checks and the partial-presence answer stay: the table did not change. `tests/test_notebook_statistics_refused.py`. - **`binary_refusals` refuses unbound mask headers for the whole inventory before any read (#490, from the #502 review of #480).** It refused a file found without `bind=True` only when that file's turn came (`scan_fingerprints`), so the bound `binary` files before it were read first, the `MaskUnboundError` named one file, and an unbound file of a mask that is not `binary` passed. It now calls `refuse_unbound` on every file of the inventory first: every unbound file is named (`mask_header_unbound`) and nothing is read. Its docstring lists `MaskUnboundError` under Raises. The mask step's own inventories are found bound, so its behaviour is unchanged. `tests/test_binary_refusals_unbound.py`. - **The section-digest check is tested on runs of other shapes (#490).** #501's tests built runs from `v08` (with masks) only. `tests/test_manifest_section_digests.py` now also opens runs of `v01` (no masks), `v41` (fast mode) and `v43` (fast mode, RGB units with the header override), checks `section_digests()` against the published description's and that a wrong digest of each section is refused. Tests only; these runs already opened correctly. - **The manifest's channel coverage is checked against the published description at open (#490).** `experiment_description.channel_coverage` was checked only to be an object, so a manifest edited after the run (a status, a count or a lacking unit changed, a repeat or channel dropped or added) still opened. `RunInputs.open` now recomputes `channel_coverage(description)` from the published description whose SHA-256 it checked and refuses any other record with `ChannelCoverageMismatchError` (a `RunInputsError`, `manifest_channel_coverage_mismatch`), naming the field and each biological repeat that differs; the manifest is never repaired. Partial and unavailable channels recorded as the run wrote them open as before. No current `RunInputs` or resolver code reads the coverage; writer output and manifest version (5) unchanged. `tests/test_manifest_channel_coverage.py`. From 22dfebeba4c1b2d9e7f999c21242bdbd002d00cf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 19:25:17 +0000 Subject: [PATCH 12/15] #395: choose mutual channel swaps by strength, never by name Candidate mutual pairs are ranked by the larger of their two cross distances and taken greedily from the strongest, each channel in one pair at most. Pairs sharing a channel within PAIR_TOLERANCE (0.5) are one ambiguous_channel_swap warning naming every channel, no pair picked. The review's case now reports B and C, whatever the channel names. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- AGENTS.md | 5 +- docs/contract.md | 7 +- docs/user_guide.md | 8 +- .../channel_identity.py | 161 ++++++++++++++---- .../channel_identity_model.py | 15 +- .../channel_identity_text.py | 59 ++++++- .../notebook_channel_identity.py | 12 +- tests/test_channel_identity.py | 23 --- tests/test_channel_identity_pairs.py | 98 +++++++++++ tests/test_notebook_channel_identity.py | 11 ++ 10 files changed, 331 insertions(+), 68 deletions(-) create mode 100644 tests/test_channel_identity_pairs.py diff --git a/AGENTS.md b/AGENTS.md index 442ed30f..6ab13004 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -161,8 +161,9 @@ src/morphobricks_preprocessing/ the notebook's plots, intensity_text for the CLI channel_identity.py channel-identity check (contract §14.1): per unit and channel a scale-free log signature from the same summaries, within-condition robust - reference, channel_unlike_others / possible_channel_swap (warnings, never - blocking); channel_identity_model.py ChannelIdentitySettings (manifest key + reference, channel_unlike_others / possible_channel_swap / + ambiguous_channel_swap (warnings, never blocking; mutual pairs chosen by + strength, never by name, #395); channel_identity_model.py ChannelIdentitySettings (manifest key channel_identity) and the results; channel_identity_text.py their words; notebook_channel_identity.py its notebook view and plot validation.py ValidationIssue (severity, code, message, paths, action), error()/warning() builders diff --git a/docs/contract.md b/docs/contract.md index 13d6b719..60b5cbf6 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -198,7 +198,7 @@ method is an offset and a scale, `(pixels − offset) / scale`. | Severity | Situations | Effect | |---|---|---| | Error | Experiment design not confirmed (`design_not_confirmed`) or a repeat group holding two folders of one condition (`repeat_group_conflict`), when a design is used (§12); image type RGB for images that are not three channels of an integer type (`rgb_not_possible`, §13); mixed dtypes; images with different numbers of channels (`different_channel_counts`, §2) or different channel names at the same channel number (`channel_names_differ`, §2); unreadable TIFF (header or pixel data) or OME-Zarr folder in a leaf folder that is not excluded; OME-Zarr images without the `zarr` extra; OME-Zarr images whose declared axes do not fit the experiment's roles or that the confirmed roles contradict (`ome_zarr_axes_mismatch`, §2); OME-Zarr images that do not name their axes, and every OME-NGFF 0.1 or 0.2 store (`unreadable_ome_zarr`, §2); every image excluded; more than one image series in a file; unsupported sample format or axis; an image with more than one depth slice (`z_stack_not_supported`, §2; MorphoBricks v1 analyses 2-D planes); missing/duplicate X or Y, duplicate roles, unassigned non-singleton axis, inconsistent mapping; an image whose confirmed roles swap Y and X, contradict its header or put X before Y (`axes_yx_swapped`, `axes_contradict_header`, `axes_x_before_y`, §2); plane that cannot be read within the memory limit, not even in blocks (for example a plane stored compressed in one piece); a plane over the memory limit stored with a TIFF compression whose decoding memory is not measured, which is never read in blocks (`compression_not_bounded`, §9.1 *Codecs*, #356); folder named `single` in another case, or beside other folders (§1); folders of one level differing only in case, anywhere in the experiment (`case_conflict`); folder or image names with outer whitespace or reading as a missing value (`invalid_name`, §1); images in one leaf folder with the same position identifier (§1); links that leave the experiment or masks folder, loop, or reach one file twice (`link_outside_folder`, `link_loop`, `linked_twice`, §1); a mount point below the experiment or masks folder (`mounted_folder`, §1); folder below the technical-repeat level; images in a folder that also holds subfolders (`tiff_outside_leaf`, §1); output folder inside the experiment or inside the masks folder (`output_inside_masks`, §15); experiment or named-axis copies inside the masks folder (`experiment_inside_masks`, `copies_inside_masks`, §15); images named as masks of other images (`image_named_as_mask`, §1); no usable planes; no axis roles given or recorded (`axes_not_confirmed`, §9.2); another run holding the output folder's lock (`output_locked`, §9.2); a copy tree whose conversion record cannot be read (`conversion_record_unreadable`, §17), or whose copies changed, went missing or were added since the conversion (`copy_changed_after_conversion`, §17; owner decision of 2 November 2026, PP-12: the bricks would refuse the run); an image that changed or went missing while the run checked or read it (`source_changed_during_run`, §9.4; no scientific outputs are published and sources are untouched; the discovery report is written); a mask that changed while its header was read (`mask_changed_during_check`) or after it, before the run's commit (`mask_changed_during_run`, §9.4, issue #160; the same); a recorded `experiment_design.csv` that cannot be read (`design_unreadable`); a `calibration.csv` that cannot be read (`calibration_unreadable`) or that states sizes for a target that is neither a folder nor an image of the experiment (`calibration_target_not_found`, §9.3); no experiment folder given or recorded (`experiment_not_recorded`, §9.2); when masks are given, a masks folder missing or inside the experiment, mask names differing only in case, two masks of one type for an image, a mask whose name could belong to two images or types, or a mask that is unreadable, has axes other than Y, X and named or stated Z/T (`mask_not_2d`), has stated axes that do not fit it or contradict the axes its metadata names (`invalid_mask_axes`, `mask_axes_contradict_header`), is stated `YX` (`shared_mask_not_supported`, §15), is stored with X before Y (its header's or its stated axes; refused by `check` and `run` too, never recorded with empty axes) or with its image's Y and X sizes swapped (`mask_layout`; never transposed), is of another size than its image (in `run`, its image's Y and X under the confirmed roles; not reported for an image with an axis error), is not of integers or booleans, has other depth slices or time points than the image's other masks or, in `run`, than the image (§15) | Processing is blocked | -| Warning | Images whose metadata does not name their axes, read with the confirmed roles (`axes_not_named`, §2); images or masks with other names, hard links (`hard_linked_file`, §1); in a tree of named-axis copies, sources changed or gone since the conversion (`conversion_source_changed`, §17); folders named like a masks folder holding images named as masks (`mask_folder_in_experiment`, §1); intensity checks of the written table (`image_intensity_outlier`, `repeat_intensity_shift`, `saturated_image`, `no_intensity_spread`, `channel_without_finite_pixels`, §14), reported apart from the run's issues; channels of a unit that do not look like the same channels of the other units (`channel_unlike_others`, `possible_channel_swap`, §14.1), reported the same way; files that are not images; empty folders; images excluded by the user, or excluded paths that match no image; non-finite pixels; different image widths or heights; different numbers of depth slices, time points or other planes; physical pixel sizes that differ or are known for only some images; a stated pixel size that differs from the header (`calibration_differs_from_header`, §9.3; the stated size is used); unbalanced numbers of images; biological repeats missing from some conditions (§11); planes without finite pixels while others remain; channels whose central intensity range covers too few histogram bins (`narrow_histogram_range`, §4); planes over the memory limit that are read in blocks; images without a mask of a type other images have, masks matching no image, masks of excluded images, files outside the mask-type folders (§15) | Processing continues; the item is reported | +| Warning | Images whose metadata does not name their axes, read with the confirmed roles (`axes_not_named`, §2); images or masks with other names, hard links (`hard_linked_file`, §1); in a tree of named-axis copies, sources changed or gone since the conversion (`conversion_source_changed`, §17); folders named like a masks folder holding images named as masks (`mask_folder_in_experiment`, §1); intensity checks of the written table (`image_intensity_outlier`, `repeat_intensity_shift`, `saturated_image`, `no_intensity_spread`, `channel_without_finite_pixels`, §14), reported apart from the run's issues; channels of a unit that do not look like the same channels of the other units (`channel_unlike_others`, `possible_channel_swap`, `ambiguous_channel_swap`, §14.1), reported the same way; files that are not images; empty folders; images excluded by the user, or excluded paths that match no image; non-finite pixels; different image widths or heights; different numbers of depth slices, time points or other planes; physical pixel sizes that differ or are known for only some images; a stated pixel size that differs from the header (`calibration_differs_from_header`, §9.3; the stated size is used); unbalanced numbers of images; biological repeats missing from some conditions (§11); planes without finite pixels while others remain; channels whose central intensity range covers too few histogram bins (`narrow_histogram_range`, §4); planes over the memory limit that are read in blocks; images without a mask of a type other images have, masks matching no image, masks of excluded images, files outside the mask-type folders (§15) | Processing continues; the item is reported | Every message states what happened in plain language, lists the affected paths, and suggests an action. Technical details go to the diagnostic log. The command line's log @@ -926,12 +926,13 @@ same image summaries (design `channel-identity-check-2026-11-21`, owner answers | Reference | For unit `u` and channel `c`: the per-component median and MAD × 1.4826 (at least `mad_floor`) of `c`'s signatures in the other units of `u`'s condition, never `u` itself. A treatment effect is therefore not reported when the condition has at least `min_reference` other units with the channel. With fewer, the other units of the experiment are the reference and the finding says "compared across conditions" (a treatment effect may then be reported); with fewer still, `c` of `u` is not checked (listed, not a warning). Units are compared only with units of the same pixel type; different types are named as not compared. **Limit:** a swap made in every unit of a condition is not found, since it is what that condition looks like. | | Distance | `d(u, c -> c')`: root mean square of the robust z-scores of `u`'s `c` signature against the reference of `c'`. | | Reported | A unit channel is reported when `d(u, c -> c) > outlier_limit` and at least one component is more than `outlier_limit` robust deviations and at least `min_log_difference` from the reference (the components named as off: level, brightness, contrast). Only unit channels compared with a reference count as checked; with none, the summary says that no channel could be checked. | -| `possible_channel_swap` | Either a mutual pair: `u`'s `c` is reported, its nearest other channel `c'` is one of `u`'s channels, `partner_ratio × d(u, c -> c') < d(u, c -> c)` and `partner_ratio × d(u, c' -> c) < d(u, c' -> c')`, both within `outlier_limit` (`u`'s `c'` reported or not): one warning, "`c` and `c'` look swapped", with both channels' distances, naming the unit once. Or a clear look-alike of another channel `c'` of the unit: `d(u, c -> c') <= swap_limit` and `swap_ratio × d(u, c -> c') < d(u, c -> c)`. | +| `possible_channel_swap` | Either a mutual pair: `u`'s `c` is reported, its nearest other channel `c'` is one of `u`'s channels, `partner_ratio × d(u, c -> c') < d(u, c -> c)` and `partner_ratio × d(u, c' -> c) < d(u, c' -> c')`, both within `outlier_limit` (`u`'s `c'` reported or not): a candidate pair, whose strength is the larger of `d(u, c -> c')` and `d(u, c' -> c)` (smaller is stronger). The pairs are chosen greedily from the strongest, and a channel is in one pair at most (#395): one warning per chosen pair, "`c` and `c'` look swapped", with both channels' distances, naming the unit once. Or a clear look-alike of another channel `c'` of the unit, not in a chosen pair: `d(u, c -> c') <= swap_limit` and `swap_ratio × d(u, c -> c') < d(u, c -> c)` ("does not look like `c` but like `c'`"). Channel names and the order of the images never decide which pair is chosen. | +| `ambiguous_channel_swap` | When the strongest remaining candidate pair shares a channel with other remaining pairs of the unit (directly or through each other) whose strengths are within `PAIR_TOLERANCE` (0.5, a constant, not a recorded limit) of it, none of them is chosen: one warning naming every channel of the group, each with its own distance and its distances to the channels it could be swapped with, "look swapped in more than one way … no pair is named"; those channels are paired with nothing else. Check every channel named. | | `channel_unlike_others` | Every other reported unit channel: names the unit (`condition/biological repeat/technical repeat`), the channel, the components off and the distances; "Nearest channel: `c'`" when another channel's reference is nearer than its own, or "It looks like `c'`, a channel this unit does not have" for a clear look-alike of a channel the unit lacks (never called a swap). | | Limits | `ChannelIdentitySettings`: `outlier_limit` 3.5, `min_reference` 3, `mad_floor` 0.2, `min_log_difference` 0.6 (natural-log units), `swap_limit` 1.0, `swap_ratio` 3.0, `partner_ratio` 2.0, chosen with a simulation (2 conditions × 4 units × 3 channels, between-unit variation of 10 % and 20 %; PR #364). With very noisy data (units differing by about 30 % per channel) false warnings become frequent: in that simulation 171 of 300 runs without any swap give a warning and 59 a false swap; read the warnings as prompts to look, never as verdicts. The run uses the defaults and records them in the manifest (`channel_identity`, §9, beside `intensity_checks`); other limits are applied by calling `check_channel_identity(result.intensity.summaries, settings)`, which recomputes nothing. | | Run | `RunResult.channel_identity` (`ChannelIdentityReport`: signatures, findings, warnings, not checked, the number compared, pixel types and offsets) for a written table, None otherwise; its warnings are in the run report beside the intensity warnings and kept apart from `RunResult.issues`. | | Command line | `run` prints them after the intensity checks, grouped by kind with what to do, then what was not checked. | -| Notebook | Under the intensity checks' plots, **Do the channels look like themselves?**: a status line (an information status when no channel could be checked) with the limits, the findings with what to do, what was not checked, and one plot of brightness against contrast (log scale) with one point per unit and channel, coloured and shaped by channel tag; a flagged point is circled and labelled with its unit; a possible swap has a dashed arrow from the centre of the reference the check used for that unit and channel to the point. When nothing could be checked, the section stays and shows the status and why each unit channel was not checked, without a plot. Nothing is written. | +| Notebook | Under the intensity checks' plots, **Do the channels look like themselves?**: a status line (an information status when no channel could be checked) with the limits, the findings with what to do, what was not checked, and one plot of brightness against contrast (log scale) with one point per unit and channel, coloured and shaped by channel tag; a flagged point is circled and labelled with its unit; a possible swap has a dashed arrow from the centre of the reference the check used for that unit and channel to the point; a point of an ambiguous swap is labelled with every channel it could be swapped with, without an arrow. When nothing could be checked, the section stays and shows the status and why each unit channel was not checked, without a plot. Nothing is written. | ## 15. Masks (optional) diff --git a/docs/user_guide.md b/docs/user_guide.md index f915e4ba..82561629 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -720,8 +720,9 @@ the channel, the image or biological repeat and the values compared, and what to per kind; it draws no plots (the notebook does). Then it prints the channel check: each imaging unit's channels compared with the same channels of the other units of its condition (a treatment effect is not reported when the condition has at least 3 other units), with -`channel_unlike_others` and `possible_channel_swap` warnings (for example "channels DAPI and -GFP look swapped") and the channels it could not check; the notebook draws them under +`channel_unlike_others`, `possible_channel_swap` (for example "channels DAPI and GFP look +swapped") and `ambiguous_channel_swap` warnings (channels that look swapped in more than one +way the check cannot tell apart: it names them all and no pair) and the channels it could not check; the notebook draws them under **Do the channels look like themselves?**. A swap made in every unit of a condition is not found. Warnings only: nothing is changed or blocked. @@ -1460,7 +1461,8 @@ continues. | `saturated_image` | Warning (intensity check) | More than the limit (default 1 %) of an image's pixels in a channel are at the largest value of its pixel type, so their true intensity is lost. Check the exposure, gain or laser power. | | `no_intensity_spread` | Warning (intensity check) | An image's channel has the same 1st and 99.8th percentile (empty or blank), so it cannot be normalised on its own. Check the channel, or exclude the image. | | `channel_unlike_others` | Warning (channel check) | One imaging unit's channel does not look like the same channel in the other units of its condition: its level, brightness or contrast differ by about 1.8 times or more and by much more than the units usually differ. The message names the nearest other channel, or says it looks like a channel this unit does not have (for example a fourth channel only other repeats have). Look at that unit's images in that channel: check its channel tag and how the images were exported, and whether the stain, exposure or acquisition differed. Nothing is changed or blocked. With very noisy data (units differing by about 30 % per channel) false warnings are frequent (171 of 300 simulated runs without a swap warned); floats converted from whole numbers with medians near zero can warn falsely, and 16-bit and 0-1 float images agree only above the integer floor (a high percentile above about 333 counts). | -| `possible_channel_swap` | Warning (channel check) | Two channels of one imaging unit look like each other's channel in the other units (for example "DAPI and GFP look swapped"), or one channel clearly looks like another channel of the same unit: its channel tags may be in the wrong order. Check the unit's channels against how its images were acquired; if they are swapped, correct them in the experiment description and run again. Nothing is changed or blocked. A swap made in every unit of a condition is not found: the check compares each unit with the other units of its condition. | +| `possible_channel_swap` | Warning (channel check) | Two channels of one imaging unit look like each other's channel in the other units (for example "DAPI and GFP look swapped"), or one channel clearly looks like another channel of the same unit: its channel tags may be in the wrong order. Check the unit's channels against how its images were acquired; if they are swapped, correct them in the experiment description and run again. Nothing is changed or blocked. A swap made in every unit of a condition is not found: the check compares each unit with the other units of its condition. When a channel could be swapped with two others, the pair whose two channels look most like each other is named, and the third channel gets its own "does not look like ... but like ..." warning; channel names never decide. | +| `ambiguous_channel_swap` | Warning (channel check) | Channels of one imaging unit look swapped in more than one way that the check cannot tell apart (for example "channels A, B and C look swapped in more than one way": its B looks like A or C), so no pair is named. Check the channel tags of every channel named against how the images were acquired, and correct the unit's channels in the experiment description only once you know which are swapped; run again. Nothing is changed or blocked. | | `channel_without_finite_pixels` | Warning (intensity check) | An image's channel has no finite pixels (every value NaN or infinite), so its intensities were not checked and it cannot be normalised from its own pixels. Exclude the image, or fix the channel in the source data and run again. | | `channel_names_differ` | Error | Channel names differ between images at the same channel number, so different stains would be pooled as one channel. Spaces at the start or end of a name are ignored (and noted in the manifest); otherwise names must match exactly, and names that differ only in inner spaces are quoted and reported as such. Check the channel order; export the images again with the same channel order and names, or exclude the images whose channels differ. | | `non_finite_pixels` | Warning | NaN or infinite pixels are left out of the histograms and counted. | diff --git a/src/morphobricks_preprocessing/channel_identity.py b/src/morphobricks_preprocessing/channel_identity.py index a304c52a..16434621 100644 --- a/src/morphobricks_preprocessing/channel_identity.py +++ b/src/morphobricks_preprocessing/channel_identity.py @@ -30,7 +30,9 @@ mean square of the robust z-scores) to its own reference is over ``outlier_limit`` and one component differs by at least ``min_log_difference``. ``possible_channel_swap`` when it clearly looks like another channel of the same unit (within ``swap_limit`` and ``swap_ratio`` times -closer than to its own reference) or the two channels look like each other (one warning); +closer than to its own reference) or the two channels look like each other (one warning; +mutual pairs are chosen by strength, a channel in one pair at most, and pairs sharing a channel +that cannot be told apart are one ``ambiguous_channel_swap`` naming every channel); otherwise ``channel_unlike_others``, naming the nearest channel, or saying that it looks like a channel the unit does not have. Units of different pixel types are never compared, and nothing is guessed or filled in. @@ -47,10 +49,12 @@ from morphobricks_normalization.summaries import ImageSummary from .channel_identity_model import ( + AMBIGUOUS_CHANNEL_SWAP, CHANNEL_IDENTITY_CODES, CHANNEL_UNLIKE_OTHERS, COMPONENTS, KEY, + PAIR_TOLERANCE, POSSIBLE_CHANNEL_SWAP, ChannelFinding, ChannelIdentityReport, @@ -377,56 +381,151 @@ def _leans(place: _Place, channel: str, limit: float, ratio: float) -> bool: return found is not None and found[0] * ratio < place.distance and found[0] <= limit +class _Pair(NamedTuple): + """A candidate mutual swap of two channels of one unit, and how strongly it is supported.""" + + strength: float + """The larger of the two cross distances ``d(u, a -> b)`` and ``d(u, b -> a)``.""" + unit: Unit + channels: tuple[str, str] + """Sorted, so the pair is the same whichever channel found it.""" + + +def _pairs( + places: Mapping[tuple[Unit, str], _Place], + findings: Mapping[tuple[Unit, str], ChannelFinding], + settings: ChannelIdentitySettings, +) -> list[_Pair]: + """Return every candidate mutual pair, strongest first. + + A reported channel whose nearest channel ``c'`` is one of its unit's (and checked) is a + candidate with ``c'`` when each leans on the other (:func:`_leans`, ``partner_ratio``, + within ``outlier_limit``). The order (strength, then unit and channels) only makes the + iteration repeatable: :func:`_choose` gives the same answer for any order of equal ones. + """ + limit, ratio = settings.outlier_limit, settings.partner_ratio + pairs = set() + for key, found in findings.items(): + other = (found.unit, found.nearest) + partner = places.get(other) + if found.nearest_absent or partner is None: + continue + if _leans(places[key], found.nearest, limit, ratio) and _leans( + partner, found.channel, limit, ratio + ): + there = places[key].others[found.nearest][0] + back = partner.others[found.channel][0] + channels = tuple(sorted((found.channel, found.nearest))) + pairs.add(_Pair(max(there, back), found.unit, channels)) + return sorted(pairs) + + +def _choose(pairs: list[_Pair]) -> tuple[list[_Pair], list[list[_Pair]]]: + """Choose the mutual pairs by strength; return the pairs kept and the ambiguous groups. + + Greedy from the strongest pair (smallest strength): a channel is in one pair at most. When + a remaining pair sharing a channel with the strongest one (directly or through each other) + is within :data:`PAIR_TOLERANCE` of its strength, none of them is chosen: they form one + ambiguous group, and its channels are not paired with anything else. Channel names and + input order never decide (#395). + """ + kept, groups, used = [], [], set() + remaining = list(pairs) + while remaining: + remaining = [p for p in remaining if not used & {(p.unit, c) for c in p.channels}] + if not remaining: + break + first = remaining[0] + close = [ + p + for p in remaining + if p.unit == first.unit and p.strength <= first.strength + PAIR_TOLERANCE + ] + group, channels = [first], set(first.channels) + grown = True + while grown: + grown = False + for pair in close: + if pair not in group and channels & set(pair.channels): + group.append(pair) + channels.update(pair.channels) + grown = True + if len(group) == 1: + kept.append(first) + else: + groups.append(sorted(group, key=lambda p: p.channels)) + used.update((first.unit, c) for c in channels) + return kept, groups + + def _findings( places: Mapping[tuple[Unit, str], _Place], settings: ChannelIdentitySettings ) -> list[ChannelFinding]: """Return the findings, with the swaps made, sorted by unit and channel. - A reported channel whose nearest channel ``c'`` is one of its unit's makes a mutual swap - when it is ``partner_ratio`` times nearer ``c'`` than its own reference and the unit's - ``c'`` is ``partner_ratio`` times nearer this channel than its own (both within - ``outlier_limit``), the unit's ``c'`` reported or not; - otherwise a channel that clearly looks like another channel of its unit is a swap. + A reported channel whose nearest channel ``c'`` is one of its unit's makes a candidate + mutual swap when it is ``partner_ratio`` times nearer ``c'`` than its own reference and the + unit's ``c'`` is ``partner_ratio`` times nearer this channel than its own (both within + ``outlier_limit``), the unit's ``c'`` reported or not. The pairs are chosen by strength + (:func:`_choose`): each channel is in one pair at most, and pairs that share a channel and + cannot be told apart are one ``ambiguous_channel_swap`` naming all their channels. + Otherwise a channel that clearly looks like another channel of its unit is a swap. """ - limit = settings.outlier_limit findings = {key: f for key, place in places.items() if (f := _finding(place, settings))} - for key in list(findings): - found = findings[key] - other = (found.unit, found.nearest) - partner = places.get(other) - if found.mutual or found.nearest_absent or partner is None: - continue - if (taken := findings.get(other)) is not None and taken.mutual: - # A channel has one swap partner: the first pair (sorted order) keeps it, and this - # channel stays a plain swap finding (#395). - continue - ratio = settings.partner_ratio - if not _leans(places[key], found.nearest, limit, ratio): - continue - if not _leans(partner, found.channel, limit, ratio): - continue - pair = findings.get(other) or _finding(partner, settings, force=True) - distance, across = partner.others[found.channel] - pair = replace(pair, nearest=found.channel, nearest_distance=distance, nearest_absent=False) - across = across or pair.across_conditions or found.across_conditions - across = across or places[key].others[found.nearest][1] - for place, item in ((key, found), (other, pair)): - findings[place] = replace( - item, code=POSSIBLE_CHANNEL_SWAP, clear=True, mutual=True, across_conditions=across + kept, groups = _choose(_pairs(places, findings, settings)) + for pair in kept: + a, b = ((pair.unit, c) for c in pair.channels) + items = { + key: findings.get(key) or _finding(places[key], settings, force=True) for key in (a, b) + } + across = any(items[key].across_conditions for key in (a, b)) + across = across or any(places[key].others[other[1]][1] for key, other in ((a, b), (b, a))) + for key, other in ((a, b), (b, a)): + findings[key] = replace( + items[key], + code=POSSIBLE_CHANNEL_SWAP, + nearest=other[1], + nearest_distance=places[key].others[other[1]][0], + nearest_absent=False, + clear=True, + mutual=True, + across_conditions=across, + ) + for group in groups: + unit = group[0].unit + partners: dict[str, set[str]] = {} + for pair in group: + a, b = pair.channels + partners.setdefault(a, set()).add(b) + partners.setdefault(b, set()).add(a) + for channel, others in partners.items(): + key = (unit, channel) + item = findings.get(key) or _finding(places[key], settings, force=True) + alternatives = tuple((c, places[key].others[c][0]) for c in sorted(others)) + across = item.across_conditions or any(places[key].others[c][1] for c in others) + findings[key] = replace( + item, + code=AMBIGUOUS_CHANNEL_SWAP, + alternatives=alternatives, + across_conditions=across, ) for key, found in findings.items(): - if found.clear and not found.nearest_absent and not found.mutual: + if found.code != CHANNEL_UNLIKE_OTHERS or found.mutual: + continue + if found.clear and not found.nearest_absent: findings[key] = replace(found, code=POSSIBLE_CHANNEL_SWAP) return [findings[key] for key in sorted(findings)] __all__ = [ + "AMBIGUOUS_CHANNEL_SWAP", "CHANNEL_IDENTITY_CODES", "CHANNEL_UNLIKE_OTHERS", "COMPONENTS", "KEY", "MAD_SCALE", "OFFSET_FRACTION", + "PAIR_TOLERANCE", "POSSIBLE_CHANNEL_SWAP", "ChannelFinding", "ChannelIdentityReport", diff --git a/src/morphobricks_preprocessing/channel_identity_model.py b/src/morphobricks_preprocessing/channel_identity_model.py index 1d617e7a..49e8bf72 100644 --- a/src/morphobricks_preprocessing/channel_identity_model.py +++ b/src/morphobricks_preprocessing/channel_identity_model.py @@ -18,7 +18,13 @@ CHANNEL_UNLIKE_OTHERS = "channel_unlike_others" POSSIBLE_CHANNEL_SWAP = "possible_channel_swap" -CHANNEL_IDENTITY_CODES = (POSSIBLE_CHANNEL_SWAP, CHANNEL_UNLIKE_OTHERS) +AMBIGUOUS_CHANNEL_SWAP = "ambiguous_channel_swap" +CHANNEL_IDENTITY_CODES = (POSSIBLE_CHANNEL_SWAP, AMBIGUOUS_CHANNEL_SWAP, CHANNEL_UNLIKE_OTHERS) +PAIR_TOLERANCE = 0.5 +"""Two mutual pairs sharing a channel whose strengths (the larger of a pair's two cross +distances) differ by at most this much cannot be told apart: the channels are an ambiguous +swap, never one pair picked (#395). Half a robust deviation (root mean square), below the +spread of the references themselves (``mad_floor``, ``swap_limit``).""" KEY = "channel_identity" """The manifest key of the limits, beside ``intensity_checks``.""" COMPONENTS = ("level", "bright", "spread") @@ -180,7 +186,7 @@ class ChannelFinding: Attributes ---------- code - ``possible_channel_swap`` or ``channel_unlike_others``. + ``possible_channel_swap``, ``ambiguous_channel_swap`` or ``channel_unlike_others``. unit, channel Where. distance @@ -201,6 +207,10 @@ class ChannelFinding: across_conditions True when a reference used was taken across conditions (too few units in the condition). + alternatives + For an ``ambiguous_channel_swap``: ``(channel, distance)`` for each other channel of + the unit it could be swapped with, the distance being to that channel's reference, + sorted by channel; empty otherwise. """ code: str @@ -215,6 +225,7 @@ class ChannelFinding: clear: bool = False mutual: bool = False across_conditions: bool = False + alternatives: tuple[tuple[str, float], ...] = () @property def resembles(self) -> str | None: diff --git a/src/morphobricks_preprocessing/channel_identity_text.py b/src/morphobricks_preprocessing/channel_identity_text.py index 4e7b112a..a6da4645 100644 --- a/src/morphobricks_preprocessing/channel_identity_text.py +++ b/src/morphobricks_preprocessing/channel_identity_text.py @@ -9,8 +9,10 @@ from collections.abc import Sequence from .channel_identity_model import ( + AMBIGUOUS_CHANNEL_SWAP, CHANNEL_IDENTITY_CODES, CHANNEL_UNLIKE_OTHERS, + PAIR_TOLERANCE, POSSIBLE_CHANNEL_SWAP, ChannelFinding, ChannelIdentityReport, @@ -25,6 +27,12 @@ "acquired. If they are swapped, correct the unit's channels in the experiment " "description and run again. Nothing was changed or blocked." ), + AMBIGUOUS_CHANNEL_SWAP: ( + "Check the channel tags of every channel named for this unit against how its images " + "were acquired: they look swapped in more than one way the check cannot tell apart, so " + "it names no pair. Correct the unit's channels in the experiment description only once " + "the acquisition shows which are swapped, and run again. Nothing was changed or blocked." + ), CHANNEL_UNLIKE_OTHERS: ( "Look at this unit's images in this channel: check its channel tag and how the images " "were exported, and whether the stain, exposure or acquisition differed from the other " @@ -33,6 +41,7 @@ } TITLES = { POSSIBLE_CHANNEL_SWAP: "Channels that look swapped with another channel of their unit", + AMBIGUOUS_CHANNEL_SWAP: "Channels that look swapped in more than one way", CHANNEL_UNLIKE_OTHERS: "Channels unlike the same channel of the other units", } @@ -40,14 +49,21 @@ def finding_issues( findings: Sequence[ChannelFinding], settings: ChannelIdentitySettings ) -> list[ValidationIssue]: - """Return the findings as warnings; a mutual swap is one warning, naming its unit once.""" + """Return the findings as warnings, naming the unit once per warning. + + A mutual swap is one warning, and so is each ambiguous group (every channel of it). + """ by_place = {(f.unit, f.channel): f for f in findings} issues, done = [], set() for found in findings: if (found.unit, found.channel) in done: continue partner = by_place.get((found.unit, found.nearest)) if found.mutual else None - if partner is not None: + if found.code == AMBIGUOUS_CHANNEL_SWAP: + group = _group(found, by_place) + done.update((f.unit, f.channel) for f in group) + message = _ambiguous_message(group) + elif partner is not None: done.add((partner.unit, partner.channel)) message = _swap_message(found, partner) else: @@ -56,6 +72,45 @@ def finding_issues( return issues +def _group(found: ChannelFinding, by_place: dict[tuple, ChannelFinding]) -> list[ChannelFinding]: + """Return the ambiguous findings of ``found``'s unit linked to it, sorted by channel.""" + group, todo = {}, [found] + while todo: + item = todo.pop() + if item.channel in group: + continue + group[item.channel] = item + for channel, _ in item.alternatives: + other = by_place.get((item.unit, channel)) + if other is not None and other.code == AMBIGUOUS_CHANNEL_SWAP: + todo.append(other) + return [group[channel] for channel in sorted(group)] + + +def _names(channels: Sequence[str]) -> str: + """Return the channels as words: ``A``, ``A and B`` or ``A, B and C``.""" + return channels[0] if len(channels) == 1 else f"{', '.join(channels[:-1])} and {channels[-1]}" + + +def _ambiguous_message(group: Sequence[ChannelFinding]) -> str: + """Word an ambiguous swap: every channel, its own distance and those to its alternatives.""" + first = group[0] + others = _others(any(f.across_conditions for f in group)) + parts = [] + for found in group: + near = ", ".join(f"{d:.1f} to {c}" for c, d in found.alternatives) + alike = " or ".join(c for c, _ in found.alternatives) + parts.append( + f"its {found.channel} looks like {alike} (distance {found.distance:.1f} to " + f"{found.channel}, {near})" + ) + return ( + f"In unit {first.unit.label}, channels {_names([f.channel for f in group])} look " + f"swapped in more than one way: compared with {others}, {'; '.join(parts)}. The " + f"possible pairs are within {PAIR_TOLERANCE:g} of each other, so no pair is named." + ) + + def _others(across: bool) -> str: """Return what the unit was compared with.""" if across: diff --git a/src/morphobricks_preprocessing/notebook_channel_identity.py b/src/morphobricks_preprocessing/notebook_channel_identity.py index e34a31c0..ed452daf 100644 --- a/src/morphobricks_preprocessing/notebook_channel_identity.py +++ b/src/morphobricks_preprocessing/notebook_channel_identity.py @@ -26,6 +26,7 @@ from . import notebook_style as ui from .channel_identity import check_channel_identity from .channel_identity_model import ( + AMBIGUOUS_CHANNEL_SWAP, CHANNEL_IDENTITY_CODES, POSSIBLE_CHANNEL_SWAP, ChannelFinding, @@ -45,7 +46,11 @@ COLOURS = ("#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6") MARKERS = ("o", "s", "^", "D", "v", "P", "X") INK = "#222222" -_CHECK_WORDS = {POSSIBLE_CHANNEL_SWAP: "Possible swap", "channel_unlike_others": "Unlike others"} +_CHECK_WORDS = { + POSSIBLE_CHANNEL_SWAP: "Possible swap", + AMBIGUOUS_CHANNEL_SWAP: "Swap, pair unclear", + "channel_unlike_others": "Unlike others", +} class ChannelIdentityView: @@ -231,7 +236,10 @@ def _draw_finding( axes.scatter(*point, s=70, color=look[0], marker=look[1], edgecolors=INK, zorder=5) axes.scatter(*point, s=320, facecolors="none", edgecolors=INK, linewidths=1.6, zorder=5) text = f"{signature.unit.label}\ntagged {signature.channel}" - if found.resembles is not None: + if found.code == AMBIGUOUS_CHANNEL_SWAP: + # No pair is named: every channel it could be swapped with (#395). + text += f", looks like {' or '.join(c for c, _ in found.alternatives)}" + elif found.resembles is not None: text += f", looks like {found.resembles}" axes.annotate( text, diff --git a/tests/test_channel_identity.py b/tests/test_channel_identity.py index 8186658f..09693469 100644 --- a/tests/test_channel_identity.py +++ b/tests/test_channel_identity.py @@ -110,29 +110,6 @@ def test_two_swapped_channels_give_one_mutual_swap(): assert "swapped" in issue.message and "nearest" not in issue.message.casefold() -def test_a_channel_keeps_one_swap_partner(): - """#395: A and C look alike, and B is swapped with both in one unit: one pair, not two.""" - ref = {"A": (800.0, 100.0, 4000.0), "B": (4000.0, 500.0, 20000.0), "C": (800.0, 100.0, 4000.0)} - swapped = {"A": ref["B"], "B": ref["A"], "C": ref["B"]} - units = [Unit("ctrl", "rep1", f"t{i}") for i in range(5)] - summaries = [ - summary(unit, i, swapped if unit.technical_repeat == "t0" else ref) - for unit in units - for i in range(2) - ] - report = check_channel_identity(summaries) - found = {f.channel: (f.code, f.nearest, f.mutual) for f in report.findings} - assert found == { - "A": (POSSIBLE_CHANNEL_SWAP, "B", True), - "B": (POSSIBLE_CHANNEL_SWAP, "A", True), - "C": (POSSIBLE_CHANNEL_SWAP, "B", False), - } - messages = [issue.message for issue in report.validation_issues()] - assert sum("look swapped" in m for m in messages) == 1 - assert "channels A and B look swapped" in messages[0] - assert check_channel_identity(summaries[::-1]).findings == report.findings - - def test_a_dim_channel_is_unlike_the_others_but_no_swap(): def dim(unit, stains): if unit == SWAPPED: diff --git a/tests/test_channel_identity_pairs.py b/tests/test_channel_identity_pairs.py new file mode 100644 index 00000000..eebd41c8 --- /dev/null +++ b/tests/test_channel_identity_pairs.py @@ -0,0 +1,98 @@ +"""Mutual channel swaps chosen by strength, never by name (contract §14.1, #395).""" + +import itertools + +import pytest + +from morphobricks_preprocessing.channel_identity import ( + AMBIGUOUS_CHANNEL_SWAP, + POSSIBLE_CHANNEL_SWAP, + Unit, + channel_identity_text, + check_channel_identity, +) +from test_channel_identity import summary + + +def one_unit_off(ref, shown): + """Two images in each of five units of ``ref``, except ``t0``, which shows ``shown``.""" + units = [Unit("ctrl", "rep1", f"t{i}") for i in range(5)] + return [ + summary(unit, i, shown if unit.technical_repeat == "t0" else ref) + for unit in units + for i in range(2) + ] + + +# #395, the review's case: "dim" shows "bright"'s content, "bright" shows exactly "faint"'s +# reference and "faint" shows "bright"'s content. bright <-> faint is the mutual swap (distance +# 0 both ways); dim <-> bright is weaker (bright is at 1.1 from dim's reference). +ROLE_REF = { + "dim": (1000.0, 125.0, 5000.0), + "bright": (4000.0, 500.0, 20000.0), + "faint": (800.0, 100.0, 4000.0), +} +ROLE_SHOWN = {"dim": "bright", "bright": "faint", "faint": "bright"} + + +def roles_named(names): + """The review's case with the roles dim, bright and faint named ``names``.""" + name = dict(zip(("dim", "bright", "faint"), names, strict=True)) + ref = {name[role]: values for role, values in ROLE_REF.items()} + shown = {name[role]: ROLE_REF[other] for role, other in ROLE_SHOWN.items()} + return name, one_unit_off(ref, shown) + + +def test_the_strongest_mutual_pair_is_chosen_not_the_first_name(): + """#395: B <-> C (distance 0 each way) is the swap; A stays a plain look-alike of B.""" + report = check_channel_identity(roles_named("ABC")[1]) + found = {f.channel: (f.code, f.nearest, f.mutual) for f in report.findings} + assert found == { + "A": (POSSIBLE_CHANNEL_SWAP, "B", False), + "B": (POSSIBLE_CHANNEL_SWAP, "C", True), + "C": (POSSIBLE_CHANNEL_SWAP, "B", True), + } + messages = sorted(issue.message for issue in report.validation_issues()) + assert len(messages) == 2 + assert "channel A does not look like A" in messages[0] and "but like B" in messages[0] + assert "channels B and C look swapped" in messages[1] + assert "A and B look swapped" not in " ".join(messages) + + +@pytest.mark.parametrize("names", sorted(itertools.permutations("ABC"))) +def test_the_chosen_pair_does_not_depend_on_channel_names(names): + """#395: renaming the channels (and reordering the images) gives the same physical answer.""" + name, summaries = roles_named(names) + for order in (summaries, summaries[::-1]): + report = check_channel_identity(order) + found = {f.channel: (f.code, f.nearest, f.mutual) for f in report.findings} + dim, bright, faint = name["dim"], name["bright"], name["faint"] + assert found == { + dim: (POSSIBLE_CHANNEL_SWAP, bright, False), + bright: (POSSIBLE_CHANNEL_SWAP, faint, True), + faint: (POSSIBLE_CHANNEL_SWAP, bright, True), + } + swaps = [i.message for i in report.validation_issues() if "look swapped" in i.message] + pair = " and ".join(sorted((bright, faint))) + assert len(swaps) == 1 and f"channels {pair} look swapped" in swaps[0] + + +def test_tied_mutual_pairs_are_one_ambiguous_finding(): + """#395: A and C look alike and B is swapped with both: no pair is picked, all are named.""" + ref = {"A": (800.0, 100.0, 4000.0), "B": (4000.0, 500.0, 20000.0), "C": (800.0, 100.0, 4000.0)} + summaries = one_unit_off(ref, {"A": ref["B"], "B": ref["A"], "C": ref["B"]}) + report = check_channel_identity(summaries) + assert {f.channel: (f.code, f.mutual) for f in report.findings} == { + c: (AMBIGUOUS_CHANNEL_SWAP, False) for c in "ABC" + } + alternatives = {f.channel: tuple(c for c, _ in f.alternatives) for f in report.findings} + assert alternatives == {"A": ("B",), "B": ("A", "C"), "C": ("B",)} + (issue,) = report.validation_issues() + assert issue.code == AMBIGUOUS_CHANNEL_SWAP and not issue.is_error + assert issue.paths == ("ctrl/rep1/t0",) + assert "channels A, B and C look swapped in more than one way" in issue.message + assert "its B looks like A or C" in issue.message and "no pair is named" in issue.message + assert "every channel named" in issue.action and "names no pair" in issue.action + assert check_channel_identity(summaries[::-1]).findings == report.findings + text = channel_identity_text(report) + assert f"in more than one way ({AMBIGUOUS_CHANNEL_SWAP}, 1):" in text diff --git a/tests/test_notebook_channel_identity.py b/tests/test_notebook_channel_identity.py index cda9e6d9..29e13fc2 100644 --- a/tests/test_notebook_channel_identity.py +++ b/tests/test_notebook_channel_identity.py @@ -3,6 +3,7 @@ import pytest from test_channel_identity import UNITS, experiment +from test_channel_identity_pairs import one_unit_off pytest.importorskip("ipywidgets") pytest.importorskip("matplotlib") @@ -54,3 +55,13 @@ def test_the_section_shows_the_status_and_the_reasons_when_nothing_was_checked(s def test_the_section_with_a_plot_shows_the_plot(): view = shown(experiment()) assert ui.is_visible(view.box) and ui.is_visible(view.plot) and view.plot.value + + +def test_an_ambiguous_swap_is_one_row_naming_every_channel(): + """#395: tied mutual pairs are one row, with their own words and what to do.""" + ref = {"A": (800.0, 100.0, 4000.0), "B": (4000.0, 500.0, 20000.0), "C": (800.0, 100.0, 4000.0)} + view = shown(one_unit_off(ref, {"A": ref["B"], "B": ref["A"], "C": ref["B"]})) + assert view.findings.value.count("Swap, pair unclear") == 1 + assert "channels A, B and C look swapped in more than one way" in view.findings.value + assert "Channels that look swapped in more than one way" in view.findings.value + assert ui.is_visible(view.plot) and view.plot.value From da0aa3246720fd8c6d71ae634ca611047ef2f85d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 19:25:17 +0000 Subject: [PATCH 13/15] #433: accept NumPy whole numbers of channels, refuse bool checked_shown accepts numbers.Integral (not bool) and returns an int; ViewRequest and header_channels share it. Changelog for #395 and #433. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- CHANGELOG.md | 4 +-- .../header_preview.py | 25 ++++++++++++++++--- src/morphobricks_preprocessing/image_view.py | 8 ++---- tests/test_image_viewer.py | 13 +++++++++- 4 files changed, 37 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b6647a7..a65a076f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,9 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased - **Quick fixes B (24 November 2026): channel QC, previews, notebook cards and state, results lifecycle.** - - **A channel keeps one swap partner in the channel-identity check (#395).** When two channels of a unit look alike and a third is swapped with both, the third no longer overwrites its partner's mutual pair: the first pair (sorted order) keeps it, and the other channel stays a plain `possible_channel_swap` finding, so one channel is never in two "look swapped" warnings. Warning-only, as before. `tests/test_channel_identity.py`. + - **Mutual channel swaps are chosen by strength, never by channel name (#395).** A third channel swapped with one of a mutual pair overwrote its partner, so one channel was in two "look swapped" warnings. Candidate mutual pairs are now ranked by strength, the larger of the pair's two cross distances (smaller is stronger), and taken greedily from the strongest, each channel in one pair at most; a channel not in a chosen pair keeps its plain "does not look like X but like Y" warning. When pairs sharing a channel are within `PAIR_TOLERANCE` (0.5) of each other, none is named: a new warning `ambiguous_channel_swap` names every channel of the group, each with its distances, and says to check them all (`ChannelFinding.alternatives`; notebook row "Swap, pair unclear", its plot label lists every alternative). Channel names and image order no longer decide (with A at 1000/125/5000, B at 4000/500/20000 and C at 800/100/4000, a unit whose B shows C's reference and whose A and C show B's now gives "B and C look swapped", not "A and B"). Warning-only, as before. Contract §14.1, user guide. `tests/test_channel_identity_pairs.py`, `tests/test_notebook_channel_identity.py`. - **Cached preview planes are keyed by the confirmed roles (#428).** `PreviewCache` keys held the path, fingerprint and coordinates but not the roles, so one file read as `ZCYX` and then `CZYX` showed the first reading's pixels. The key now holds the mapping's axes, roles and singleton roles (also for the discard after a rewrite). `tests/test_preview.py`. - - **A view of fewer than one channel is refused before any read (#433).** `ViewRequest(shown=...)` and `header_channels(..., shown)` raise a `ValueError` naming the value when it is not a whole number of at least 1, instead of an `IndexError`, `AttributeError` or `ZeroDivisionError` after reading. `tests/test_image_viewer.py`. + - **A view of fewer than one channel is refused before any read (#433).** `ViewRequest(shown=...)` and `header_channels(..., shown)` raise a `ValueError` naming the value when it is not a whole number of at least 1, instead of an `IndexError`, `AttributeError` or `ZeroDivisionError` after reading. Any whole number (`numbers.Integral`, so NumPy integers too) is accepted and kept as an `int`; `bool` is refused (`header_preview.checked_shown`). `tests/test_image_viewer.py`. - **A plane that cannot be read is the H&E tissue-mask card's and command's refusal (#469).** The preview and the write of the card, and `tissue-mask`, now catch `PlaneReadError` (`PlaneMemoryError`, `CompressionNotBoundedError`) and `OSError`: the card replaces "Computing the preview…" with the message and hides an earlier preview; the command prints the image's refusal and exits 1, without a traceback. `tests/test_notebook_tissue_mask.py`, `tests/test_cli_tissue_mask.py`. - **Converting a declared mask the run recorded no file of is refused (#481).** The *Convert a mask* card said "The mask is converted." with nothing written; it now shows a red card naming the mask ID and its source type, and writes nothing. The run's manifest is read at the click (the card refreshes on the description only), so no stale state disables the button. `tests/test_notebook_mask_conversion.py`. - **An empty row fold drops its earlier rows (#514).** `RowFold.arrange` kept the last fold's rows (and their images and callbacks) in its hidden box when nothing folded; it now empties the box and its line. `tests/test_notebook_row_fold.py`. diff --git a/src/morphobricks_preprocessing/header_preview.py b/src/morphobricks_preprocessing/header_preview.py index 8a5eec6c..dfa21173 100644 --- a/src/morphobricks_preprocessing/header_preview.py +++ b/src/morphobricks_preprocessing/header_preview.py @@ -30,6 +30,7 @@ from __future__ import annotations import math +import numbers import os from collections.abc import Mapping from dataclasses import dataclass @@ -251,6 +252,24 @@ def _channel_layout(meta: TiffMetadata) -> tuple[AxisMapping, list[int], int]: return AxisMapping(meta.axes, tuple(roles)), projected, c +def checked_shown(shown: object) -> int: + """Return ``shown``, the number of channels to draw, as an ``int`` (#433). + + Any whole number (``int`` or a NumPy integer, ``numbers.Integral``) of at least 1 is + accepted; ``bool`` is not a number of channels. + + Raises + ------ + ValueError + When ``shown`` is a ``bool``, not a whole number, or below 1. + """ + if isinstance(shown, bool) or not isinstance(shown, numbers.Integral) or shown < 1: + raise ValueError( + f"The number of channels to draw must be a whole number of at least 1, not {shown!r}." + ) + return int(shown) + + def header_channels( path: str | os.PathLike, meta: TiffMetadata, side: int, shown: int = CHANNELS_SHOWN ) -> HeaderChannels: @@ -268,10 +287,7 @@ def header_channels( When the file cannot be read; ValueError also when ``shown`` is not a whole number of at least 1. """ - if isinstance(shown, bool) or not isinstance(shown, int) or shown < 1: - raise ValueError( # before any read (#433) - f"The number of channels to draw must be a whole number of at least 1, not {shown!r}." - ) + shown = checked_shown(shown) # before any read (#433) if not meta.readable: raise PreviewUnavailable(f"the header cannot be read: {meta.error or 'unknown reason'}") mapping, projected, c_axis = _channel_layout(meta) @@ -352,6 +368,7 @@ def header_preview( __all__ = [ "CHANNELS_SHOWN", + "checked_shown", "HEADER_NOTE", "NO_YX", "PIXEL_CAP", diff --git a/src/morphobricks_preprocessing/image_view.py b/src/morphobricks_preprocessing/image_view.py index 8335974c..da2975cb 100644 --- a/src/morphobricks_preprocessing/image_view.py +++ b/src/morphobricks_preprocessing/image_view.py @@ -22,7 +22,7 @@ from .axes import AxisMapping from .fingerprint import Fingerprint -from .header_preview import CHANNELS_SHOWN +from .header_preview import CHANNELS_SHOWN, checked_shown from .planes import DEFAULT_MEMORY_LIMIT from .preview import THUMBNAIL_SIDE, ReducedPlane, check_unchanged, read_plane from .preview_render import colour_composite, display_panel, png_bytes @@ -132,11 +132,7 @@ class ViewRequest: def __post_init__(self) -> None: # Refused before any read: no channel to draw is not a picture (#433). - if isinstance(self.shown, bool) or not isinstance(self.shown, int) or self.shown < 1: - raise ValueError( - f"The number of channels to draw must be a whole number of at least 1, " - f"not {self.shown!r}." - ) + object.__setattr__(self, "shown", checked_shown(self.shown)) def read_view( diff --git a/tests/test_image_viewer.py b/tests/test_image_viewer.py index 1295e5e7..020b6ae3 100644 --- a/tests/test_image_viewer.py +++ b/tests/test_image_viewer.py @@ -126,7 +126,7 @@ def test_at_most_six_channels_are_drawn_and_the_view_says_so(tmp_path): assert [t.c for t in one.tiles] == [None] and one.shown_text == "the only channel" -@pytest.mark.parametrize("shown", [0, -1, True, 1.5, "2"]) +@pytest.mark.parametrize("shown", [0, -1, True, False, np.bool_(True), np.int64(0), 1.5, "2"]) def test_a_view_of_no_channel_is_refused_before_any_read(tmp_path, monkeypatch, shown): """#433: ``shown`` below 1 (or not a whole number) is a ValueError, not a crash later.""" write(tmp_path / "a.tif", "CYX", (2, 8, 8)) @@ -138,6 +138,17 @@ def test_a_view_of_no_channel_is_refused_before_any_read(tmp_path, monkeypatch, header_channels(tmp_path / "a.tif", meta, 64, shown) +@pytest.mark.parametrize("shown", [np.int64(1), np.uint8(2), np.int32(6)]) +def test_a_numpy_whole_number_of_channels_is_accepted(tmp_path, shown): + """#433: a NumPy integer is a whole number of channels; it is kept as a Python int.""" + write(tmp_path / "a.tif", "CYX", (2, 8, 8)) + meta = inspect_image(tmp_path / "a.tif", "a.tif") + request = ViewRequest(shown=shown) + assert request.shown == int(shown) and type(request.shown) is int + picture = header_channels(tmp_path / "a.tif", meta, 64, shown) + assert len(picture.tiles) == min(2, int(shown)) + + def test_a_view_is_refused_for_another_revision_and_without_y_and_x(tmp_path): path = tmp_path / "a.tif" write(path, "CYX", (2, 8, 8)) From e660cbfca851971b9475aed78e8524f9a461692d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 20:20:13 +0000 Subject: [PATCH 14/15] #395: pin the swap tolerance with near-tie tests, say what it measures Tests: a near-tie just inside and just outside PAIR_TOLERANCE (strengths computed in the test and asserted to straddle it), two independent swaps, an ambiguous group beside a clean swap, a 3-cycle (three plain look-alikes, locked), name and image-order independence of the ambiguous case, and units/conditions that do not interact. Wording: the ambiguous warning says the pairs are within the tolerance in robust deviations of the larger cross distance, and that look-alike alternatives are why no pair can be chosen. Contract 14.1, user guide and CHANGELOG updated. PAIR_TOLERANCE and its computation are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- CHANGELOG.md | 1 + docs/contract.md | 4 +- docs/user_guide.md | 2 +- .../channel_identity_text.py | 13 +- tests/test_channel_identity_pairs.py | 182 ++++++++++++++++++ 5 files changed, 197 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a65a076f..bfefff5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ v0.5.1: no run before v0.5.1 is read.) - **Quick fixes B (24 November 2026): channel QC, previews, notebook cards and state, results lifecycle.** - **Mutual channel swaps are chosen by strength, never by channel name (#395).** A third channel swapped with one of a mutual pair overwrote its partner, so one channel was in two "look swapped" warnings. Candidate mutual pairs are now ranked by strength, the larger of the pair's two cross distances (smaller is stronger), and taken greedily from the strongest, each channel in one pair at most; a channel not in a chosen pair keeps its plain "does not look like X but like Y" warning. When pairs sharing a channel are within `PAIR_TOLERANCE` (0.5) of each other, none is named: a new warning `ambiguous_channel_swap` names every channel of the group, each with its distances, and says to check them all (`ChannelFinding.alternatives`; notebook row "Swap, pair unclear", its plot label lists every alternative). Channel names and image order no longer decide (with A at 1000/125/5000, B at 4000/500/20000 and C at 800/100/4000, a unit whose B shows C's reference and whose A and C show B's now gives "B and C look swapped", not "A and B"). Warning-only, as before. Contract §14.1, user guide. `tests/test_channel_identity_pairs.py`, `tests/test_notebook_channel_identity.py`. + - **Ambiguous-swap wording (#395 re-review).** The warning now says that the pairs are within `PAIR_TOLERANCE` robust deviations of each other in the larger of their two cross distances, and, for a channel with several alternatives, that those alternatives look alike in the other units, which is why no pair can be chosen. A three-cycle (A shows B, B shows C, C shows A) stays three plain look-alikes (documented, tested). `PAIR_TOLERANCE` and its computation are unchanged. Tests only otherwise. - **Cached preview planes are keyed by the confirmed roles (#428).** `PreviewCache` keys held the path, fingerprint and coordinates but not the roles, so one file read as `ZCYX` and then `CZYX` showed the first reading's pixels. The key now holds the mapping's axes, roles and singleton roles (also for the discard after a rewrite). `tests/test_preview.py`. - **A view of fewer than one channel is refused before any read (#433).** `ViewRequest(shown=...)` and `header_channels(..., shown)` raise a `ValueError` naming the value when it is not a whole number of at least 1, instead of an `IndexError`, `AttributeError` or `ZeroDivisionError` after reading. Any whole number (`numbers.Integral`, so NumPy integers too) is accepted and kept as an `int`; `bool` is refused (`header_preview.checked_shown`). `tests/test_image_viewer.py`. - **A plane that cannot be read is the H&E tissue-mask card's and command's refusal (#469).** The preview and the write of the card, and `tissue-mask`, now catch `PlaneReadError` (`PlaneMemoryError`, `CompressionNotBoundedError`) and `OSError`: the card replaces "Computing the preview…" with the message and hides an earlier preview; the command prints the image's refusal and exits 1, without a traceback. `tests/test_notebook_tissue_mask.py`, `tests/test_cli_tissue_mask.py`. diff --git a/docs/contract.md b/docs/contract.md index 60b5cbf6..b0dd7708 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -926,8 +926,8 @@ same image summaries (design `channel-identity-check-2026-11-21`, owner answers | Reference | For unit `u` and channel `c`: the per-component median and MAD × 1.4826 (at least `mad_floor`) of `c`'s signatures in the other units of `u`'s condition, never `u` itself. A treatment effect is therefore not reported when the condition has at least `min_reference` other units with the channel. With fewer, the other units of the experiment are the reference and the finding says "compared across conditions" (a treatment effect may then be reported); with fewer still, `c` of `u` is not checked (listed, not a warning). Units are compared only with units of the same pixel type; different types are named as not compared. **Limit:** a swap made in every unit of a condition is not found, since it is what that condition looks like. | | Distance | `d(u, c -> c')`: root mean square of the robust z-scores of `u`'s `c` signature against the reference of `c'`. | | Reported | A unit channel is reported when `d(u, c -> c) > outlier_limit` and at least one component is more than `outlier_limit` robust deviations and at least `min_log_difference` from the reference (the components named as off: level, brightness, contrast). Only unit channels compared with a reference count as checked; with none, the summary says that no channel could be checked. | -| `possible_channel_swap` | Either a mutual pair: `u`'s `c` is reported, its nearest other channel `c'` is one of `u`'s channels, `partner_ratio × d(u, c -> c') < d(u, c -> c)` and `partner_ratio × d(u, c' -> c) < d(u, c' -> c')`, both within `outlier_limit` (`u`'s `c'` reported or not): a candidate pair, whose strength is the larger of `d(u, c -> c')` and `d(u, c' -> c)` (smaller is stronger). The pairs are chosen greedily from the strongest, and a channel is in one pair at most (#395): one warning per chosen pair, "`c` and `c'` look swapped", with both channels' distances, naming the unit once. Or a clear look-alike of another channel `c'` of the unit, not in a chosen pair: `d(u, c -> c') <= swap_limit` and `swap_ratio × d(u, c -> c') < d(u, c -> c)` ("does not look like `c` but like `c'`"). Channel names and the order of the images never decide which pair is chosen. | -| `ambiguous_channel_swap` | When the strongest remaining candidate pair shares a channel with other remaining pairs of the unit (directly or through each other) whose strengths are within `PAIR_TOLERANCE` (0.5, a constant, not a recorded limit) of it, none of them is chosen: one warning naming every channel of the group, each with its own distance and its distances to the channels it could be swapped with, "look swapped in more than one way … no pair is named"; those channels are paired with nothing else. Check every channel named. | +| `possible_channel_swap` | Either a mutual pair: `u`'s `c` is reported, its nearest other channel `c'` is one of `u`'s channels, `partner_ratio × d(u, c -> c') < d(u, c -> c)` and `partner_ratio × d(u, c' -> c) < d(u, c' -> c')`, both within `outlier_limit` (`u`'s `c'` reported or not): a candidate pair, whose strength is the larger of `d(u, c -> c')` and `d(u, c' -> c)` (smaller is stronger). The pairs are chosen greedily from the strongest, and a channel is in one pair at most (#395): one warning per chosen pair, "`c` and `c'` look swapped", with both channels' distances, naming the unit once. Or a clear look-alike of another channel `c'` of the unit, not in a chosen pair: `d(u, c -> c') <= swap_limit` and `swap_ratio × d(u, c -> c') < d(u, c -> c)` ("does not look like `c` but like `c'`"). Channel names and the order of the images never decide which pair is chosen. A cycle of three or more channels (A shows B's content, B shows C's, C shows A's) has no mutual pair: each channel keeps its own "does not look like `c` but like `c'`" warning (locked by a test). | +| `ambiguous_channel_swap` | When the strongest remaining candidate pair shares a channel with other remaining pairs of the unit (directly or through each other) whose strengths are within `PAIR_TOLERANCE` (0.5, a constant, not a recorded limit) of it, none of them is chosen: one warning naming every channel of the group, each with its own distance and its distances to the channels it could be swapped with, "look swapped in more than one way … no pair is named" (the pairs are "within 0.5 robust deviations of each other in the larger of their two cross distances", and a channel with several alternatives adds that those alternatives "look alike in the other units, which is why no pair can be chosen"); those channels are paired with nothing else. Check every channel named. | | `channel_unlike_others` | Every other reported unit channel: names the unit (`condition/biological repeat/technical repeat`), the channel, the components off and the distances; "Nearest channel: `c'`" when another channel's reference is nearer than its own, or "It looks like `c'`, a channel this unit does not have" for a clear look-alike of a channel the unit lacks (never called a swap). | | Limits | `ChannelIdentitySettings`: `outlier_limit` 3.5, `min_reference` 3, `mad_floor` 0.2, `min_log_difference` 0.6 (natural-log units), `swap_limit` 1.0, `swap_ratio` 3.0, `partner_ratio` 2.0, chosen with a simulation (2 conditions × 4 units × 3 channels, between-unit variation of 10 % and 20 %; PR #364). With very noisy data (units differing by about 30 % per channel) false warnings become frequent: in that simulation 171 of 300 runs without any swap give a warning and 59 a false swap; read the warnings as prompts to look, never as verdicts. The run uses the defaults and records them in the manifest (`channel_identity`, §9, beside `intensity_checks`); other limits are applied by calling `check_channel_identity(result.intensity.summaries, settings)`, which recomputes nothing. | | Run | `RunResult.channel_identity` (`ChannelIdentityReport`: signatures, findings, warnings, not checked, the number compared, pixel types and offsets) for a written table, None otherwise; its warnings are in the run report beside the intensity warnings and kept apart from `RunResult.issues`. | diff --git a/docs/user_guide.md b/docs/user_guide.md index 82561629..9760be92 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -722,7 +722,7 @@ imaging unit's channels compared with the same channels of the other units of it (a treatment effect is not reported when the condition has at least 3 other units), with `channel_unlike_others`, `possible_channel_swap` (for example "channels DAPI and GFP look swapped") and `ambiguous_channel_swap` warnings (channels that look swapped in more than one -way the check cannot tell apart: it names them all and no pair) and the channels it could not check; the notebook draws them under +way the check cannot tell apart: it names them all and no pair; a cycle of three channels, A shows B, B shows C, C shows A, is not a swap and gives three "does not look like" warnings) and the channels it could not check; the notebook draws them under **Do the channels look like themselves?**. A swap made in every unit of a condition is not found. Warnings only: nothing is changed or blocked. diff --git a/src/morphobricks_preprocessing/channel_identity_text.py b/src/morphobricks_preprocessing/channel_identity_text.py index a6da4645..7a4f2b11 100644 --- a/src/morphobricks_preprocessing/channel_identity_text.py +++ b/src/morphobricks_preprocessing/channel_identity_text.py @@ -104,11 +104,20 @@ def _ambiguous_message(group: Sequence[ChannelFinding]) -> str: f"its {found.channel} looks like {alike} (distance {found.distance:.1f} to " f"{found.channel}, {near})" ) - return ( + text = ( f"In unit {first.unit.label}, channels {_names([f.channel for f in group])} look " f"swapped in more than one way: compared with {others}, {'; '.join(parts)}. The " - f"possible pairs are within {PAIR_TOLERANCE:g} of each other, so no pair is named." + f"possible pairs are within {PAIR_TOLERANCE:g} robust deviations of each other in the " + "larger of their two cross distances, so no pair is named." ) + for found in group: + if len(found.alternatives) > 1: + alike = _names([c for c, _ in found.alternatives]) + text += ( + f" {alike} look alike in the other units, which is why no pair can be " + f"chosen for {found.channel}." + ) + return text def _others(across: bool) -> str: diff --git a/tests/test_channel_identity_pairs.py b/tests/test_channel_identity_pairs.py index eebd41c8..d2880827 100644 --- a/tests/test_channel_identity_pairs.py +++ b/tests/test_channel_identity_pairs.py @@ -4,8 +4,10 @@ import pytest +from morphobricks_preprocessing import channel_identity from morphobricks_preprocessing.channel_identity import ( AMBIGUOUS_CHANNEL_SWAP, + PAIR_TOLERANCE, POSSIBLE_CHANNEL_SWAP, Unit, channel_identity_text, @@ -96,3 +98,183 @@ def test_tied_mutual_pairs_are_one_ambiguous_finding(): assert check_channel_identity(summaries[::-1]).findings == report.findings text = channel_identity_text(report) assert f"in more than one way ({AMBIGUOUS_CHANNEL_SWAP}, 1):" in text + + +def strengths_of(monkeypatch, summaries): + """Run the check and return ``({channels: strength}, report)`` of the candidate pairs.""" + seen = [] + choose = channel_identity._choose + monkeypatch.setattr( + channel_identity, "_choose", lambda pairs: (seen.append(pairs), choose(pairs))[1] + ) + report = check_channel_identity(summaries) + return {p.channels: p.strength for p in seen[0]}, report + + +def faint_scaled(factor): + """The review's roles with faint's reference ``factor`` times its base; faint shows bright's. + + dim shows bright, bright shows faint's (scaled) reference and faint shows bright's: bright + <-> faint is exactly mutual (strength 0), dim <-> bright is the weaker, closer to a tie the + nearer faint's reference is to dim's (``factor`` 1.25 is dim's reference exactly). + """ + ref = dict(ROLE_REF, faint=tuple(factor * v for v in ROLE_REF["faint"])) + shown = {role: ref[other] for role, other in ROLE_SHOWN.items()} + return one_unit_off(ref, shown) + + +def test_a_near_tie_just_inside_the_tolerance_is_ambiguous(monkeypatch): + """#395: strengths 0 and about 0.46 (within PAIR_TOLERANCE of each other) are one group.""" + strengths, report = strengths_of(monkeypatch, faint_scaled(1.14)) + assert strengths[("bright", "faint")] == pytest.approx(0.0, abs=1e-6) + assert 0.40 < strengths[("bright", "dim")] < PAIR_TOLERANCE + assert {f.channel: f.code for f in report.findings} == { + c: AMBIGUOUS_CHANNEL_SWAP for c in ROLE_REF + } + + +def test_a_near_tie_just_outside_the_tolerance_is_a_clean_swap(monkeypatch): + """#395: strengths 0 and about 0.63 are not a tie: bright <-> faint, dim a look-alike.""" + strengths, report = strengths_of(monkeypatch, faint_scaled(1.10)) + assert strengths[("bright", "faint")] == pytest.approx(0.0, abs=1e-6) + assert PAIR_TOLERANCE < strengths[("bright", "dim")] < 0.75 + found = {f.channel: (f.code, f.nearest, f.mutual) for f in report.findings} + assert found == { + "dim": (POSSIBLE_CHANNEL_SWAP, "bright", False), + "bright": (POSSIBLE_CHANNEL_SWAP, "faint", True), + "faint": (POSSIBLE_CHANNEL_SWAP, "bright", True), + } + swaps = [i.message for i in report.validation_issues() if "look swapped" in i.message] + assert len(swaps) == 1 and "channels bright and faint look swapped" in swaps[0] + + +def units_off(shown_by_unit, ref, conditions=("ctrl", "treated"), per_condition=6): + """Units of every condition showing ``ref``, except the units in ``shown_by_unit``.""" + units = [Unit(c, "rep1", f"t{i}") for c in conditions for i in range(per_condition)] + return [summary(u, i, shown_by_unit.get(u, ref)) for u in units for i in range(2)] + + +FOUR = { + "A": (1000.0, 125.0, 5000.0), + "B": (4000.0, 500.0, 20000.0), + "C": (300.0, 50.0, 1500.0), + "D": (150.0, 80.0, 600.0), +} + + +def test_two_independent_swaps_are_two_warnings(): + """#395: A <-> B and C <-> D are separate pairs, each its own warning, nothing ambiguous.""" + shown = {"A": FOUR["B"], "B": FOUR["A"], "C": FOUR["D"], "D": FOUR["C"]} + report = check_channel_identity(one_unit_off(FOUR, shown)) + assert {f.channel: (f.code, f.nearest, f.mutual) for f in report.findings} == { + "A": (POSSIBLE_CHANNEL_SWAP, "B", True), + "B": (POSSIBLE_CHANNEL_SWAP, "A", True), + "C": (POSSIBLE_CHANNEL_SWAP, "D", True), + "D": (POSSIBLE_CHANNEL_SWAP, "C", True), + } + messages = sorted(i.message for i in report.validation_issues()) + assert len(messages) == 2 + assert "channels A and B look swapped" in messages[0] + assert "channels C and D look swapped" in messages[1] + + +def test_an_ambiguous_group_does_not_hold_back_a_clean_swap_of_other_channels(): + """#395: five channels: A, B, C (A and C alike) are one group; D <-> E is still a pair.""" + ref = {"A": FOUR["A"], "B": FOUR["B"], "C": FOUR["A"], "D": FOUR["C"], "E": FOUR["D"]} + shown = {"A": ref["B"], "B": ref["A"], "C": ref["B"], "D": ref["E"], "E": ref["D"]} + report = check_channel_identity(one_unit_off(ref, shown)) + assert {f.channel: (f.code, f.mutual) for f in report.findings} == { + "A": (AMBIGUOUS_CHANNEL_SWAP, False), + "B": (AMBIGUOUS_CHANNEL_SWAP, False), + "C": (AMBIGUOUS_CHANNEL_SWAP, False), + "D": (POSSIBLE_CHANNEL_SWAP, True), + "E": (POSSIBLE_CHANNEL_SWAP, True), + } + messages = sorted(i.message for i in report.validation_issues()) + assert len(messages) == 2 + assert "channels A, B and C look swapped in more than one way" in messages[0] + assert "channels D and E look swapped" in messages[1] + + +def test_a_three_cycle_is_three_plain_look_alikes(): + """Current behaviour, locked: A shows B, B shows C, C shows A is no mutual pair at all.""" + ref = {c: FOUR[c] for c in "ABC"} + report = check_channel_identity( + one_unit_off(ref, {"A": ref["B"], "B": ref["C"], "C": ref["A"]}) + ) + assert {f.channel: (f.code, f.nearest, f.mutual) for f in report.findings} == { + "A": (POSSIBLE_CHANNEL_SWAP, "B", False), + "B": (POSSIBLE_CHANNEL_SWAP, "C", False), + "C": (POSSIBLE_CHANNEL_SWAP, "A", False), + } + messages = [i.message for i in report.validation_issues()] + assert len(messages) == 3 + assert not any("look swapped" in m for m in messages) + assert all("does not look like" in m for m in messages) + + +@pytest.mark.parametrize("names", sorted(itertools.permutations("XYZ"))) +def test_the_ambiguous_group_does_not_depend_on_names_or_image_order(names): + """#395: the tied case is the same physical answer under every naming and image order.""" + one, two, alike = names # roles: faint-like, bright, and the channel alike to the first + ref = {one: ROLE_REF["faint"], two: ROLE_REF["bright"], alike: ROLE_REF["faint"]} + shown = {one: ref[two], two: ref[one], alike: ref[two]} + summaries = one_unit_off(ref, shown) + expected = { + two: tuple(sorted((one, alike))), + one: (two,), + alike: (two,), + } + for order in (summaries, summaries[::-1]): + report = check_channel_identity(order) + assert {f.channel: f.code for f in report.findings} == { + c: AMBIGUOUS_CHANNEL_SWAP for c in names + } + found = {f.channel: tuple(c for c, _ in f.alternatives) for f in report.findings} + assert found == expected + (issue,) = report.validation_issues() + assert f"channels {', '.join(sorted(names)[:2])} and {sorted(names)[2]} look" in ( + issue.message + ) + + +def test_units_of_other_conditions_and_other_units_do_not_interact(): + """#395: a tie in one unit and a clean swap of the same channels in others stay apart.""" + ref = {"A": FOUR["A"], "B": FOUR["B"], "C": FOUR["A"]} + tie = Unit("ctrl", "rep1", "t0") + swap_same_condition = Unit("ctrl", "rep1", "t1") + swap_other_condition = Unit("treated", "rep1", "t0") + clean = {"A": ref["B"], "B": ref["A"], "C": ref["C"]} + summaries = units_off( + { + tie: {"A": ref["B"], "B": ref["A"], "C": ref["B"]}, + swap_same_condition: clean, + swap_other_condition: clean, + }, + ref, + ) + report = check_channel_identity(summaries) + by_unit = {} + for f in report.findings: + by_unit.setdefault(f.unit, {})[f.channel] = (f.code, f.mutual) + assert by_unit[tie] == {c: (AMBIGUOUS_CHANNEL_SWAP, False) for c in "ABC"} + for unit in (swap_same_condition, swap_other_condition): + assert by_unit[unit]["A"] == (POSSIBLE_CHANNEL_SWAP, True), by_unit[unit] + assert by_unit[unit]["B"] == (POSSIBLE_CHANNEL_SWAP, True), by_unit[unit] + assert set(by_unit) == {tie, swap_same_condition, swap_other_condition} + + +def test_the_ambiguous_message_says_what_the_tolerance_measures_and_why_no_pair(): + """#395: "within 0.5" names its unit, and look-alike references are named as the cause.""" + ref = {"A": ROLE_REF["faint"], "B": ROLE_REF["bright"], "C": ROLE_REF["faint"]} + report = check_channel_identity( + one_unit_off(ref, {"A": ref["B"], "B": ref["A"], "C": ref["B"]}) + ) + (issue,) = report.validation_issues() + assert ( + f"within {PAIR_TOLERANCE:g} robust deviations of each other in the larger of their two " + "cross distances, so no pair is named." in issue.message + ) + assert "A and C look alike in the other units, which is why no pair can be chosen" in ( + issue.message + ) From 84b96a5b748d5e3c64db9a1c0338b5257c30638b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 20:52:30 +0000 Subject: [PATCH 15/15] Record the channel-swap pair tolerance in the manifest (owner decision) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PAIR_TOLERANCE, which decides between a clean possible_channel_swap and an ambiguous_channel_swap, becomes ChannelIdentitySettings.pair_tolerance (default 0.5; finite and at least 0), written to the run manifest's channel_identity with the seven other limits and read back, so a verdict can be reproduced from the manifest. The ambiguous warning and the printed limits name the tolerance used. Limits recorded without pair_tolerance are read with 0.5, explicitly: earlier code used 0.5 as a constant, and no released version recorded these limits or produced ambiguous_channel_swap (v0.8.0 manifests have no channel_identity at all and still read as None). Every other key stays required. No CLI option or notebook field exists for any channel-check limit, so it is exposed through the settings API only. Contract §9 and §14.1, user guide, CHANGELOG. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AxjpGPw9xfWAUJNqc --- CHANGELOG.md | 3 +- docs/contract.md | 6 +- docs/user_guide.md | 8 ++- .../channel_identity.py | 8 +-- .../channel_identity_model.py | 42 +++++++++++--- .../channel_identity_text.py | 19 ++++--- tests/test_channel_identity.py | 37 ++++++++++++ tests/test_channel_identity_pairs.py | 56 +++++++++++++++++-- tests/test_channel_identity_run.py | 31 ++++++++++ 9 files changed, 180 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfefff5b..3b21baba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,9 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased - **Quick fixes B (24 November 2026): channel QC, previews, notebook cards and state, results lifecycle.** - - **Mutual channel swaps are chosen by strength, never by channel name (#395).** A third channel swapped with one of a mutual pair overwrote its partner, so one channel was in two "look swapped" warnings. Candidate mutual pairs are now ranked by strength, the larger of the pair's two cross distances (smaller is stronger), and taken greedily from the strongest, each channel in one pair at most; a channel not in a chosen pair keeps its plain "does not look like X but like Y" warning. When pairs sharing a channel are within `PAIR_TOLERANCE` (0.5) of each other, none is named: a new warning `ambiguous_channel_swap` names every channel of the group, each with its distances, and says to check them all (`ChannelFinding.alternatives`; notebook row "Swap, pair unclear", its plot label lists every alternative). Channel names and image order no longer decide (with A at 1000/125/5000, B at 4000/500/20000 and C at 800/100/4000, a unit whose B shows C's reference and whose A and C show B's now gives "B and C look swapped", not "A and B"). Warning-only, as before. Contract §14.1, user guide. `tests/test_channel_identity_pairs.py`, `tests/test_notebook_channel_identity.py`. + - **Mutual channel swaps are chosen by strength, never by channel name (#395).** A third channel swapped with one of a mutual pair overwrote its partner, so one channel was in two "look swapped" warnings. Candidate mutual pairs are now ranked by strength, the larger of the pair's two cross distances (smaller is stronger), and taken greedily from the strongest, each channel in one pair at most; a channel not in a chosen pair keeps its plain "does not look like X but like Y" warning. When pairs sharing a channel are within `pair_tolerance` (0.5 by default, a recorded limit since the entry below) of each other, none is named: a new warning `ambiguous_channel_swap` names every channel of the group, each with its distances, and says to check them all (`ChannelFinding.alternatives`; notebook row "Swap, pair unclear", its plot label lists every alternative). Channel names and image order no longer decide (with A at 1000/125/5000, B at 4000/500/20000 and C at 800/100/4000, a unit whose B shows C's reference and whose A and C show B's now gives "B and C look swapped", not "A and B"). Warning-only, as before. Contract §14.1, user guide. `tests/test_channel_identity_pairs.py`, `tests/test_notebook_channel_identity.py`. - **Ambiguous-swap wording (#395 re-review).** The warning now says that the pairs are within `PAIR_TOLERANCE` robust deviations of each other in the larger of their two cross distances, and, for a channel with several alternatives, that those alternatives look alike in the other units, which is why no pair can be chosen. A three-cycle (A shows B, B shows C, C shows A) stays three plain look-alikes (documented, tested). `PAIR_TOLERANCE` and its computation are unchanged. Tests only otherwise. + - **The swap tolerance is a recorded limit (owner decision of 24 November 2026).** The constant `PAIR_TOLERANCE` that decides between a clean `possible_channel_swap` and an `ambiguous_channel_swap` is now `ChannelIdentitySettings.pair_tolerance` (default 0.5, `PAIR_TOLERANCE` is that default): a finite number of at least 0 (a negative, NaN, infinite, boolean or non-number value is refused; at 0 only exact ties are ambiguous), written to the run manifest's `channel_identity` with the seven other limits and read back from it, so a verdict can be reproduced from the manifest. The ambiguous warning and the printed limits name the tolerance used. Limits recorded without `pair_tolerance` (written by this branch before this change) are read with 0.5, explicitly: earlier code used 0.5 as a constant, and no released version recorded these limits or gave `ambiguous_channel_swap` (the check is not in v0.8.0, whose manifests have no `channel_identity` and still read as None), so an absent key only means that no ambiguity rule was recorded. Every other key stays required. Like the other channel-check limits it has no command-line option or notebook field (the settings API only). The manifest version does not change. Contract §9 and §14.1, user guide. `tests/test_channel_identity.py`, `tests/test_channel_identity_pairs.py` (the near-tie cases with tolerances 0.3, 0.5 and 0.8), `tests/test_channel_identity_run.py`. - **Cached preview planes are keyed by the confirmed roles (#428).** `PreviewCache` keys held the path, fingerprint and coordinates but not the roles, so one file read as `ZCYX` and then `CZYX` showed the first reading's pixels. The key now holds the mapping's axes, roles and singleton roles (also for the discard after a rewrite). `tests/test_preview.py`. - **A view of fewer than one channel is refused before any read (#433).** `ViewRequest(shown=...)` and `header_channels(..., shown)` raise a `ValueError` naming the value when it is not a whole number of at least 1, instead of an `IndexError`, `AttributeError` or `ZeroDivisionError` after reading. Any whole number (`numbers.Integral`, so NumPy integers too) is accepted and kept as an `int`; `bool` is refused (`header_preview.checked_shown`). `tests/test_image_viewer.py`. - **A plane that cannot be read is the H&E tissue-mask card's and command's refusal (#469).** The preview and the write of the card, and `tissue-mask`, now catch `PlaneReadError` (`PlaneMemoryError`, `CompressionNotBoundedError`) and `OSError`: the card replaces "Computing the preview…" with the message and hides an earlier preview; the command prints the image's refusal and exits 1, without a traceback. `tests/test_notebook_tissue_mask.py`, `tests/test_cli_tissue_mask.py`. diff --git a/docs/contract.md b/docs/contract.md index b0dd7708..cf485703 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -276,7 +276,7 @@ interpretation. | `image_type` | `fluorescence` or `rgb`, the image type the user confirmed (§13); null when the run was given none, or absent in manifests written before it. Optional key: the manifest stays version 1. Changing it recomputes nothing. | | `channels_from_rgb_samples` | `true` when the C role is the RGB samples axis of images stored as RGB colour (§13), `false` otherwise; absent in manifests written before it. Optional key. | | `intensity_checks` | The limits of the intensity checks run on the table (§14): `IntensityCheckSettings.to_dict()` of the normalization brick (`library_version`, `outlier_limit`, `saturation_limit`, `min_images`); absent in manifests written before it. Optional key. Changing the limits recomputes nothing. | -| `channel_identity` | The limits of the channel-identity check run on the table (§14.1): `ChannelIdentitySettings.to_dict()` (`outlier_limit`, `min_reference`, `mad_floor`, `min_log_difference`, `swap_limit`, `swap_ratio`, `partner_ratio`, all required when present); null or absent in manifests written before it. Optional key: the manifest version does not change. Changing the limits recomputes nothing. | +| `channel_identity` | The limits of the channel-identity check run on the table (§14.1): `ChannelIdentitySettings.to_dict()` (`outlier_limit`, `min_reference`, `mad_floor`, `min_log_difference`, `swap_limit`, `swap_ratio`, `partner_ratio`, `pair_tolerance`, all required when present, except `pair_tolerance`: limits recorded without it, written before it was recorded (owner decision of 24 November 2026), are read with `pair_tolerance` 0.5, the constant of that code; no released version recorded these limits, and none gave `ambiguous_channel_swap`); null or absent in manifests written before it (v0.8.0 and earlier). Optional key: the manifest version does not change. Changing the limits recomputes nothing. | | `narrow_histogram_ranges` | The channel planes whose range check found the central range too narrow (§4), sorted by plane and channel: `relative_path`, `plane_id`, `channel` and the fields of the normalization brick's `RangeCheck` (`histogram_range`, `central_percentiles`, `central_bins`, `robust_quantiles`, `robust_limits`, `outside_robust_count`, `robust_central_bins`, `min_central_bins`). Empty when there are none; absent in manifests written before follow-up P6. Optional key: the manifest stays version 1. | | `conversion_record_sha256` | SHA-256 of the conversion record (`.morphobricks-conversion.json`) in the experiment root when the experiment is a tree of named-axis copies (design v0.4 §5, §17); null otherwise. `RunInputs` checks it (owner decision of 2 November 2026, plan question 59): a record changed or gone since the run is refused, as for `calibration_sha256`. A changed record changes no row (the copies are checked by their fingerprints like any image). | | `calibration_sha256` | SHA-256 of the output folder's `calibration.csv` as the run read it (§9.3); null when there was none (or absent in manifests written before PP-8). `RunInputs` checks it. | @@ -927,9 +927,9 @@ same image summaries (design `channel-identity-check-2026-11-21`, owner answers | Distance | `d(u, c -> c')`: root mean square of the robust z-scores of `u`'s `c` signature against the reference of `c'`. | | Reported | A unit channel is reported when `d(u, c -> c) > outlier_limit` and at least one component is more than `outlier_limit` robust deviations and at least `min_log_difference` from the reference (the components named as off: level, brightness, contrast). Only unit channels compared with a reference count as checked; with none, the summary says that no channel could be checked. | | `possible_channel_swap` | Either a mutual pair: `u`'s `c` is reported, its nearest other channel `c'` is one of `u`'s channels, `partner_ratio × d(u, c -> c') < d(u, c -> c)` and `partner_ratio × d(u, c' -> c) < d(u, c' -> c')`, both within `outlier_limit` (`u`'s `c'` reported or not): a candidate pair, whose strength is the larger of `d(u, c -> c')` and `d(u, c' -> c)` (smaller is stronger). The pairs are chosen greedily from the strongest, and a channel is in one pair at most (#395): one warning per chosen pair, "`c` and `c'` look swapped", with both channels' distances, naming the unit once. Or a clear look-alike of another channel `c'` of the unit, not in a chosen pair: `d(u, c -> c') <= swap_limit` and `swap_ratio × d(u, c -> c') < d(u, c -> c)` ("does not look like `c` but like `c'`"). Channel names and the order of the images never decide which pair is chosen. A cycle of three or more channels (A shows B's content, B shows C's, C shows A's) has no mutual pair: each channel keeps its own "does not look like `c` but like `c'`" warning (locked by a test). | -| `ambiguous_channel_swap` | When the strongest remaining candidate pair shares a channel with other remaining pairs of the unit (directly or through each other) whose strengths are within `PAIR_TOLERANCE` (0.5, a constant, not a recorded limit) of it, none of them is chosen: one warning naming every channel of the group, each with its own distance and its distances to the channels it could be swapped with, "look swapped in more than one way … no pair is named" (the pairs are "within 0.5 robust deviations of each other in the larger of their two cross distances", and a channel with several alternatives adds that those alternatives "look alike in the other units, which is why no pair can be chosen"); those channels are paired with nothing else. Check every channel named. | +| `ambiguous_channel_swap` | When the strongest remaining candidate pair shares a channel with other remaining pairs of the unit (directly or through each other) whose strengths are within `pair_tolerance` (a recorded limit, default 0.5; owner decision of 24 November 2026) of it, none of them is chosen: one warning naming every channel of the group, each with its own distance and its distances to the channels it could be swapped with, "look swapped in more than one way … no pair is named" (the pairs are "within 0.5 robust deviations of each other in the larger of their two cross distances", with the limits' `pair_tolerance` in place of 0.5, and a channel with several alternatives adds that those alternatives "look alike in the other units, which is why no pair can be chosen"); those channels are paired with nothing else. Check every channel named. | | `channel_unlike_others` | Every other reported unit channel: names the unit (`condition/biological repeat/technical repeat`), the channel, the components off and the distances; "Nearest channel: `c'`" when another channel's reference is nearer than its own, or "It looks like `c'`, a channel this unit does not have" for a clear look-alike of a channel the unit lacks (never called a swap). | -| Limits | `ChannelIdentitySettings`: `outlier_limit` 3.5, `min_reference` 3, `mad_floor` 0.2, `min_log_difference` 0.6 (natural-log units), `swap_limit` 1.0, `swap_ratio` 3.0, `partner_ratio` 2.0, chosen with a simulation (2 conditions × 4 units × 3 channels, between-unit variation of 10 % and 20 %; PR #364). With very noisy data (units differing by about 30 % per channel) false warnings become frequent: in that simulation 171 of 300 runs without any swap give a warning and 59 a false swap; read the warnings as prompts to look, never as verdicts. The run uses the defaults and records them in the manifest (`channel_identity`, §9, beside `intensity_checks`); other limits are applied by calling `check_channel_identity(result.intensity.summaries, settings)`, which recomputes nothing. | +| Limits | `ChannelIdentitySettings`: `outlier_limit` 3.5, `min_reference` 3, `mad_floor` 0.2, `min_log_difference` 0.6 (natural-log units), `swap_limit` 1.0, `swap_ratio` 3.0, `partner_ratio` 2.0, chosen with a simulation (2 conditions × 4 units × 3 channels, between-unit variation of 10 % and 20 %; PR #364), and `pair_tolerance` 0.5 (#395; finite and at least 0, at 0 only exact ties are ambiguous; half a robust deviation, below the spread of the references, not taken from that simulation). With very noisy data (units differing by about 30 % per channel) false warnings become frequent: in that simulation 171 of 300 runs without any swap give a warning and 59 a false swap; read the warnings as prompts to look, never as verdicts. The run uses the defaults and records them in the manifest (`channel_identity`, §9, beside `intensity_checks`); other limits are applied by calling `check_channel_identity(result.intensity.summaries, settings)`, which recomputes nothing. No limit, `pair_tolerance` included, has a command-line option or a notebook field: they are set through the settings API only. | | Run | `RunResult.channel_identity` (`ChannelIdentityReport`: signatures, findings, warnings, not checked, the number compared, pixel types and offsets) for a written table, None otherwise; its warnings are in the run report beside the intensity warnings and kept apart from `RunResult.issues`. | | Command line | `run` prints them after the intensity checks, grouped by kind with what to do, then what was not checked. | | Notebook | Under the intensity checks' plots, **Do the channels look like themselves?**: a status line (an information status when no channel could be checked) with the limits, the findings with what to do, what was not checked, and one plot of brightness against contrast (log scale) with one point per unit and channel, coloured and shaped by channel tag; a flagged point is circled and labelled with its unit; a possible swap has a dashed arrow from the centre of the reference the check used for that unit and channel to the point; a point of an ambiguous swap is labelled with every channel it could be swapped with, without an arrow. When nothing could be checked, the section stays and shows the status and why each unit channel was not checked, without a plot. Nothing is written. | diff --git a/docs/user_guide.md b/docs/user_guide.md index 9760be92..7d8cdae2 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -722,10 +722,16 @@ imaging unit's channels compared with the same channels of the other units of it (a treatment effect is not reported when the condition has at least 3 other units), with `channel_unlike_others`, `possible_channel_swap` (for example "channels DAPI and GFP look swapped") and `ambiguous_channel_swap` warnings (channels that look swapped in more than one -way the check cannot tell apart: it names them all and no pair; a cycle of three channels, A shows B, B shows C, C shows A, is not a swap and gives three "does not look like" warnings) and the channels it could not check; the notebook draws them under +way the check cannot tell apart, the pairs being within `pair_tolerance`, 0.5 by default, of each other: it names them all and no pair; a cycle of three channels, A shows B, B shows C, C shows A, is not a swap and gives three "does not look like" warnings) and the channels it could not check; the notebook draws them under **Do the channels look like themselves?**. A swap made in every unit of a condition is not found. Warnings only: nothing is changed or blocked. +The channel check's limits, `pair_tolerance` included, are recorded in `run_manifest.json` +(`channel_identity`). They have no command-line option or notebook field: to apply others, call +`check_channel_identity(result.intensity.summaries, ChannelIdentitySettings(pair_tolerance=0.8))` +(Python, both from `morphobricks_preprocessing.channel_identity`), which recomputes nothing. A manifest whose limits lack `pair_tolerance` (written +before it was recorded) is read with 0.5, the value that code used. + Read the warnings as prompts to look, not as verdicts. With very noisy data (units that differ by about 30 % per channel) false warnings are frequent: in a simulation, 171 of 300 runs without any swap gave a warning and 59 a false swap. Images stored as floating-point numbers diff --git a/src/morphobricks_preprocessing/channel_identity.py b/src/morphobricks_preprocessing/channel_identity.py index 16434621..0a36074d 100644 --- a/src/morphobricks_preprocessing/channel_identity.py +++ b/src/morphobricks_preprocessing/channel_identity.py @@ -420,12 +420,12 @@ def _pairs( return sorted(pairs) -def _choose(pairs: list[_Pair]) -> tuple[list[_Pair], list[list[_Pair]]]: +def _choose(pairs: list[_Pair], tolerance: float) -> tuple[list[_Pair], list[list[_Pair]]]: """Choose the mutual pairs by strength; return the pairs kept and the ambiguous groups. Greedy from the strongest pair (smallest strength): a channel is in one pair at most. When a remaining pair sharing a channel with the strongest one (directly or through each other) - is within :data:`PAIR_TOLERANCE` of its strength, none of them is chosen: they form one + is within ``pair_tolerance`` of its strength, none of them is chosen: they form one ambiguous group, and its channels are not paired with anything else. Channel names and input order never decide (#395). """ @@ -439,7 +439,7 @@ def _choose(pairs: list[_Pair]) -> tuple[list[_Pair], list[list[_Pair]]]: close = [ p for p in remaining - if p.unit == first.unit and p.strength <= first.strength + PAIR_TOLERANCE + if p.unit == first.unit and p.strength <= first.strength + tolerance ] group, channels = [first], set(first.channels) grown = True @@ -472,7 +472,7 @@ def _findings( Otherwise a channel that clearly looks like another channel of its unit is a swap. """ findings = {key: f for key, place in places.items() if (f := _finding(place, settings))} - kept, groups = _choose(_pairs(places, findings, settings)) + kept, groups = _choose(_pairs(places, findings, settings), settings.pair_tolerance) for pair in kept: a, b = ((pair.unit, c) for c in pair.channels) items = { diff --git a/src/morphobricks_preprocessing/channel_identity_model.py b/src/morphobricks_preprocessing/channel_identity_model.py index 49e8bf72..cd3cf265 100644 --- a/src/morphobricks_preprocessing/channel_identity_model.py +++ b/src/morphobricks_preprocessing/channel_identity_model.py @@ -21,17 +21,19 @@ AMBIGUOUS_CHANNEL_SWAP = "ambiguous_channel_swap" CHANNEL_IDENTITY_CODES = (POSSIBLE_CHANNEL_SWAP, AMBIGUOUS_CHANNEL_SWAP, CHANNEL_UNLIKE_OTHERS) PAIR_TOLERANCE = 0.5 -"""Two mutual pairs sharing a channel whose strengths (the larger of a pair's two cross -distances) differ by at most this much cannot be told apart: the channels are an ambiguous -swap, never one pair picked (#395). Half a robust deviation (root mean square), below the -spread of the references themselves (``mad_floor``, ``swap_limit``).""" +"""The default of :attr:`ChannelIdentitySettings.pair_tolerance` (#395), and the value read +for a recorded ``channel_identity`` without ``pair_tolerance`` (see +:meth:`ChannelIdentitySettings.from_dict`). Half a robust deviation (root mean square), below +the spread of the references themselves (``mad_floor``, ``swap_limit``).""" KEY = "channel_identity" """The manifest key of the limits, beside ``intensity_checks``.""" COMPONENTS = ("level", "bright", "spread") _FLOATS = ("outlier_limit", "mad_floor", "min_log_difference", "swap_limit", "swap_ratio") _FLOATS += ("partner_ratio",) _KEYS = ("outlier_limit", "min_reference", "mad_floor", "min_log_difference") -_KEYS += ("swap_limit", "swap_ratio", "partner_ratio") +_KEYS += ("swap_limit", "swap_ratio", "partner_ratio", "pair_tolerance") +_UNTIL_PAIR_TOLERANCE = frozenset(_KEYS) - {"pair_tolerance"} +"""The keys recorded before ``pair_tolerance`` was (owner decision of 24 November 2026).""" @dataclass(frozen=True) @@ -67,6 +69,12 @@ class ChannelIdentitySettings: For a mutual swap, how many times nearer the other channel's reference than its own each of the two channels must be, so a normal channel close to a failed one is not named half of a swap; default 2.0. + pair_tolerance + Two candidate mutual pairs of a unit sharing a channel whose strengths (the larger of a + pair's two cross distances) differ by at most this much cannot be told apart: their + channels are one ``ambiguous_channel_swap``, never one pair picked (#395); a finite + number of at least 0, default 0.5 (:data:`PAIR_TOLERANCE`). At 0 only exact ties are + ambiguous. Raises ------ @@ -81,6 +89,7 @@ class ChannelIdentitySettings: swap_limit: float = 1.0 swap_ratio: float = 3.0 partner_ratio: float = 2.0 + pair_tolerance: float = PAIR_TOLERANCE def __post_init__(self) -> None: for name in _FLOATS: @@ -97,6 +106,14 @@ def __post_init__(self) -> None: if isinstance(count, bool) or not isinstance(count, (int, np.integer)) or count < 1: raise ValueError(f"min_reference must be a whole number of at least 1; got {count!r}.") object.__setattr__(self, "min_reference", int(count)) + tolerance = self.pair_tolerance + if isinstance(tolerance, bool) or not isinstance(tolerance, (int, float, np.number)): + raise ValueError(f"pair_tolerance must be a number; got {tolerance!r}.") + if not (math.isfinite(tolerance) and tolerance >= 0): + raise ValueError( + f"pair_tolerance must be a finite number of at least 0; got {tolerance!r}." + ) + object.__setattr__(self, "pair_tolerance", float(tolerance)) def to_dict(self) -> dict[str, Any]: """Return the limits as JSON-compatible data, for the manifest.""" @@ -106,15 +123,26 @@ def to_dict(self) -> dict[str, Any]: def from_dict(cls, data: Mapping[str, Any]) -> ChannelIdentitySettings: """Read limits written by :meth:`to_dict`; every key is required, none is defaulted. + One documented exception: limits recorded without ``pair_tolerance`` (written before + it was recorded, owner decision of 24 November 2026) are read with ``pair_tolerance`` + 0.5 (:data:`PAIR_TOLERANCE`), because earlier code used 0.5 as a constant. No released + version wrote such limits with a pair rule (the check is not in v0.8.0 or earlier, whose + manifests have no ``channel_identity`` at all), and none produced + ``ambiguous_channel_swap``: the rule is new with the tolerance, so the absent key means + only that no ambiguity rule was recorded. Every other key stays required. + Raises ------ ValueError For a missing or unknown key, or a value outside its range. """ - if not isinstance(data, Mapping) or set(data) != set(_KEYS): + keys = set(data) if isinstance(data, Mapping) else None + if keys is None or keys not in (set(_KEYS), _UNTIL_PAIR_TOLERANCE): found = sorted(data) if isinstance(data, Mapping) else data raise ValueError(f"Expected the channel identity limits {list(_KEYS)}; got {found!r}.") - return cls(**{name: data[name] for name in _KEYS}) + values = {name: data[name] for name in _KEYS if name in data} + values.setdefault("pair_tolerance", PAIR_TOLERANCE) # absent: the earlier constant + return cls(**values) def settings_entry(settings: ChannelIdentitySettings | None) -> dict[str, Any] | None: diff --git a/src/morphobricks_preprocessing/channel_identity_text.py b/src/morphobricks_preprocessing/channel_identity_text.py index 7a4f2b11..5798a2bb 100644 --- a/src/morphobricks_preprocessing/channel_identity_text.py +++ b/src/morphobricks_preprocessing/channel_identity_text.py @@ -12,7 +12,6 @@ AMBIGUOUS_CHANNEL_SWAP, CHANNEL_IDENTITY_CODES, CHANNEL_UNLIKE_OTHERS, - PAIR_TOLERANCE, POSSIBLE_CHANNEL_SWAP, ChannelFinding, ChannelIdentityReport, @@ -62,7 +61,7 @@ def finding_issues( if found.code == AMBIGUOUS_CHANNEL_SWAP: group = _group(found, by_place) done.update((f.unit, f.channel) for f in group) - message = _ambiguous_message(group) + message = _ambiguous_message(group, settings.pair_tolerance) elif partner is not None: done.add((partner.unit, partner.channel)) message = _swap_message(found, partner) @@ -92,8 +91,11 @@ def _names(channels: Sequence[str]) -> str: return channels[0] if len(channels) == 1 else f"{', '.join(channels[:-1])} and {channels[-1]}" -def _ambiguous_message(group: Sequence[ChannelFinding]) -> str: - """Word an ambiguous swap: every channel, its own distance and those to its alternatives.""" +def _ambiguous_message(group: Sequence[ChannelFinding], tolerance: float) -> str: + """Word an ambiguous swap: every channel, its own distance and those to its alternatives. + + ``tolerance`` is the limits' ``pair_tolerance``, the one the group was found with. + """ first = group[0] others = _others(any(f.across_conditions for f in group)) parts = [] @@ -107,7 +109,7 @@ def _ambiguous_message(group: Sequence[ChannelFinding]) -> str: text = ( f"In unit {first.unit.label}, channels {_names([f.channel for f in group])} look " f"swapped in more than one way: compared with {others}, {'; '.join(parts)}. The " - f"possible pairs are within {PAIR_TOLERANCE:g} robust deviations of each other in the " + f"possible pairs are within {tolerance:g} robust deviations of each other in the " "larger of their two cross distances, so no pair is named." ) for found in group: @@ -172,9 +174,10 @@ def describe_settings(settings: ChannelIdentitySettings) -> str: f"least {settings.min_log_difference:g} log units, references of at least " f"{plural(settings.min_reference, 'other unit')}, robust spread at least " f"{settings.mad_floor:g} log units; a swap when two channels of a unit look like each " - f"other ({settings.partner_ratio:g} times nearer each other), or one is at distance " - f"{settings.swap_limit:g} or less from another channel and {settings.swap_ratio:g} times " - "nearer it than its own" + f"other ({settings.partner_ratio:g} times nearer each other; pairs within " + f"{settings.pair_tolerance:g} of each other in strength are not told apart), or one is " + f"at distance {settings.swap_limit:g} or less from another channel and " + f"{settings.swap_ratio:g} times nearer it than its own" ) diff --git a/tests/test_channel_identity.py b/tests/test_channel_identity.py index 09693469..85f267e7 100644 --- a/tests/test_channel_identity.py +++ b/tests/test_channel_identity.py @@ -14,6 +14,7 @@ Unit, channel_identity_text, check_channel_identity, + describe_settings, recorded_settings, settings_entry, ) @@ -288,6 +289,11 @@ def test_the_limits_are_typed_and_recorded_exactly(): outlier_limit=5, min_reference=4, mad_floor=0.1, min_log_difference=1, swap_limit=1.5 ) assert recorded_settings(settings_entry(settings)) == settings + tolerant = ChannelIdentitySettings(pair_tolerance=0.8) + assert settings_entry(tolerant)["pair_tolerance"] == 0.8 + assert recorded_settings(settings_entry(tolerant)) == tolerant + assert settings_entry(ChannelIdentitySettings())["pair_tolerance"] == 0.5 + assert "pairs within 0.8 of each other in strength" in describe_settings(tolerant) assert settings_entry(None) is None and recorded_settings(None) is None with pytest.raises(ValueError, match="channel identity limits"): ChannelIdentitySettings.from_dict({"outlier_limit": 3.5}) # never defaulted @@ -298,6 +304,12 @@ def test_the_limits_are_typed_and_recorded_exactly(): {"min_log_difference": -1}, {"swap_ratio": 0.5}, {"partner_ratio": 0.9}, + {"pair_tolerance": -0.1}, + {"pair_tolerance": float("nan")}, + {"pair_tolerance": float("inf")}, + {"pair_tolerance": True}, + {"pair_tolerance": "0.5"}, + {"pair_tolerance": None}, ) for bad in bad_limits: with pytest.raises(ValueError): @@ -308,6 +320,31 @@ def test_the_limits_are_typed_and_recorded_exactly(): assert check_channel_identity(found, loose).findings == () +def test_limits_recorded_without_pair_tolerance_read_as_the_earlier_constant(): + """Owner decision of 24 November 2026: absent ``pair_tolerance`` is 0.5, documented. + + Earlier code used 0.5 as a constant and no released version recorded these limits, so the + absent key is read as that constant; every other key is still required, and an unknown or + invalid one is refused. + """ + entry = settings_entry(ChannelIdentitySettings(outlier_limit=4)) + assert entry is not None + del entry["pair_tolerance"] + read = recorded_settings(entry) + assert read == ChannelIdentitySettings(outlier_limit=4, pair_tolerance=0.5) + assert read.pair_tolerance == 0.5 and isinstance(read.pair_tolerance, float) + assert ChannelIdentitySettings(pair_tolerance=0).pair_tolerance == 0.0 # exact ties only + for bad in ( + {k: v for k, v in entry.items() if k != "partner_ratio"}, # only pair_tolerance may lack + {**entry, "pair_tolerance": 0.5, "pair_rule": 1}, + {**entry, "pair_tolerance": -1}, + {**entry, "pair_tolerance": float("nan")}, + {**entry, "pair_tolerance": None}, + ): + with pytest.raises(ValueError): + recorded_settings(bad) + + # Mutation checks: the tests above fail when the reference is not the other units. diff --git a/tests/test_channel_identity_pairs.py b/tests/test_channel_identity_pairs.py index d2880827..869e1300 100644 --- a/tests/test_channel_identity_pairs.py +++ b/tests/test_channel_identity_pairs.py @@ -9,6 +9,7 @@ AMBIGUOUS_CHANNEL_SWAP, PAIR_TOLERANCE, POSSIBLE_CHANNEL_SWAP, + ChannelIdentitySettings, Unit, channel_identity_text, check_channel_identity, @@ -100,14 +101,17 @@ def test_tied_mutual_pairs_are_one_ambiguous_finding(): assert f"in more than one way ({AMBIGUOUS_CHANNEL_SWAP}, 1):" in text -def strengths_of(monkeypatch, summaries): +def strengths_of(monkeypatch, summaries, settings=None): """Run the check and return ``({channels: strength}, report)`` of the candidate pairs.""" seen = [] choose = channel_identity._choose - monkeypatch.setattr( - channel_identity, "_choose", lambda pairs: (seen.append(pairs), choose(pairs))[1] - ) - report = check_channel_identity(summaries) + + def spy(pairs, tolerance): + seen.append(pairs) + return choose(pairs, tolerance) + + monkeypatch.setattr(channel_identity, "_choose", spy) + report = check_channel_identity(summaries, settings) return {p.channels: p.strength for p in seen[0]}, report @@ -124,7 +128,7 @@ def faint_scaled(factor): def test_a_near_tie_just_inside_the_tolerance_is_ambiguous(monkeypatch): - """#395: strengths 0 and about 0.46 (within PAIR_TOLERANCE of each other) are one group.""" + """#395: strengths 0 and about 0.46 (within the default pair_tolerance) are one group.""" strengths, report = strengths_of(monkeypatch, faint_scaled(1.14)) assert strengths[("bright", "faint")] == pytest.approx(0.0, abs=1e-6) assert 0.40 < strengths[("bright", "dim")] < PAIR_TOLERANCE @@ -148,6 +152,46 @@ def test_a_near_tie_just_outside_the_tolerance_is_a_clean_swap(monkeypatch): assert len(swaps) == 1 and "channels bright and faint look swapped" in swaps[0] +CLEAN_TIE_BREAK = { + "dim": (POSSIBLE_CHANNEL_SWAP, "bright", False), + "bright": (POSSIBLE_CHANNEL_SWAP, "faint", True), + "faint": (POSSIBLE_CHANNEL_SWAP, "bright", True), +} + + +@pytest.mark.parametrize( + ("factor", "tolerance", "ambiguous"), + [ + (1.14, 0.3, False), # strengths 0 and about 0.46 + (1.14, 0.5, True), + (1.14, 0.8, True), + (1.10, 0.3, False), # strengths 0 and about 0.63 + (1.10, 0.5, False), + (1.10, 0.8, True), + ], +) +def test_the_recorded_pair_tolerance_decides_a_near_tie(monkeypatch, factor, tolerance, ambiguous): + """Owner decision of 24 November 2026: ``pair_tolerance`` is a recorded limit, not a constant. + + The same summaries give a clean swap or an ambiguous one by the limits' tolerance only, + and the ambiguous warning names the tolerance it was found with. + """ + settings = ChannelIdentitySettings(pair_tolerance=tolerance) + strengths, report = strengths_of(monkeypatch, faint_scaled(factor), settings) + assert strengths[("bright", "faint")] == pytest.approx(0.0, abs=1e-6) + assert (strengths[("bright", "dim")] <= tolerance) == ambiguous + assert report.settings.pair_tolerance == tolerance + found = {f.channel: (f.code, f.nearest, f.mutual) for f in report.findings} + if not ambiguous: + assert found == CLEAN_TIE_BREAK + return + assert {c: code for c, (code, _, _) in found.items()} == { + c: AMBIGUOUS_CHANNEL_SWAP for c in ROLE_REF + } + (issue,) = report.validation_issues() + assert f"within {tolerance:g} robust deviations of each other" in issue.message + + def units_off(shown_by_unit, ref, conditions=("ctrl", "treated"), per_condition=6): """Units of every condition showing ``ref``, except the units in ``shown_by_unit``.""" units = [Unit(c, "rep1", f"t{i}") for c in conditions for i in range(per_condition)] diff --git a/tests/test_channel_identity_run.py b/tests/test_channel_identity_run.py index 5b2f010b..cdc105c5 100644 --- a/tests/test_channel_identity_run.py +++ b/tests/test_channel_identity_run.py @@ -18,6 +18,7 @@ from morphobricks_preprocessing.description_file import DESCRIPTION_FILENAME from morphobricks_preprocessing.description_write import canonical_bytes from morphobricks_preprocessing.discovery import default_output_folder +from morphobricks_preprocessing.manifest import ManifestFormatError from morphobricks_preprocessing.run.preflight import preflight from tiff_tree import write_data @@ -116,3 +117,33 @@ def test_the_notebook_shows_the_plot_and_findings(swapped_run): assert bytes(view.plot.value).startswith(b"\x89PNG") panel.clear() assert not ui.is_visible(view.box) and view.plot.value == b"" + + +def test_the_manifest_records_pair_tolerance_and_reads_older_limits(swapped_run): + """Owner decision of 24 November 2026: ``pair_tolerance`` is in the manifest's limits. + + A manifest whose limits lack it (written before it was recorded) reads as 0.5, the + earlier constant; one without ``channel_identity`` (v0.8.0 and earlier) reads as None; an + invalid value is refused when the manifest is read. + """ + _, result = swapped_run + path = result.manifest_path + data = json.loads(path.read_text(encoding="utf-8")) + assert data["channel_identity"]["pair_tolerance"] == 0.5 + + def read_with(edit): + edited = json.loads(json.dumps(data)) + edit(edited) + path.write_text(json.dumps(edited), encoding="utf-8") + return read_manifest(path) + + def tolerance(value): + return lambda d: d["channel_identity"].__setitem__("pair_tolerance", value) + + assert read_with(tolerance(0.8)).channel_identity == ChannelIdentitySettings(pair_tolerance=0.8) + older = read_with(lambda d: d["channel_identity"].pop("pair_tolerance")) + assert older.channel_identity == ChannelIdentitySettings(pair_tolerance=0.5) + assert read_with(lambda d: d.pop("channel_identity")).channel_identity is None + for bad in (-0.5, None, "0.5"): + with pytest.raises(ManifestFormatError): + read_with(tolerance(bad))