Skip to content

Commit

Permalink
Decrease verbosity of unit tests (#1201)
Browse files Browse the repository at this point in the history
  • Loading branch information
fepegar authored Sep 22, 2024
1 parent 4075273 commit 7bb2b4c
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 11 deletions.
8 changes: 8 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,11 @@ markers = [
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
"serial",
]

filterwarnings = [
# Ignore SimpleITK Swig warnings
"ignore:builtin type .* has no __module__ attribute",
"ignore:Casting complex values to real discards the imaginary part",
# Raised by SimpleITK on CI
"ignore:invalid escape sequence",
]
19 changes: 12 additions & 7 deletions src/torchio/data/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,23 +220,25 @@ def write_matrix(matrix: torch.Tensor, path: TypePath):
_write_niftyreg_matrix(matrix, path)


def _to_itk_convention(matrix):
def _to_itk_convention(matrix: TypeData) -> np.ndarray:
"""RAS to LPS."""
if isinstance(matrix, torch.Tensor):
matrix = matrix.numpy()
matrix = np.dot(FLIPXY_44, matrix)
matrix = np.dot(matrix, FLIPXY_44)
matrix = np.linalg.inv(matrix)
return matrix


def _from_itk_convention(matrix):
def _from_itk_convention(matrix: TypeData) -> np.ndarray:
"""LPS to RAS."""
matrix = np.dot(matrix, FLIPXY_44)
matrix = np.dot(FLIPXY_44, matrix)
matrix = np.linalg.inv(matrix)
return matrix


def _read_itk_matrix(path):
def _read_itk_matrix(path: TypePath) -> torch.Tensor:
"""Read an affine transform in ITK's .tfm format."""
transform = sitk.ReadTransform(str(path))
parameters = transform.GetParameters()
Expand All @@ -250,28 +252,31 @@ def _read_itk_matrix(path):
return torch.as_tensor(homogeneous_matrix_ras)


def _write_itk_matrix(matrix, tfm_path):
def _write_itk_matrix(matrix: TypeData, tfm_path: TypePath) -> None:
"""The tfm file contains the matrix from floating to reference."""
transform = _matrix_to_itk_transform(matrix)
transform.WriteTransform(str(tfm_path))


def _matrix_to_itk_transform(matrix, dimensions=3):
def _matrix_to_itk_transform(
matrix: TypeData,
dimensions: int = 3,
) -> sitk.AffineTransform:
matrix = _to_itk_convention(matrix)
rotation = matrix[:dimensions, :dimensions].ravel().tolist()
translation = matrix[:dimensions, 3].tolist()
transform = sitk.AffineTransform(rotation, translation)
return transform


def _read_niftyreg_matrix(trsf_path):
def _read_niftyreg_matrix(trsf_path: TypePath) -> torch.Tensor:
"""Read a NiftyReg matrix and return it as a NumPy array."""
matrix = np.loadtxt(trsf_path)
matrix = np.linalg.inv(matrix)
return torch.as_tensor(matrix)


def _write_niftyreg_matrix(matrix, txt_path):
def _write_niftyreg_matrix(matrix: TypeData, txt_path: TypePath) -> None:
"""Write an affine transform in NiftyReg's .txt format (ref -> flo)"""
matrix = np.linalg.inv(matrix)
np.savetxt(txt_path, matrix, fmt='%.8f')
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from pathlib import Path
from typing import Callable
from typing import Dict
from typing import Iterable
from typing import Optional
from typing import Sequence
from typing import Tuple
Expand Down Expand Up @@ -107,6 +108,8 @@ def train(
mask_path: Optional[Union[Sequence[TypePath], TypePath]] = None,
masking_function: Optional[Callable] = None,
output_path: Optional[TypePath] = None,
*,
progress: bool = True,
) -> np.ndarray:
"""Extract average histogram landmarks from images used for training.
Expand Down Expand Up @@ -171,7 +174,9 @@ def train(
percentiles_database = []
a, b = percentiles_cutoff # for mypy
percentiles = _get_percentiles((a, b))
for i, image_file_path in enumerate(tqdm(images_paths)):
iterable: Iterable[TypePath]
iterable = tqdm(images_paths) if progress else images_paths # type: ignore[assignment]
for i, image_file_path in enumerate(iterable):
tensor, _ = read_image(image_file_path)
if masking_function is not None:
mask = masking_function(tensor)
Expand Down
2 changes: 2 additions & 0 deletions tests/data/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,10 @@ def test_dicom_dir_missing(self):
def test_dicom_dir_no_files(self):
empty = self.dir / 'empty'
empty.mkdir()
sitk.ProcessObject_SetGlobalWarningDisplay(False)
with pytest.raises(FileNotFoundError):
io._read_dicom(empty)
sitk.ProcessObject_SetGlobalWarningDisplay(True)

def write_read_matrix(self, suffix):
out_path = self.dir / f'matrix{suffix}'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,22 @@ def test_train_histogram(self):
paths,
masking_function=HistogramStandardization.mean,
output_path=(self.dir / 'landmarks.txt'),
progress=False,
)
# Use a file to mask
HistogramStandardization.train(
paths,
mask_path=self.dataset[0].label.path,
output_path=(self.dir / 'landmarks.npy'),
progress=False,
)
# Use files to mask
masks = [subject.label.path for subject in self.dataset]
HistogramStandardization.train(
paths,
mask_path=masks,
output_path=(self.dir / 'landmarks_masks.npy'),
progress=False,
)

def test_bad_paths_lengths(self):
Expand All @@ -74,8 +77,9 @@ def test_wrong_image_key(self):
def test_with_saved_dict(self):
landmarks = np.linspace(0, 100, 13)
landmarks_dict = {'image': landmarks}
torch.save(landmarks_dict, self.dir / 'landmarks_dict.pth')
landmarks_dict = torch.load(self.dir / 'landmarks_dict.pth')
landmarks_path = self.dir / 'landmarks_dict.pth'
torch.save(landmarks_dict, landmarks_path)
landmarks_dict = torch.load(landmarks_path, weights_only=False)
transform = HistogramStandardization(landmarks_dict)
transform(self.dataset[0])

Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ commands =
[testenv:mypy]
deps =
mypy
pandas-stubs
pip
commands =
mypy \
--install-types \
Expand Down

0 comments on commit 7bb2b4c

Please sign in to comment.