Skip to content

Commit

Permalink
sty: format changed files
Browse files Browse the repository at this point in the history
  • Loading branch information
oesteban committed Jul 31, 2024
1 parent 06a1c01 commit 8dd883d
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 41 deletions.
17 changes: 8 additions & 9 deletions nitransforms/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Common interface for transforms."""

from pathlib import Path
import numpy as np
import h5py
Expand Down Expand Up @@ -146,13 +147,13 @@ def from_arrays(cls, coordinates, triangles):
darrays = [
nb.gifti.GiftiDataArray(
coordinates.astype(np.float32),
intent=nb.nifti1.intent_codes['NIFTI_INTENT_POINTSET'],
datatype=nb.nifti1.data_type_codes['NIFTI_TYPE_FLOAT32'],
intent=nb.nifti1.intent_codes["NIFTI_INTENT_POINTSET"],
datatype=nb.nifti1.data_type_codes["NIFTI_TYPE_FLOAT32"],
),
nb.gifti.GiftiDataArray(
triangles.astype(np.int32),
intent=nb.nifti1.intent_codes['NIFTI_INTENT_TRIANGLE'],
datatype=nb.nifti1.data_type_codes['NIFTI_TYPE_INT32'],
intent=nb.nifti1.intent_codes["NIFTI_INTENT_TRIANGLE"],
datatype=nb.nifti1.data_type_codes["NIFTI_TYPE_INT32"],
),
]
gii = nb.gifti.GiftiImage(darrays=darrays)
Expand Down Expand Up @@ -282,7 +283,7 @@ def __add__(self, b):
def __len__(self):
"""
Enable ``len()``.
By default, all transforms are of length one.
This must be overriden by transforms arrays and chains.
Expand Down Expand Up @@ -345,10 +346,8 @@ def apply(self, *args, **kwargs):
Deprecated. Please use ``nitransforms.resampling.apply`` instead.
"""
message = (
"The `apply` method is deprecated. Please use `nitransforms.resampling.apply` instead."
)
warnings.warn(message, DeprecationWarning, stacklevel=2)
_msg = "This method is deprecated. Please use `nitransforms.resampling.apply` instead."
warnings.warn(_msg, DeprecationWarning, stacklevel=2)
from .resampling import apply

return apply(self, *args, **kwargs)
Expand Down
6 changes: 5 additions & 1 deletion nitransforms/resampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,11 @@ def apply(
)

if isinstance(_ref, ImageGrid): # If reference is grid, reshape
hdr = _ref.header.copy() if _ref.header is not None else spatialimage.header.__class__()
hdr = (
_ref.header.copy()
if _ref.header is not None
else spatialimage.header.__class__()
)
hdr.set_data_dtype(output_dtype or spatialimage.header.get_data_dtype())

moved = spatialimage.__class__(
Expand Down
10 changes: 8 additions & 2 deletions nitransforms/tests/test_base.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Tests of the base module."""

import numpy as np
import nibabel as nb
from nibabel.arrayproxy import get_obj_dtype
Expand Down Expand Up @@ -114,7 +115,9 @@ def _to_hdf5(klass, x5_root):
xfm.reference = fname
moved = apply(xfm, fname, order=0)

assert np.all(imgdata == np.asanyarray(moved.dataobj, dtype=get_obj_dtype(moved.dataobj)))
assert np.all(
imgdata == np.asanyarray(moved.dataobj, dtype=get_obj_dtype(moved.dataobj))
)

# Test ndim returned by affine
assert nitl.Affine().ndim == 3
Expand Down Expand Up @@ -168,7 +171,10 @@ def test_concatenation(testdata_path):

def test_SurfaceMesh(testdata_path):
surf_path = testdata_path / "sub-200148_hemi-R_pial.surf.gii"
shape_path = testdata_path / "sub-sid000005_ses-budapest_acq-MPRAGE_hemi-R_thickness.shape.gii"
shape_path = (
testdata_path
/ "sub-sid000005_ses-budapest_acq-MPRAGE_hemi-R_thickness.shape.gii"
)
img_path = testdata_path / "bold.nii.gz"

