Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Revise doctests and get them ready for more thorough testing. #10

Merged
merged 3 commits into from
Oct 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion nitransforms/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,4 +193,4 @@ def to_filename(self, filename, fmt='X5'):
root = out_file.create_group('/0')
self._to_hdf5(root)

return filename
return filename
27 changes: 27 additions & 0 deletions nitransforms/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""py.test configuration."""
import os
from pathlib import Path
import numpy as np
import nibabel as nb
import pytest
import tempfile


@pytest.fixture(autouse=True)
def doctest_autoimport(doctest_namespace):
"""Make available some fundamental modules to doctest modules."""
doctest_namespace['np'] = np
doctest_namespace['nb'] = nb
doctest_namespace['os'] = os
doctest_namespace['Path'] = Path
doctest_namespace['datadir'] = os.path.join(os.path.dirname(__file__), 'tests/data')

tmpdir = tempfile.TemporaryDirectory()
doctest_namespace['tmpdir'] = tmpdir.name

testdata = np.zeros((11, 11, 11), dtype='uint8')
nifti_fname = str(Path(tmpdir.name) / 'test.nii.gz')
nb.Nifti1Image(testdata, np.eye(4)).to_filename(nifti_fname)
doctest_namespace['testfile'] = nifti_fname
yield
tmpdir.cleanup()
30 changes: 22 additions & 8 deletions nitransforms/linear.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,24 @@ class Affine(TransformBase):
def __init__(self, matrix=None, reference=None):
"""
Initialize a linear transform.

Parameters
----------
matrix : ndarray
The inverse coordinate transformation matrix **in physical
coordinates**, mapping coordinates from *reference* space
into *moving* space.
This matrix should be provided in homogeneous coordinates.

Examples
--------
>>> xfm = Affine([[1, 0, 0, 4], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
>>> xfm.matrix # doctest: +NORMALIZE_WHITESPACE
array([[1, 0, 0, 4],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
array([[[1, 0, 0, 4],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]]])

"""
super(Affine, self).__init__()
if matrix is None:
Expand All @@ -71,6 +74,7 @@ def resample(self, moving, order=3, mode='constant', cval=0.0, prefilter=True,
output_dtype=None):
"""
Resample the moving image in reference space.

Parameters
----------
moving : `spatialimage`
Expand All @@ -92,17 +96,27 @@ def resample(self, moving, order=3, mode='constant', cval=0.0, prefilter=True,
slightly blurred if *order > 1*, unless the input is prefiltered,
i.e. it is the result of calling the spline filter on the original
input.

Returns
-------
moved_image : `spatialimage`
The moving imaged after resampling to reference space.

Examples
--------
>>> import nibabel as nib
>>> xfm = Affine([[1, 0, 0, 4], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
>>> ref = nib.load('image.nii.gz')
>>> ref = nb.load(testfile)
>>> xfm.reference = ref
>>> xfm.resample(ref, order=0)
>>> refdata = ref.get_fdata()
>>> np.allclose(refdata, 0)
True

>>> refdata[5, 5, 5] = 1 # Set a one in the middle voxel
>>> moving = nb.Nifti1Image(refdata, ref.affine, ref.header)
>>> resampled = xfm.resample(moving, order=0).get_fdata()
>>> resampled[1, 5, 5]
1.0

"""
if output_dtype is None:
output_dtype = moving.header.get_data_dtype()
Expand Down Expand Up @@ -323,4 +337,4 @@ def _fsl_aff_adapt(space):
if np.linalg.det(aff) > 0:
swp[0, 0] = -1.0
swp[0, 3] = (space.shape[0] - 1) * zooms[0]
return swp, np.diag(zooms)
return swp, np.diag(zooms)
38 changes: 22 additions & 16 deletions nitransforms/nonlinear.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,18 +102,25 @@ def _cache_moving(self, moving):
def resample(self, moving, order=3, mode='constant', cval=0.0, prefilter=True,
output_dtype=None):
"""
Resample the `moving` image applying the deformation field.
Resample the ``moving`` image applying the deformation field.

Examples
--------
>>> import numpy as np
>>> import nibabel as nb
>>> ref = nb.load('t1_weighted.nii.gz')
>>> ref = nb.load(testfile)
>>> refdata = ref.get_fdata()
>>> np.allclose(refdata, 0)
True

>>> refdata[5, 5, 5] = 1 # Set a one in the middle voxel
>>> moving = nb.Nifti1Image(refdata, ref.affine, ref.header)
>>> field = np.zeros(tuple(list(ref.shape) + [3]))
>>> field[..., 0] = 4.0
>>> fieldimg = nb.Nifti1Image(field, ref.affine, ref.header)
>>> xfm = nb.transform.DeformationFieldTransform(fieldimg)
>>> new = xfm.resample(ref)
>>> new.to_filename('deffield.nii.gz')
>>> xfm = DeformationFieldTransform(fieldimg)
>>> resampled = xfm.resample(moving, order=0).get_fdata()
>>> resampled[1, 5, 5]
1.0

"""
self._cache_moving(moving)
return super(DeformationFieldTransform, self).resample(
Expand Down Expand Up @@ -222,25 +229,24 @@ def map_voxel(self, index, moving=None):
def resample(self, moving, order=3, mode='constant', cval=0.0, prefilter=True,
output_dtype=None):
"""
Resample the `moving` image applying the deformation field.
Resample the ``moving`` image applying the deformation field.

Examples
--------
>>> import numpy as np
>>> import nibabel as nb
>>> ref = nb.load('t1_weighted.nii.gz')
>>> ref = nb.load(os.path.join(datadir, 'someones_anatomy.nii.gz'))
>>> coeffs = np.zeros((6, 6, 6, 3))
>>> coeffs[2, 2, 2, ...] = [10.0, -20.0, 0]
>>> aff = ref.affine
>>> aff[:3, :3] = aff.dot(np.eye(3) * np.array(ref.header.get_zooms()[:3] / 6.0)
>>> aff[:3, :3] = aff[:3, :3].dot(np.eye(3) * np.array(ref.header.get_zooms()[:3]) / 6.0)
>>> coeffsimg = nb.Nifti1Image(coeffs, ref.affine, ref.header)
>>> xfm = nb.transform.BSplineFieldTransform(ref, coeffsimg)
>>> new = xfm.resample(ref)
>>> new.to_filename('deffield.nii.gz')
>>> xfm = BSplineFieldTransform(ref, coeffsimg)
>>> new = xfm.resample(ref) # doctest: +SKIP

"""
self._cache_moving()
return super(BSplineFieldTransform, self).resample(
moving, order=order, mode=mode, cval=cval, prefilter=prefilter)


def _pprint(inlist):
return 'x'.join(['%d' % s for s in inlist])
return 'x'.join(['%d' % s for s in inlist])