|
| 1 | +import os |
| 2 | +import tempfile |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +import mrcfile |
| 6 | +import pytest |
| 7 | + |
| 8 | +from partinet.process_utils.guided_denoiser import denoise, transform, standard_scaler |
| 9 | + |
| 10 | + |
| 11 | +def _write_temp_mrc(array: np.ndarray, dtype: np.dtype) -> str: |
| 12 | + """Write ``array`` to a temporary .mrc file and return its path.""" |
| 13 | + fd, path = tempfile.mkstemp(suffix=".mrc") |
| 14 | + os.close(fd) |
| 15 | + with mrcfile.new(path, overwrite=True) as mrc: |
| 16 | + mrc.set_data(array.astype(dtype)) |
| 17 | + return path |
| 18 | + |
| 19 | + |
| 20 | +@ pytest.mark.parametrize("dtype", [np.uint16, np.int16, np.float32]) |
| 21 | +def test_denoise_handles_various_dtypes(dtype): |
| 22 | + """The ``denoise`` pipeline should accept 16-bit and 32-bit inputs without |
| 23 | + throwing OpenCV kernel-type errors (issue #41). |
| 24 | + """ |
| 25 | + data = (np.random.rand(32, 32) * 255).astype(dtype) |
| 26 | + path = _write_temp_mrc(data, dtype) |
| 27 | + |
| 28 | + try: |
| 29 | + out = denoise(path) |
| 30 | + assert isinstance(out, np.ndarray) |
| 31 | + # our pipeline always returns 8-bit data |
| 32 | + assert out.dtype == np.uint8 |
| 33 | + assert out.shape == data.shape |
| 34 | + finally: |
| 35 | + os.unlink(path) |
| 36 | + |
| 37 | + |
| 38 | +def test_transform_stable_when_constant(): |
| 39 | + """``transform`` should not divide by zero if image has no contrast.""" |
| 40 | + arr = np.full((4, 4), 100, dtype=np.float32) |
| 41 | + out = transform(arr) |
| 42 | + assert out.dtype == np.uint8 |
| 43 | + assert np.all(out == 0) |
| 44 | + |
| 45 | + |
| 46 | +def test_standard_scaler_normalises(): |
| 47 | + arr = np.arange(25, dtype=np.float32).reshape(5, 5) |
| 48 | + scaled = standard_scaler(arr) |
| 49 | + assert scaled.dtype == np.uint8 |
| 50 | + # scaled values should not all be equal |
| 51 | + assert scaled.std() > 0 |
0 commit comments