mesh = SurfaceMesh(nb.load(surf_path))
Expand Down
41 changes: 29 additions & 12 deletions nitransforms/tests/test_linear.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Tests of linear transforms."""
import os

import pytest
import numpy as np
import h5py

import nibabel as nb
from nibabel.eulerangles import euler2mat
from nibabel.affines import from_matvec
from nitransforms import linear as nitl
from nitransforms import io
from .utils import assert_affines_by_filename


@pytest.mark.parametrize("matrix", [[0.0], np.ones((3, 3, 3)), np.ones((3, 4)), ])
@pytest.mark.parametrize(
"matrix",
[
[0.0],
np.ones((3, 3, 3)),
np.ones((3, 4)),
],
)
def test_linear_typeerrors1(matrix):
"""Exercise errors in Affine creation."""
with pytest.raises(TypeError):
Expand Down Expand Up @@ -136,7 +142,9 @@ def test_loadsave(tmp_path, data_path, testdata_path, autofmt, fmt):

assert np.allclose(
xfm.matrix,
nitl.load(fname, fmt=supplied_fmt, reference=ref_file, moving=ref_file).matrix,
nitl.load(
fname, fmt=supplied_fmt, reference=ref_file, moving=ref_file
).matrix,
)
else:
assert xfm == nitl.load(fname, fmt=supplied_fmt, reference=ref_file)
Expand All @@ -146,7 +154,9 @@ def test_loadsave(tmp_path, data_path, testdata_path, autofmt, fmt):
if fmt == "fsl":
assert np.allclose(
xfm.matrix,
nitl.load(fname, fmt=supplied_fmt, reference=ref_file, moving=ref_file).matrix,
nitl.load(
fname, fmt=supplied_fmt, reference=ref_file, moving=ref_file
).matrix,
rtol=1e-2, # FSL incurs into large errors due to rounding
)
else:
Expand All @@ -160,7 +170,9 @@ def test_loadsave(tmp_path, data_path, testdata_path, autofmt, fmt):
if fmt == "fsl":
assert np.allclose(
xfm.matrix,
nitl.load(fname, fmt=supplied_fmt, reference=ref_file, moving=ref_file).matrix,
nitl.load(
fname, fmt=supplied_fmt, reference=ref_file, moving=ref_file
).matrix,
rtol=1e-2, # FSL incurs into large errors due to rounding
)
else:
Expand All @@ -170,7 +182,9 @@ def test_loadsave(tmp_path, data_path, testdata_path, autofmt, fmt):
if fmt == "fsl":
assert np.allclose(
xfm.matrix,
nitl.load(fname, fmt=supplied_fmt, reference=ref_file, moving=ref_file).matrix,
nitl.load(
fname, fmt=supplied_fmt, reference=ref_file, moving=ref_file
).matrix,
rtol=1e-2, # FSL incurs into large errors due to rounding
)
else:
Expand All @@ -190,12 +204,15 @@ def test_linear_save(tmpdir, data_path, get_testdata, image_orientation, sw_tool
T = np.linalg.inv(T)

xfm = (
nitl.Affine(T) if (sw_tool, image_orientation) != ("afni", "oblique") else
nitl.Affine(T)
if (sw_tool, image_orientation) != ("afni", "oblique")
# AFNI is special when moving or reference are oblique - let io do the magic
nitl.Affine(io.afni.AFNILinearTransform.from_ras(T).to_ras(
reference=img,
moving=img,
))
else nitl.Affine(
io.afni.AFNILinearTransform.from_ras(T).to_ras(
reference=img,
moving=img,
)
)
)
xfm.reference = img

Expand Down
1 change: 1 addition & 0 deletions nitransforms/tests/test_manip.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Tests of nonlinear transforms."""

import pytest

import numpy as np
Expand Down
4 changes: 1 addition & 3 deletions nitransforms/tests/test_nonlinear.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Tests of nonlinear transforms."""

import os
import shutil
from subprocess import check_call
import pytest

import numpy as np
Expand All @@ -14,7 +13,6 @@
from nitransforms.nonlinear import (
BSplineFieldTransform,
DenseFieldTransform,
load as nlload,
)
from ..io.itk import ITKDisplacementsField

Expand Down
41 changes: 27 additions & 14 deletions nitransforms/tests/test_resampling.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Exercise the standalone ``apply()`` implementation."""

import os
import pytest
import numpy as np
Expand Down Expand Up @@ -50,9 +51,19 @@
}


