"""Regression tests for the defects found in the adversarial review.""" import os import zipfile import numpy as np import pytest import tifffile from PIL import Image from cellquant.annotations import discover, load_image, normalized_name, short_keys, to_rgb_uint8 from cellquant.data import AugConfig, Prefetcher, make_targets from cellquant.annotations import RasterAnnotation from cellquant.metrics import match_by_iou from cellquant.postprocess import PostConfig, _fill_and_filter, analyze XML = """ 1.11 """ def _rgb(h=64, w=64): a = np.zeros((h, w, 3), np.uint8) a[..., 0], a[..., 1], a[..., 2] = 200, 100, 50 return a def test_channel_per_page_tif_loads_three_channels(tmp_path): rgb = _rgb() p1 = tmp_path / "ij.tif" tifffile.imwrite(str(p1), np.moveaxis(rgb, -1, 0), imagej=True, metadata={"axes": "CYX"}) p2 = tmp_path / "ome.ome.tif" tifffile.imwrite(str(p2), np.moveaxis(rgb, -1, 0), ome=True, metadata={"axes": "CYX"}) for p in (p1, p2): a = load_image(str(p)) assert a.shape == (64, 64, 3) assert a[1, 1].tolist() == [200, 100, 50], str(p) def test_plain_tif_still_loads_and_large_stack_refused(tmp_path): p = tmp_path / "plain.tif" tifffile.imwrite(str(p), _rgb()) assert load_image(str(p))[0, 0].tolist() == [200, 100, 50] stack = tmp_path / "stack.tif" tifffile.imwrite(str(stack), np.zeros((7, 32, 32), np.uint8), imagej=True, metadata={"axes": "ZYX"}) with pytest.raises(ValueError): load_image(str(stack)) def test_lzw_tif_via_pillow_fallback_or_codecs(tmp_path): p = tmp_path / "lzw.tif" Image.fromarray(_rgb()).save(str(p), compression="tiff_lzw") assert load_image(str(p))[2, 2].tolist() == [200, 100, 50] def test_palette_png_converted_to_rgb(tmp_path): p = tmp_path / "pal.png" Image.fromarray(_rgb()).convert("P", palette=Image.ADAPTIVE, colors=4).save(str(p)) a = load_image(str(p)) assert a.shape == (64, 64, 3) assert not (np.array_equal(a[..., 0], a[..., 1]) and np.array_equal(a[..., 1], a[..., 2])) def test_16bit_scaling_ignores_single_saturated_pixel(): a = np.full((64, 64, 3), 1000, np.uint16) b = a.copy() b[0, 0, :] = 65535 ua, ub = to_rgb_uint8(a), to_rgb_uint8(b) assert ua[10, 10, 0] == 255 and ub[10, 10, 0] == 255 # the one hot pixel does not change the gain assert to_rgb_uint8(np.full((8, 8, 3), 0.5, np.float32))[0, 0, 0] in (127, 128) def test_enclosed_instance_survives_and_ids_are_contiguous(): inst = np.zeros((40, 40), np.int32) yy, xx = np.mgrid[:40, :40] ring = ((yy - 20) ** 2 + (xx - 20) ** 2 <= 15 ** 2) & ((yy - 20) ** 2 + (xx - 20) ** 2 > 8 ** 2) inner = (yy - 20) ** 2 + (xx - 20) ** 2 <= 6 ** 2 inst[ring] = 1 inst[inner] = 2 out = _fill_and_filter(inst, min_area=5) ids = np.unique(out) assert ids.tolist() == [0, 1, 2] assert out[20, 20] == 2 and out[20, 7] == 1 # the 2-px moat between ring and inner disc is background in the input and gets filled into the ring assert out[20, 13] == 1 # analyze() must not crash on such a map either h = w = 40 p_cell = np.zeros((3, h, w), np.float32) p_cell[1][inner] = 0.9 p_cell[1][ring] = 0.9 p_cell[2] = 0 p_cell[0] = 1 - p_cell[1] probs = {"cell": p_cell, "antibody": np.zeros((h, w), np.float32), "cellnos": np.zeros((h, w), np.float32), "nos": np.stack([np.ones((h, w)), np.zeros((h, w)), np.zeros((h, w))]).astype(np.float32)} res = analyze(probs, PostConfig(min_cell_area=5)) assert len(res.cells) == int(res.cell_inst.max()) def test_match_by_iou_prefers_number_of_valid_matches(): # GT A overlaps pred X with IoU 0.6 and pred Y with IoU 0.45; GT B overlaps X with 0.45. # Summed-IoU assignment would pick (A,Y)+(B,X)=0.9 < (A,X)=0.6 ... make the sums favour the wrong choice: gt = np.zeros((30, 60), np.int32) pred = np.zeros((30, 60), np.int32) gt[0:10, 0:20] = 1 # A: 200 px gt[10:20, 0:20] = 2 # B: 200 px pred[0:10, 0:20] = 1 # X == A exactly (IoU 1.0 with A) pred[5:15, 0:20] = 2 # Y straddles A and B (IoU 100/300 = 0.33 with each) pred[0:10, 0:20] = 1 # X overwrites the top of Y m = match_by_iou(gt, pred, 0.5) assert (1, 1) in [(g, p) for g, p, _ in m] def test_short_keys_disambiguate_wells(): names = ["C110 F 35D SC Iba W001 - Focused EDF Document_RGB copy.tif", "C110 F 35D SC Iba W003 - Focused EDF Document_RGB.tif", "F99 M 35D SC Iba W004 - Focused EDF Document_RGB.tif"] assert short_keys(names) == ["C110_W001", "C110_W003", "F99"] assert normalized_name("F114 F 35D SC Iba W002 - Focused EDF Document_RGB copy (1).tif") == "f114 f 35d sc iba w002 - focused edf document_rgb" def test_discover_two_sections_same_animal_and_size_check(tmp_path): for n in ("C110 F 35D SC Iba W001 - RGB.png", "C110 F 35D SC Iba W003 - RGB.png"): Image.fromarray(np.zeros((40, 50, 3), np.uint8)).save(tmp_path / n) for i, n in enumerate(("C110 F 35D SC Iba W001 - RGB copy.tif", "C110 F 35D SC Iba W003 - RGB.tif")): with zipfile.ZipFile(tmp_path / f"ann{i}.zip", "w") as zf: zf.writestr("annotations.xml", XML.format(name=n, w=50, h=40)) samples, unann = discover(str(tmp_path), verbose=False) assert [s.key for s in samples] == ["C110_W001", "C110_W003"] and unann == [] # a mismatching canvas is refused with zipfile.ZipFile(tmp_path / "ann0.zip", "w") as zf: zf.writestr("annotations.xml", XML.format(name="C110 F 35D SC Iba W001 - RGB.tif", w=500, h=400)) with pytest.raises(ValueError): discover(str(tmp_path), verbose=False) def test_discover_refuses_two_different_images_with_same_name(tmp_path): Image.fromarray(np.zeros((40, 50, 3), np.uint8)).save(tmp_path / "K1 a - RGB.png") Image.fromarray(np.ones((40, 50, 3), np.uint8)).save(tmp_path / "K1 a - RGB copy.png") with zipfile.ZipFile(tmp_path / "ann.zip", "w") as zf: zf.writestr("annotations.xml", XML.format(name="K1 a - RGB.png", w=50, h=40)) with pytest.raises(ValueError): discover(str(tmp_path), verbose=False) def test_prefetcher_is_deterministic(): inst = np.zeros((64, 64), np.int32) inst[10:30, 10:30] = 1 R = RasterAnnotation(inst, ["", "Cell, Antibody +"], np.zeros((64, 64), np.int32), [""]) img = (np.random.default_rng(0).random((64, 64, 3)) * 255).astype(np.uint8) T = make_targets(R) def stream(seed): pf = Prefetcher([img], [T], AugConfig(crop=32), batch=2, seed=seed, workers=3, depth=6) out = [pf.next()[0].numpy().copy() for _ in range(9)] pf.close() return out a, b = stream(4), stream(4) assert all(np.array_equal(x, y) for x, y in zip(a, b)) assert not all(np.array_equal(x, y) for x, y in zip(a, stream(5)))