cellquant / tests /test_data.py
stevafernandes's picture
Deploy CellQuant
812b6ee verified
Raw History Blame Contribute Delete
1.77 kB
import numpy as np
from cellquant.annotations import RasterAnnotation
from cellquant.data import AugConfig, PatchSampler, make_targets
def _raster():
inst = np.zeros((64, 64), np.int32)
inst[10:30, 10:30] = 1
inst[30:50, 30:50] = 2 # touches instance 1 at a corner
nos = np.zeros((64, 64), np.int32)
nos[20:23, 20:23] = 1
nos[5:7, 50:52] = 2
return RasterAnnotation(inst, ["", "Cell, Nostril, Antibody +", "Cell, Antibody -"], nos,
["", "Nostril in Nucleus", "Nostril External of Nucleus"])
def test_make_targets_layout():
T = make_targets(_raster())
assert set(np.unique(T["cell3"])) == {0, 1, 2}
assert ((T["cell3"] > 0) == (T["cellmask"] > 0)).all()
# border ring is 3 px wide: a 20x20 square has 20*20 - 14*14 = 204 border px
assert int((T["cell3"][10:30, 10:30] == 2).sum()) == 204
assert T["dist"].shape == T["cell3"].shape and T["dist"].dtype == np.float32
assert T["antibody"][15, 15] == 1 and T["antibody"][40, 40] == 0
assert T["cellnos"][15, 15] == 1 and T["cellnos"][40, 40] == 0
assert T["nos3"][21, 21] == 1 and T["nos3"][5, 50] == 2 and T["nos3"][0, 0] == 0
def test_sampler_batch_shapes_and_reproducibility():
img = (np.random.default_rng(0).random((64, 64, 3)) * 255).astype(np.uint8)
T = make_targets(_raster())
cfg = AugConfig(crop=32)
a = PatchSampler([img], [T], cfg, seed=3).batch(2)
b = PatchSampler([img], [T], cfg, seed=3).batch(2)
x, t = a
assert x.shape == (2, 3, 32, 32) and x.min() >= 0 and x.max() <= 1
assert t["cell3"].shape == (2, 32, 32) and t["cell3"].dtype.is_floating_point is False
assert np.allclose(x.numpy(), b[0].numpy())
assert all(np.array_equal(t[k].numpy(), b[1][k].numpy()) for k in t)