@pytest.mark.parametrize("image_orientation", ["RAS", "LAS", "LPS", 'oblique', ])
@pytest.mark.parametrize(
"image_orientation",
[
"RAS",
"LAS",
"LPS",
"oblique",
],
)
@pytest.mark.parametrize("sw_tool", ["itk", "fsl", "afni", "fs"])
def test_apply_linear_transform(tmpdir, get_testdata, get_testmask, image_orientation, sw_tool):
def test_apply_linear_transform(
tmpdir, get_testdata, get_testmask, image_orientation, sw_tool
):
"""Check implementation of exporting affines to formats."""
tmpdir.chdir()

Expand Down Expand Up @@ -107,7 +118,7 @@ def test_apply_linear_transform(tmpdir, get_testdata, get_testmask, image_orient
nt_moved_mask.to_filename("ntmask.nii.gz")
diff = np.asanyarray(sw_moved_mask.dataobj) - np.asanyarray(nt_moved_mask.dataobj)

assert np.sqrt((diff ** 2).mean()) < RMSE_TOL_LINEAR
assert np.sqrt((diff**2).mean()) < RMSE_TOL_LINEAR
brainmask = np.asanyarray(nt_moved_mask.dataobj, dtype=bool)

cmd = APPLY_LINEAR_CMD[sw_tool](
Expand All @@ -123,19 +134,17 @@ def test_apply_linear_transform(tmpdir, get_testdata, get_testmask, image_orient
sw_moved.set_data_dtype(img.get_data_dtype())

nt_moved = apply(xfm, img, order=0)
diff = (
np.asanyarray(sw_moved.dataobj, dtype=sw_moved.get_data_dtype())
- np.asanyarray(nt_moved.dataobj, dtype=nt_moved.get_data_dtype())
)
diff = np.asanyarray(
sw_moved.dataobj, dtype=sw_moved.get_data_dtype()
) - np.asanyarray(nt_moved.dataobj, dtype=nt_moved.get_data_dtype())

# A certain tolerance is necessary because of resampling at borders
assert np.sqrt((diff[brainmask] ** 2).mean()) < RMSE_TOL_LINEAR

nt_moved = apply(xfm, "img.nii.gz", order=0)
diff = (
np.asanyarray(sw_moved.dataobj, dtype=sw_moved.get_data_dtype())
- np.asanyarray(nt_moved.dataobj, dtype=nt_moved.get_data_dtype())
)
diff = np.asanyarray(
sw_moved.dataobj, dtype=sw_moved.get_data_dtype()
) - np.asanyarray(nt_moved.dataobj, dtype=nt_moved.get_data_dtype())
# A certain tolerance is necessary because of resampling at borders
assert np.sqrt((diff[brainmask] ** 2).mean()) < RMSE_TOL_LINEAR

Expand Down Expand Up @@ -281,7 +290,8 @@ def test_apply_transformchain(tmp_path, testdata_path):

ref_fname = tmp_path / "reference.nii.gz"
nb.Nifti1Image(
np.zeros(xfm.reference.shape, dtype="uint16"), xfm.reference.affine,
np.zeros(xfm.reference.shape, dtype="uint16"),
xfm.reference.affine,
).to_filename(str(ref_fname))

# Then apply the transform and cross-check with software
Expand Down Expand Up @@ -310,7 +320,9 @@ def test_apply_transformchain(tmp_path, testdata_path):


@pytest.mark.parametrize("serialize_4d", [True, False])
def test_LinearTransformsMapping_apply(tmp_path, data_path, testdata_path, serialize_4d):
def test_LinearTransformsMapping_apply(
tmp_path, data_path, testdata_path, serialize_4d
):
"""Apply transform mappings."""
hmc = nitl.load(
data_path / "hmc-itk.tfm", fmt="itk", reference=testdata_path / "sbref.nii.gz"
Expand All @@ -333,7 +345,8 @@ def test_LinearTransformsMapping_apply(tmp_path, data_path, testdata_path, seria
)

nii = apply(
hmcinv, testdata_path / "fmap.nii.gz",
hmcinv,
testdata_path / "fmap.nii.gz",
order=1,
serialize_nvols=2 if serialize_4d else np.inf,
)
Expand Down

0 comments on commit 8dd883d

Please sign in to comment.