[med-svn] [Git][med-team/dcmstack][upstream] New upstream version 0.9
Yaroslav Halchenko (@yoh)
gitlab at salsa.debian.org
Fri Sep 30 01:11:06 BST 2022
Yaroslav Halchenko pushed to branch upstream at Debian Med / dcmstack
Commits:
4f7a3831 by Yaroslav Halchenko at 2022-09-29T19:18:56-04:00
New upstream version 0.9
- - - - -
15 changed files:
- + .github/workflows/test.yml
- − .travis.yml
- README.rst
- doc/Python_Tutorial.rst
- + setup.cfg
- setup.py
- src/dcmstack/dcmmeta.py
- src/dcmstack/dcmstack.py
- src/dcmstack/dcmstack_cli.py
- src/dcmstack/info.py
- src/dcmstack/nitool_cli.py
- test/test_cli.py
- test/test_dcmmeta.py
- test/test_dcmstack.py
- test/test_extract.py
Changes:
=====================================
.github/workflows/test.yml
=====================================
@@ -0,0 +1,62 @@
+name: Tests
+
+on:
+ push:
+ branches:
+ - master
+ pull_request:
+ schedule:
+ - cron: '0 6 * * *'
+
+defaults:
+ run:
+ shell: bash
+
+jobs:
+ test:
+ runs-on: ${{ matrix.os }}
+ env:
+ NO_ET: 1
+ strategy:
+ fail-fast: false
+ matrix:
+ os:
+ - windows-2019
+ - ubuntu-latest
+ - macos-latest
+ python:
+ - '2.7'
+ - '3.7'
+ - '3.8'
+ - '3.9'
+ - '3.10'
+ mode:
+ - normal
+
+ steps:
+
+ - uses: actions/checkout at v1
+
+ - name: Set up Python ${{ matrix.python }}
+ uses: actions/setup-python at v2
+ with:
+ python-version: ${{ matrix.python }}
+
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip wheel
+ pip install ".[test]"
+
+ - name: Run all tests
+ run: |
+ python -m pytest -s -v --cov=dcmstack --cov-report=xml
+
+ - name: Upload coverage to Codecov
+ uses: codecov/codecov-action at v2
+ with:
+ token: ${{ secrets.CODECOV_TOKEN }}
+ file: ./coverage.xml
+ flags: unittests
+ # name: codecov-umbrella
+ # yml: ./codecov.yml
+ fail_ci_if_error: false
\ No newline at end of file
=====================================
.travis.yml deleted
=====================================
@@ -1,35 +0,0 @@
-language: python
-
-python:
- - "2.7"
- - "3.5"
- - "3.6"
- - "3.7-dev"
-
-env:
- global:
- - DEPENDS="nose codecov coverage"
- - OPTIONAL_DEPENDS=""
-
-install:
- - pip install $DEPENDS $OPTIONAL_DEPENDS
- - pip install -e .
-
-matrix:
- include:
- - python: 2.7
- - python: 2.7
- env:
- - DEPENDS="pydicom==0.9.9"
- - python: 2.7
- env:
- - OPTIONAL_DEPENDS="chardet"
- - python: 3.7-dev
- env:
- - OPTIONAL_DEPENDS="chardet"
-
-script:
- - nosetests -v --with-cov --cover-package dcmstack
-
-after_success:
- - codecov
=====================================
README.rst
=====================================
@@ -1,6 +1,3 @@
-.. -*- rest -*-
-.. vim:syntax=rest
-
========
dcmstack
========
@@ -10,6 +7,17 @@ to extract and summarize meta data from the source DICOMs. The meta data
can be injected it into a Nifti header extension or written out as a JSON
formatted text file.
+
+Installing
+----------
+
+You can the latest release from PyPI by doing:
+
+.. code-block:: console
+
+ $ pip install dcmstack
+
+
Documentation
-------------
@@ -17,37 +25,26 @@ Documentation can be read online: https://dcmstack.readthedocs.org/
You can build the HTML documentation under build/sphinx/html with:
-$ python setup.py build_sphinx
-
If you have the *sphinx* and *numpydoc* packages and a *make* command you
can build the documentation by running the *make* command in the *doc/*
directory. For example, to create the HTML documentation you would do:
-$ make html
+.. code-block:: console
+
+ $ python setup.py build_sphinx
+ $ make html
And then view doc/_build/html/index.html with a web browser.
+
Running Tests
-------------
-You can run the tests with:
-
-$ python setup.py test
-
-Or if you already have the *nose* package installed you can use the
-*nosetests* command in the top level directory:
-
-$ nosetests
-
-Installing
-----------
-
-You can install the *.zip* or *.tar.gz* package with the *easy_install*
-command.
-
-$ easy_install dcmstack-0.6.zip
-
-Or you can uncompress the package and in the top level directory run:
+You can install dcmstack along with any test dependencies by installing the ``test``
+extra. Then you can run the ``pytest`` command to run the test-suite:
-$ python setup.py install
+.. code-block:: console
+
+ $ pip install dcmstack[test]
+ $ pytest
=====================================
doc/Python_Tutorial.rst
=====================================
@@ -12,12 +12,12 @@ If you have an acquisition that you would like to turn into a single
.. code-block:: python
- >>> import dcmstack, dicom
+ >>> import dcmstack, pydicom
>>> from glob import glob
>>> src_paths = glob('032-MPRAGEAXTI900Pre/*.dcm')
>>> my_stack = dcmstack.DicomStack()
>>> for src_path in src_paths:
- ... src_dcm = dicom.read_file(src_path)
+ ... src_dcm = pydicom.dcmread(src_path)
... my_stack.add_dcm(src_dcm)
If you are unsure how many stacks you want from a collection of DICOM data
@@ -89,12 +89,12 @@ these can be created directly from a *DicomStack*.
.. code-block:: python
- >>> import dcmstack, dicom
+ >>> import dcmstack, pydicom
>>> from glob import glob
>>> src_paths = glob('032-MPRAGEAXTI900Pre/*.dcm')
>>> my_stack = dcmstack.DicomStack()
>>> for src_path in src_paths:
- ... src_dcm = dicom.read_file(src_path)
+ ... src_dcm = pydicom.dcmread(src_path)
... my_stack.add_dcm(src_dcm)
...
>>> nii_wrp = my_stack.to_nifti_wrapper()
@@ -196,6 +196,3 @@ extension directly.
[11.0, 87.0]
>>> print nw.meta_ext.get_classification('EchoTime')
('time', 'samples')
-
-
-
=====================================
setup.cfg
=====================================
@@ -0,0 +1,4 @@
+[options.extras_require]
+test =
+ pytest
+ pytest-cov
=====================================
setup.py
=====================================
@@ -7,7 +7,10 @@ exec(open(info_file).read())
setup(name=NAME,
+ python_requires=">=2.7",
description=DESCRIPTION,
+ long_description=open("README.rst").read(),
+ long_description_content_type="text/x-rst",
author=AUTHOR,
author_email=AUTHOR_EMAIL,
maintainer=MAINTAINER,
@@ -26,5 +29,5 @@ setup(name=NAME,
'nitool = dcmstack.nitool_cli:main',
],
},
- test_suite = 'nose.collector'
+ test_suite = 'pytest'
)
=====================================
src/dcmstack/dcmmeta.py
=====================================
@@ -1435,7 +1435,7 @@ class NiftiWrapper(object):
'''
shape = self.nii_img.shape
- data = self.nii_img.get_data()
+ data = np.asanyarray(self.nii_img.dataobj)
header = self.nii_img.header
slice_dim = header.get_dim_info()[2]
@@ -1462,7 +1462,7 @@ class NiftiWrapper(object):
else:
slices[dim] = slice(idx, idx+1)
- split_data = data[slices].copy()
+ split_data = data[tuple(slices)].copy()
#Update the translation in any affines if needed
if not trans_update is None and idx != 0:
@@ -1533,7 +1533,7 @@ class NiftiWrapper(object):
data = dcm_wrp.get_data()
#The Nifti patient space flips the x and y directions
- affine = np.dot(np.diag([-1., -1., 1., 1.]), dcm_wrp.get_affine())
+ affine = np.dot(np.diag([-1., -1., 1., 1.]), dcm_wrp.affine)
#Make 2D data 3D
if len(data.shape) == 2:
@@ -1647,7 +1647,7 @@ class NiftiWrapper(object):
result_shape.append(1)
result_shape[dim] = n_inputs
- result_dtype = max(input_wrp.nii_img.get_data().dtype
+ result_dtype = max(input_wrp.nii_img.get_data_dtype()
for input_wrp in seq)
result_data = np.empty(result_shape, dtype=result_dtype)
@@ -1721,7 +1721,7 @@ class NiftiWrapper(object):
data_slices[dim] = input_idx
- result_data[data_slices] = input_nii.get_data().squeeze()
+ result_data[tuple(data_slices)] = np.asanyarray(input_nii.dataobj).squeeze()
if input_idx != 0:
if (hdr_info['qform'] is None or
=====================================
src/dcmstack/dcmstack.py
=====================================
@@ -367,39 +367,6 @@ class DicomOrdering(object):
return val
-def _make_dummy(reference, meta, iop):
- '''Make a "dummy" NiftiWrapper (no valid pixel data).'''
- #Create the dummy data array filled with largest representable value
- data = np.empty_like(reference.nii_img.get_data())
- data[...] = np.iinfo(np.int16).max
-
- #Create the nifti image and set header data
- aff = reference.nii_img.affine.copy()
- aff[:3, 3] = [iop[1], iop[0], iop[2]]
- nii_img = nb.nifti1.Nifti1Image(data, aff)
- hdr = nii_img.header
- hdr.set_xyzt_units('mm', 'sec')
- dim_info = {'freq' : None,
- 'phase' : None,
- 'slice' : 2
- }
- if 'InplanePhaseEncodingDirection' in meta:
- if meta['InplanePhaseEncodingDirection'] == 'ROW':
- dim_info['phase'] = 1
- dim_info['freq'] = 0
- else:
- dim_info['phase'] = 0
- dim_info['freq'] = 1
- hdr.set_dim_info(**dim_info)
-
- #Embed the meta data extension
- result = NiftiWrapper(nii_img, make_empty=True)
- result.meta_ext.reorient_transform = np.diag([-1., -1., 1., 1.])
- result.meta_ext.get_class_dict(('global', 'const')).update(meta)
-
- return result
-
-
default_group_keys = ('SeriesInstanceUID',
'SeriesNumber',
'ProtocolName',
@@ -441,11 +408,6 @@ class DicomStack(object):
The DICOM keyword or DicomOrdering object specifying how to order
the DICOM data sets along the vector dimension.
- allow_dummies : bool
- If True then data sets without pixel data can be added to the stack.
- The "dummy" voxels will have the maximum representable value for
- the datatype.
-
meta_filter : callable
A callable that takes a meta data key and value, and returns True if
that meta data element should be excluded from the DcmMeta extension.
@@ -483,8 +445,7 @@ class DicomStack(object):
'''Set of minimal meta data keys that should be provided if they exist in
the source DICOM files.'''
- def __init__(self, time_order=None, vector_order=None,
- allow_dummies=False, meta_filter=None):
+ def __init__(self, time_order=None, vector_order=None, meta_filter=None):
if isinstance(time_order, str):
self._time_order = DicomOrdering(time_order)
else:
@@ -499,8 +460,6 @@ class DicomStack(object):
else:
self._meta_filter = meta_filter
- self._allow_dummies = allow_dummies
-
#Sets all the state variables to their defaults
self.clear()
@@ -516,25 +475,13 @@ class DicomStack(object):
key)
def _chk_congruent(self, meta):
- is_dummy = not 'Rows' in meta or not 'Columns' in meta
- if is_dummy and not self._allow_dummies:
- raise IncongruentImageError('Missing Rows/Columns')
-
if not self._ref_input is None:
self._chk_close(('PixelSpacing',
'ImageOrientationPatient'),
meta,
self._ref_input
)
- if not is_dummy:
- self._chk_equal(('Rows', 'Columns'), meta, self._ref_input)
- elif len(self._dummies) != 0:
- self._chk_close(('PixelSpacing',
- 'ImageOrientationPatient'),
- meta,
- self._dummies[0][0]
- )
- return is_dummy
+ self._chk_equal(('Rows', 'Columns'), meta, self._ref_input)
def add_dcm(self, dcm, meta=None):
'''Add a pydicom dataset to the stack.
@@ -570,7 +517,7 @@ class DicomStack(object):
dw = wrapper_from_data(dcm)
- is_dummy = self._chk_congruent(meta)
+ self._chk_congruent(meta)
self._phase_enc_dirs.add(meta.get('InPlanePhaseEncodingDirection'))
self._repetition_times.add(meta.get('RepetitionTime'))
@@ -601,22 +548,10 @@ class DicomStack(object):
#Create a NiftiWrapper for this input if possible
nii_wrp = None
- if not is_dummy:
- nii_wrp = NiftiWrapper.from_dicom_wrapper(dw, meta)
- if self._ref_input is None:
- #We don't have a reference input yet, use this one
- self._ref_input = nii_wrp
- #Convert any dummies that we have stashed previously
- for dummy_meta, dummy_tuple, iop in self._dummies:
- dummy_wrp = _make_dummy(self._ref_input, dummy_meta, iop)
- self._files_info.append((dummy_wrp, dummy_tuple))
- else:
- if self._ref_input is None:
- #We don't have a reference input, so stash the dummy for now
- self._dummies.append((meta, sorting_tuple, dcm.ImagePositionPatient))
- else:
- #Convert dummy using the reference input
- nii_wrp = _make_dummy(self._ref_input, meta, dcm.ImagePositionPatient)
+ nii_wrp = NiftiWrapper.from_dicom_wrapper(dw, meta)
+ if self._ref_input is None:
+ #We don't have a reference input yet, use this one
+ self._ref_input = nii_wrp
#If we made a NiftiWrapper add it to the stack
if not nii_wrp is None:
@@ -636,7 +571,6 @@ class DicomStack(object):
self._phase_enc_dirs = set()
self._repetition_times = set()
- self._dummies = []
self._ref_input = None
self._shape_dirty = True
@@ -701,9 +635,9 @@ class DicomStack(object):
if not self._shape_dirty:
return self._shape
- #We need at least one non-dummy file in the stack
+ #We need at least one file in the stack
if len(self._files_info) == 0:
- raise InvalidStackError("No (non-dummy) files in the stack")
+ raise InvalidStackError("No files in the stack")
#Figure out number of files and slices per volume
files_per_vol = len(self._slice_pos_vals)
@@ -836,13 +770,13 @@ class DicomStack(object):
if files_per_vol == 1 and file_shape[2] != 1:
file_idx = vec_idx*(stack_shape[3]) + time_idx
vox_array[:, :, :, time_idx, vec_idx] = \
- self._files_info[file_idx][0].nii_img.get_data()
+ np.asanyarray(self._files_info[file_idx][0].nii_img.dataobj)
else:
for slice_idx in range(files_per_vol):
file_idx = (vec_idx*(stack_shape[3]*stack_shape[2]) +
time_idx*(stack_shape[2]) + slice_idx)
vox_array[:, :, slice_idx, time_idx, vec_idx] = \
- self._files_info[file_idx][0].nii_img.get_data()[:, :, 0]
+ np.asanyarray(self._files_info[file_idx][0].nii_img.dataobj[:, :, 0])
#Trim unused time/vector dimensions
if stack_shape[4] == 1:
@@ -911,7 +845,7 @@ class DicomStack(object):
A nibabel.nifti1.Nifti1Image created with the stack's data and affine.
'''
#Get the voxel data and affine
- data = self.get_data()
+ data = self.data
affine = self.affine
#Figure out the number of three (or two) dimensional volumes
@@ -1144,7 +1078,10 @@ def parse_and_group(src_paths, group_by=default_group_keys, extractor=None,
# Look for a matching sub_result
for c_list, sub_res in results[key]:
for c_idx, c_val in enumerate(c_list):
- if not np.allclose(c_val, close_list[c_idx], atol=5e-5):
+ if not (
+ (c_val is None and close_list[c_idx] is None) or
+ np.allclose(c_val, close_list[c_idx], atol=5e-5)
+ ):
break
else:
sub_res.append((dcm, meta, dcm_path))
=====================================
src/dcmstack/dcmstack_cli.py
=====================================
@@ -64,10 +64,6 @@ def main(argv=sys.argv):
input_opt.add_argument('--file-ext', default='.dcm', help=('Only try reading '
'files with the given extension. Default: '
'%(default)s'))
- input_opt.add_argument('--allow-dummies', action='store_true', default=False,
- help=('Allow DICOM files that are missing pixel '
- 'data, filling that slice of the output nifti with '
- 'the maximum representable value.'))
output_opt = arg_parser.add_argument_group('Output options')
output_opt.add_argument('--dest-dir', default=None,
@@ -293,7 +289,6 @@ def main(argv=sys.argv):
warn_on_except=not args.strict,
time_order=time_order,
vector_order=vector_order,
- allow_dummies=args.allow_dummies,
meta_filter=meta_filter)
meta = group[0][1]
=====================================
src/dcmstack/info.py
=====================================
@@ -4,7 +4,7 @@ not import dcmstack.
import sys
_version_major = 0
-_version_minor = 8
+_version_minor = 9
_version_micro = 0
_version_extra = ''
__version__ = "%s.%s.%s%s" % (_version_major,
@@ -24,17 +24,17 @@ description = 'Stack DICOM images into volumes and convert to Nifti'
# Hard dependencies
install_requires = ['pydicom >= 0.9.7',
- 'nibabel >= 2.1.0',
+ 'nibabel >= 2.5.1',
+ 'pylibjpeg-libjpeg ; python_version >= "3.7"',
]
-# Add version specific dependencies
-if sys.version_info < (2, 6):
- raise Exception("must use python 2.6 or greater")
-elif sys.version_info < (2, 7):
- install_requires.append('ordereddict')
# Extra requirements for building documentation and testing
extras_requires = {'doc': ["sphinx", "numpydoc"],
- 'test': ["nose"],
+ 'test': [
+ 'pytest <= 4.6 ; python_version == "2.7"',
+ 'pytest ; python_version > "2.7"',
+ 'pytest-cov',
+ ],
}
=====================================
src/dcmstack/nitool_cli.py
=====================================
@@ -16,7 +16,12 @@ prog_descrip = """Work with extended Nifti files created by dcmstack"""
def main(argv=sys.argv):
#Setup the top level parser
arg_parser = argparse.ArgumentParser(description=prog_descrip)
- sub_parsers = arg_parser.add_subparsers(title="Subcommands")
+ if sys.version_info > (3, 7):
+ sub_parsers = arg_parser.add_subparsers(title="Subcommands",
+ dest='cmd',
+ required=True)
+ else:
+ sub_parsers = arg_parser.add_subparsers(title="Subcommands", dest='cmd')
#Split command
split_help = ("Split src_nii file along a dimension. Defaults to the slice "
=====================================
test/test_cli.py
=====================================
@@ -5,8 +5,6 @@ from glob import glob
import numpy as np
-from nose.tools import ok_, eq_
-
from . import test_dir, src_dir
from dcmstack import dcmstack_cli, nitool_cli
@@ -55,11 +53,11 @@ class CliTest(object):
class TestDcmstackCli(CliTest):
def test_basic(self):
nii_paths = make_niftis(self.out_dir)
- eq_(len(nii_paths), 1)
+ assert len(nii_paths) == 1
def test_embed(self):
nii_paths = make_niftis(self.out_dir, ['--embed'])
- eq_(len(nii_paths), 1)
+ assert len(nii_paths) == 1
class TestNitoolCli(CliTest):
@@ -70,11 +68,11 @@ class TestNitoolCli(CliTest):
with open(json_path) as fp:
meta = json.load(fp)
print(json.dumps(meta, indent=4))
- ok_('dcmmeta_version' in meta)
- ok_('dcmmeta_affine' in meta)
- ok_('dcmmeta_reorient_transform' in meta)
- eq_(meta['dcmmeta_shape'], [192, 192, 2, 2])
- eq_(meta['dcmmeta_slice_dim'], 2)
- eq_(meta['global']['const']['Rows'], 192)
- eq_(meta['global']['const']['Columns'], 192)
- ok_(np.allclose(meta['time']['samples']['EchoTime'], [20.0, 40.0]))
+ assert('dcmmeta_version' in meta)
+ assert('dcmmeta_affine' in meta)
+ assert('dcmmeta_reorient_transform' in meta)
+ assert meta['dcmmeta_shape'] == [192, 192, 2, 2]
+ assert meta['dcmmeta_slice_dim'] == 2
+ assert meta['global']['const']['Rows'] == 192
+ assert meta['global']['const']['Columns'] == 192
+ assert(np.allclose(meta['time']['samples']['EchoTime'], [20.0, 40.0]))
=====================================
test/test_dcmmeta.py
=====================================
@@ -5,7 +5,7 @@ import sys
from os import path
from glob import glob
-from nose.tools import ok_, eq_, assert_raises
+import pytest
import numpy as np
import nibabel as nb
try:
@@ -18,79 +18,66 @@ from . import test_dir, src_dir
from dcmstack import dcmmeta
def test_is_constant():
- ok_(dcmmeta.is_constant([0]))
- ok_(dcmmeta.is_constant([0, 0]))
- ok_(dcmmeta.is_constant([0, 0, 1, 1], period=2))
- ok_(dcmmeta.is_constant([0, 0, 1, 1, 2, 2], period=2))
- eq_(dcmmeta.is_constant([0, 1]), False)
- eq_(dcmmeta.is_constant([0, 0, 1, 2], 2), False)
- assert_raises(ValueError, dcmmeta.is_constant, [0, 0, 0], -1)
- assert_raises(ValueError, dcmmeta.is_constant, [0, 0, 0], 1)
- assert_raises(ValueError, dcmmeta.is_constant, [0, 0, 0], 2)
- assert_raises(ValueError, dcmmeta.is_constant, [0, 0, 0], 4)
+ assert(dcmmeta.is_constant([0]))
+ assert(dcmmeta.is_constant([0, 0]))
+ assert(dcmmeta.is_constant([0, 0, 1, 1], period=2))
+ assert(dcmmeta.is_constant([0, 0, 1, 1, 2, 2], period=2))
+ assert dcmmeta.is_constant([0, 1]) == False
+ assert dcmmeta.is_constant([0, 0, 1, 2], 2) == False
+ with pytest.raises(ValueError):
+ dcmmeta.is_constant([0, 0, 0], -1)
+ dcmmeta.is_constant([0, 0, 0], 1)
+ dcmmeta.is_constant([0, 0, 0], 2)
+ dcmmeta.is_constant([0, 0, 0], 4)
def test_is_repeating():
- ok_(dcmmeta.is_repeating([0, 1, 0, 1], 2))
- ok_(dcmmeta.is_repeating([0, 1, 0, 1, 0, 1], 2))
- eq_(dcmmeta.is_repeating([0, 1, 1, 2], 2), False)
- assert_raises(ValueError, dcmmeta.is_repeating, [0, 1, 0, 1], -1)
- assert_raises(ValueError, dcmmeta.is_repeating, [0, 1, 0, 1], 1)
- assert_raises(ValueError, dcmmeta.is_repeating, [0, 1, 0, 1], 3)
- assert_raises(ValueError, dcmmeta.is_repeating, [0, 1, 0, 1], 4)
- assert_raises(ValueError, dcmmeta.is_repeating, [0, 1, 0, 1], 5)
+ assert(dcmmeta.is_repeating([0, 1, 0, 1], 2))
+ assert(dcmmeta.is_repeating([0, 1, 0, 1, 0, 1], 2))
+ assert dcmmeta.is_repeating([0, 1, 1, 2], 2) == False
+ with pytest.raises(ValueError):
+ dcmmeta.is_repeating([0, 1, 0, 1], -1)
+ dcmmeta.is_repeating([0, 1, 0, 1], 1)
+ dcmmeta.is_repeating([0, 1, 0, 1], 3)
+ dcmmeta.is_repeating([0, 1, 0, 1], 4)
+ dcmmeta.is_repeating([0, 1, 0, 1], 5)
def test_get_valid_classes():
ext = dcmmeta.DcmMetaExtension.make_empty((2, 2, 2), np.eye(4))
- eq_(ext.get_valid_classes(), (('global', 'const'), ('global', 'slices')))
+ assert ext.get_valid_classes() == (('global', 'const'), ('global', 'slices'))
ext.shape = (2, 2, 2, 2)
- eq_(ext.get_valid_classes(),
- (('global', 'const'),
- ('global', 'slices'),
- ('time', 'samples'),
- ('time', 'slices')
- )
- )
+ assert ext.get_valid_classes() == (('global', 'const'), ('global', 'slices'), ('time', 'samples'), ('time', 'slices'))
ext.shape = (2, 2, 2, 1, 2)
- eq_(ext.get_valid_classes(),
- (('global', 'const'),
- ('global', 'slices'),
- ('vector', 'samples'),
- ('vector', 'slices')
- )
- )
+ assert ext.get_valid_classes() == (('global', 'const'), ('global', 'slices'), ('vector', 'samples'), ('vector', 'slices'))
ext.shape = (2, 2, 2, 2, 2)
- eq_(ext.get_valid_classes(),
- (('global', 'const'),
- ('global', 'slices'),
- ('time', 'samples'),
- ('time', 'slices'),
- ('vector', 'samples'),
- ('vector', 'slices')
- )
- )
+ assert ext.get_valid_classes() == (('global', 'const'), \
+ ('global', 'slices'), \
+ ('time', 'samples'), \
+ ('time', 'slices'), \
+ ('vector', 'samples'), \
+ ('vector', 'slices'))
def test_get_mulitplicity_4d():
ext = dcmmeta.DcmMetaExtension.make_empty((64, 64, 7, 11),
np.eye(4),
np.eye(4),
2)
- eq_(ext.get_multiplicity(('global', 'const')), 1)
- eq_(ext.get_multiplicity(('global', 'slices')), 7 * 11)
- eq_(ext.get_multiplicity(('time', 'samples')), 11)
- eq_(ext.get_multiplicity(('time', 'slices')), 7)
+ assert ext.get_multiplicity(('global', 'const')) == 1
+ assert ext.get_multiplicity(('global', 'slices')) == 7 * 11
+ assert ext.get_multiplicity(('time', 'samples')) == 11
+ assert ext.get_multiplicity(('time', 'slices')) == 7
def test_get_mulitplicity_4d_vec():
ext = dcmmeta.DcmMetaExtension.make_empty((64, 64, 7, 1, 11),
np.eye(4),
np.eye(4),
2)
- eq_(ext.get_multiplicity(('global', 'const')), 1)
- eq_(ext.get_multiplicity(('global', 'slices')), 7 * 11)
- eq_(ext.get_multiplicity(('vector', 'samples')), 11)
- eq_(ext.get_multiplicity(('vector', 'slices')), 7)
+ assert ext.get_multiplicity(('global', 'const')) == 1
+ assert ext.get_multiplicity(('global', 'slices')) == 7 * 11
+ assert ext.get_multiplicity(('vector', 'samples')) == 11
+ assert ext.get_multiplicity(('vector', 'slices')) == 7
def test_get_mulitplicity_5d():
ext = dcmmeta.DcmMetaExtension.make_empty((64, 64, 7, 11, 13),
@@ -98,12 +85,12 @@ def test_get_mulitplicity_5d():
np.eye(4),
2
)
- eq_(ext.get_multiplicity(('global', 'const')), 1)
- eq_(ext.get_multiplicity(('global', 'slices')), 7 * 11 * 13)
- eq_(ext.get_multiplicity(('time', 'samples')), 11 * 13)
- eq_(ext.get_multiplicity(('time', 'slices')), 7)
- eq_(ext.get_multiplicity(('vector', 'samples')), 13)
- eq_(ext.get_multiplicity(('vector', 'slices')), 7 * 11)
+ assert ext.get_multiplicity(('global', 'const')) == 1
+ assert ext.get_multiplicity(('global', 'slices')) == 7 * 11 * 13
+ assert ext.get_multiplicity(('time', 'samples')) == 11 * 13
+ assert ext.get_multiplicity(('time', 'slices')) == 7
+ assert ext.get_multiplicity(('vector', 'samples')) == 13
+ assert ext.get_multiplicity(('vector', 'slices')) == 7 * 11
class TestCheckValid(object):
def setUp(self):
@@ -112,6 +99,9 @@ class TestCheckValid(object):
np.eye(4),
2)
+ def setup_method(self, setUp):
+ self.setUp()
+
def test_empty(self):
self.ext.check_valid()
@@ -119,75 +109,93 @@ class TestCheckValid(object):
self.ext.get_class_dict(('global', 'const'))['ConstTest'] = 2
self.ext.check_valid()
del self.ext._content['global']['const']
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
def test_global_slices(self):
cls_dict = self.ext.get_class_dict(('global', 'slices'))
cls_dict['SliceTest'] = [0] * 23
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
cls_dict['SliceTest'] = [0] * 24
self.ext.check_valid()
del self.ext._content['global']['slices']
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
def test_time_samples(self):
cls_dict = self.ext.get_class_dict(('time', 'samples'))
cls_dict['TimeSampleTest'] = [0] * 2
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
cls_dict['TimeSampleTest'] = [0] * 3
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
cls_dict['TimeSampleTest'] = [0] * 12
self.ext.check_valid()
del self.ext._content['time']['samples']
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
def test_time_slices(self):
cls_dict = self.ext.get_class_dict(('time', 'slices'))
cls_dict['TimeSliceTest'] = [0]
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
cls_dict['TimeSliceTest'] = [0] * 2
self.ext.check_valid()
del self.ext._content['time']['slices']
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
def test_vector_samples(self):
cls_dict = self.ext.get_class_dict(('vector', 'samples'))
cls_dict['VectorSampleTest'] = [0] * 3
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
cls_dict['VectorSampleTest'] = [0] * 4
self.ext.check_valid()
del self.ext._content['vector']['samples']
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
def test_vector_slices(self):
cls_dict = self.ext.get_class_dict(('vector', 'slices'))
cls_dict['VectorSliceTest'] = [0] * 5
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
cls_dict['VectorSliceTest'] = [0] * 6
self.ext.check_valid()
del self.ext._content['vector']['slices']
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
def test_invalid_affine(self):
self.ext._content['dcmmeta_affine'] = np.eye(3).tolist()
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
def test_invalid_slice_dim(self):
self.ext._content['dcmmeta_slice_dim'] = 3
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
self.ext._content['dcmmeta_slice_dim'] = -1
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
def test_invalid_shape(self):
self.ext._content['dcmmeta_shape'] = [2, 2]
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
self.ext._content['dcmmeta_shape'] = [2, 2, 1, 1, 1, 2]
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
def test_multiple_classes(self):
self.ext.get_class_dict(('global', 'const'))['Test'] = 0
self.ext.get_class_dict(('time', 'samples'))['Test'] = [0] * 3
- assert_raises(dcmmeta.InvalidExtensionError, self.ext.check_valid)
+ with pytest.raises(dcmmeta.InvalidExtensionError):
+ self.ext.check_valid()
def test_dcmmeta_affine():
ext = dcmmeta.DcmMetaExtension.make_empty((64, 64, 2),
@@ -195,63 +203,51 @@ def test_dcmmeta_affine():
np.eye(4),
2
)
- ok_(np.allclose(ext.affine, np.diag([1, 2, 3, 4])))
- assert_raises(ValueError,
- setattr,
- ext,
- 'affine',
- np.eye(3)
- )
+ assert(np.allclose(ext.affine, np.diag([1, 2, 3, 4])))
+ with pytest.raises(ValueError):
+ setattr(ext, 'affine', np.eye(3))
ext.affine = np.eye(4)
- ok_(np.allclose(ext.affine, np.eye(4)))
+ assert(np.allclose(ext.affine, np.eye(4)))
def test_dcmmeta_slice_dim():
ext = dcmmeta.DcmMetaExtension.make_empty((64, 64, 2), np.eye(4))
- eq_(ext.slice_dim, None)
- assert_raises(ValueError,
- setattr,
- ext,
- 'slice_dim',
- 3
- )
+ assert ext.slice_dim == None
+ with pytest.raises(ValueError):
+ setattr(ext, 'slice_dim', 3)
ext.slice_dim = 2
- eq_(ext.slice_dim, 2)
+ assert ext.slice_dim == 2
def test_dcmmeta_shape():
ext = dcmmeta.DcmMetaExtension.make_empty((64, 64, 2), np.eye(4))
- eq_(ext.shape, (64, 64, 2))
- assert_raises(ValueError,
- setattr,
- ext,
- 'shape',
- (64, 64)
- )
+ assert ext.shape == (64, 64, 2)
+ with pytest.raises(ValueError):
+ setattr(ext, 'shape', (64, 64))
ext.shape = (128, 128, 64)
- eq_(ext.shape, (128, 128, 64))
+ assert ext.shape == (128, 128, 64)
def test_dcmmeta_version():
ext = dcmmeta.DcmMetaExtension.make_empty((64, 64, 2), np.eye(4))
- eq_(ext.version, dcmmeta._meta_version)
+ assert ext.version == dcmmeta._meta_version
ext.version = 1.0
- eq_(ext.version, 1.0)
+ assert ext.version == 1.0
def test_dcmmeta_slice_norm():
ext = dcmmeta.DcmMetaExtension.make_empty((64, 64, 2),
np.eye(4),
np.eye(4),
2)
- ok_(np.allclose(ext.slice_normal, [0, 0, 1]))
+ assert(np.allclose(ext.slice_normal, [0, 0, 1]))
ext.slice_dim = 1
- ok_(np.allclose(ext.slice_normal, [0, 1, 0]))
+ assert(np.allclose(ext.slice_normal, [0, 1, 0]))
def test_dcmmeta_n_slices():
ext = dcmmeta.DcmMetaExtension.make_empty((64, 64, 2),
np.eye(4),
np.eye(4),
2)
- eq_(ext.n_slices, 2)
+ assert ext.n_slices == 2
ext.slice_dim = 1
- eq_(ext.n_slices, 64)
+ assert ext.n_slices == 64
class TestGetKeysClassesValues(object):
def setUp(self):
@@ -267,36 +263,35 @@ class TestGetKeysClassesValues(object):
self.ext.get_class_dict(classes)[key] = \
([0] * self.ext.get_multiplicity(classes))
+ def setup_method(self, setUp):
+ self.setUp()
def test_get_keys(self):
- eq_(set(self.keys), set(self.ext.get_keys()))
+ assert set(self.keys) == set(self.ext.get_keys())
def test_get_classification(self):
- eq_(self.ext.get_classification('foo'), None)
+ assert self.ext.get_classification('foo') == None
for classes in self.ext.get_valid_classes():
key = '%s_%s_test' % classes
- eq_(self.ext.get_classification(key), classes)
+ assert self.ext.get_classification(key) == classes
def test_get_class_dict(self):
for classes in self.ext.get_valid_classes():
key = '%s_%s_test' % classes
- ok_(key in self.ext.get_class_dict(classes))
+ assert(key in self.ext.get_class_dict(classes))
def test_get_values(self):
- eq_(self.ext.get_values('foo'), None)
+ assert self.ext.get_values('foo') == None
for classes in self.ext.get_valid_classes():
key = '%s_%s_test' % classes
- eq_(self.ext.get_values(key),
- [0] * self.ext.get_multiplicity(classes)
- )
+ assert self.ext.get_values(key) == [0] * self.ext.get_multiplicity(classes)
+
def test_get_vals_and_class(self):
- eq_(self.ext.get_values_and_class('foo'), (None, None))
+ assert self.ext.get_values_and_class('foo') == (None, None)
for classes in self.ext.get_valid_classes():
key = '%s_%s_test' % classes
- eq_(self.ext.get_values_and_class(key),
- ([0] * self.ext.get_multiplicity(classes), classes)
- )
+ assert(self.ext.get_values_and_class(key) == ([0] * self.ext.get_multiplicity(classes), classes))
class TestFiltering(object):
def setUp(self):
@@ -313,23 +308,26 @@ class TestFiltering(object):
self.ext.get_class_dict(classes)[prefix + 'foobaz'] = \
([0] * self.ext.get_multiplicity(classes))
+ def setup_method(self, setUp):
+ self.setUp()
+
def test_filter_all(self):
self.ext.filter_meta(lambda key, val: 'foo' in key)
- eq_(len(self.ext.get_keys()), 0)
+ assert len(self.ext.get_keys()) == 0
def test_filter_some(self):
self.ext.filter_meta(lambda key, val: key.endswith('baz'))
keys = self.ext.get_keys()
for classes in self.ext.get_valid_classes():
prefix = '%s_%s_test_' % classes
- ok_(prefix + 'foo' in keys)
- ok_(not prefix + 'foobaz' in keys)
+ assert(prefix + 'foo' in keys)
+ assert(not prefix + 'foobaz' in keys)
def test_clear_slices(self):
self.ext.clear_slice_meta()
for base_cls, sub_cls in self.ext.get_valid_classes():
if sub_cls == 'slices':
- eq_(len(self.ext.get_class_dict((base_cls, sub_cls))), 0)
+ assert len(self.ext.get_class_dict((base_cls, sub_cls))) == 0
class TestSimplify(object):
def setUp(self):
@@ -338,6 +336,8 @@ class TestSimplify(object):
np.eye(4),
2
)
+ def setup_method(self, setUp):
+ self.setUp()
def test_simplify_global_slices(self):
glob_slc = self.ext.get_class_dict(('global', 'slices'))
@@ -356,20 +356,20 @@ class TestSimplify(object):
glob_slc['Test5'] += [idx2 for idx2 in range(3)]
self.ext.check_valid()
- eq_(self.ext._simplify('Test1'), True)
- eq_(self.ext.get_classification('Test1'), ('global', 'const'))
+ assert self.ext._simplify('Test1') == True
+ assert self.ext.get_classification('Test1') == ('global', 'const')
- eq_(self.ext._simplify('Test2'), True)
- eq_(self.ext.get_classification('Test2'), ('vector', 'samples'))
+ assert self.ext._simplify('Test2') == True
+ assert self.ext.get_classification('Test2'), ('vector', 'samples')
- eq_(self.ext._simplify('Test3'), True)
- eq_(self.ext.get_classification('Test3'), ('time', 'samples'))
+ assert self.ext._simplify('Test3') == True
+ assert self.ext.get_classification('Test3') == ('time', 'samples')
- eq_(self.ext._simplify('Test4'), True)
- eq_(self.ext.get_classification('Test4'), ('vector', 'slices'))
+ assert self.ext._simplify('Test4') == True
+ assert self.ext.get_classification('Test4'), ('vector', 'slices')
- eq_(self.ext._simplify('Test5'), True)
- eq_(self.ext.get_classification('Test5'), ('time', 'slices'))
+ assert self.ext._simplify('Test5') == True
+ assert self.ext.get_classification('Test5'), ('time', 'slices')
def test_simplify_vector_slices(self):
vec_slc = self.ext.get_class_dict(('vector', 'slices'))
@@ -383,22 +383,22 @@ class TestSimplify(object):
vec_slc['Test3'] += [slc_idx]
self.ext.check_valid()
- eq_(self.ext._simplify('Test1'), True)
- eq_(self.ext.get_classification('Test1'), ('global', 'const'))
+ assert self.ext._simplify('Test1') == True
+ assert self.ext.get_classification('Test1') == ('global', 'const')
- eq_(self.ext._simplify('Test2'), True)
- eq_(self.ext.get_classification('Test2'), ('time', 'samples'))
+ assert self.ext._simplify('Test2') == True
+ assert self.ext.get_classification('Test2') == ('time', 'samples')
- eq_(self.ext._simplify('Test3'), True)
- eq_(self.ext.get_classification('Test3'), ('time', 'slices'))
+ assert self.ext._simplify('Test3') == True
+ assert self.ext.get_classification('Test3') == ('time', 'slices')
def test_simplify_time_slices(self):
time_slc = self.ext.get_class_dict(('time', 'slices'))
time_slc['Test1'] = [0] * 3
self.ext.check_valid()
- eq_(self.ext._simplify('Test1'), True)
- eq_(self.ext.get_classification('Test1'), ('global', 'const'))
+ assert self.ext._simplify('Test1') == True
+ assert self.ext.get_classification('Test1') == ('global', 'const')
def test_simplify_time_samples(self):
time_smp = self.ext.get_class_dict(('time', 'samples'))
@@ -408,20 +408,19 @@ class TestSimplify(object):
time_smp['Test2'] += [vec_idx] * 5
self.ext.check_valid()
- eq_(self.ext._simplify('Test1'), True)
- eq_(self.ext.get_values_and_class('Test1'),
- (0, ('global', 'const')))
+ assert self.ext._simplify('Test1') == True
+ assert self.ext.get_values_and_class('Test1') == (0, ('global', 'const'))
- eq_(self.ext._simplify('Test2'), True)
- eq_(self.ext.get_classification('Test2'), ('vector', 'samples'))
+ assert self.ext._simplify('Test2') == True
+ assert self.ext.get_classification('Test2') == ('vector', 'samples')
def test_simplify_vector_samples(self):
vector_smp = self.ext.get_class_dict(('vector', 'samples'))
vector_smp['Test1'] = [0] * 7
self.ext.check_valid()
- eq_(self.ext._simplify('Test1'), True)
- eq_(self.ext.get_classification('Test1'), ('global', 'const'))
+ assert self.ext._simplify('Test1') == True
+ assert self.ext.get_classification('Test1') == ('global', 'const')
def test_simp_sngl_slc_5d():
ext = dcmmeta.DcmMetaExtension.make_empty((64, 64, 1, 3, 5),
@@ -432,9 +431,7 @@ def test_simp_sngl_slc_5d():
glob_slc = ext.get_class_dict(('global', 'slices'))
glob_slc['test1'] = list(range(15))
ext._simplify('test1')
- eq_(ext.get_values_and_class('test1'),
- (list(range(15)), ('time','samples'))
- )
+ assert ext.get_values_and_class('test1') == (list(range(15)), ('time','samples'))
class TestGetSubset(object):
def setUp(self):
@@ -450,6 +447,9 @@ class TestGetSubset(object):
mult = self.ext.get_multiplicity(classes)
self.ext.get_class_dict(classes)[key] = list(range(mult))
+ def setup_method(self, setUp):
+ self.setUp()
+
def test_slice_subset(self):
for slc_idx in range(self.ext.n_slices):
sub = self.ext.get_subset(2, slc_idx)
@@ -458,20 +458,15 @@ class TestGetSubset(object):
for classes in self.ext.get_valid_classes():
key = '%s_%s_test' % classes
if classes == ('time', 'slices'):
- eq_(sub.get_values_and_class(key),
- (slc_idx, ('global', 'const'))
- )
+ assert sub.get_values_and_class(key) ==(slc_idx, ('global', 'const'))
+
elif classes == ('vector', 'slices'):
- eq_(sub.get_values_and_class(key),
- ((list(range(slc_idx, (3 * 5), 3)) * 7), ('time', 'samples'))
- )
+ assert sub.get_values_and_class(key) == ((list(range(slc_idx, (3 * 5), 3)) * 7), ('time', 'samples'))
+
elif classes == ('global', 'slices'):
- eq_(sub.get_values_and_class(key),
- (list(range(slc_idx, (3 * 5 * 7), 3)), ('time', 'samples')))
+ assert sub.get_values_and_class(key) == (list(range(slc_idx, (3 * 5 * 7), 3)), ('time', 'samples'))
else:
- eq_(sub.get_values_and_class(key),
- self.ext.get_values_and_class(key)
- )
+ assert sub.get_values_and_class(key) == self.ext.get_values_and_class(key)
def test_slice_subset_simplify(self):
vals = []
@@ -497,10 +492,8 @@ class TestGetSubset(object):
sub = self.ext.get_subset(2, 1)
sub.check_valid()
- eq_(sub.get_values_and_class('vec_slc_to_const'),
- (1, ('global', 'const')))
- eq_(sub.get_values_and_class('glb_slc_to_const'),
- (1, ('global', 'const')))
+ assert sub.get_values_and_class('vec_slc_to_const') == (1, ('global', 'const'))
+ assert sub.get_values_and_class('glb_slc_to_const') == (1, ('global', 'const'))
def test_time_sample_subset(self):
for time_idx in range(5):
@@ -509,37 +502,28 @@ class TestGetSubset(object):
for classes in self.ext.get_valid_classes():
key = '%s_%s_test' % classes
if classes[0] == 'time':
- ok_(not classes in sub.get_valid_classes())
+ assert(not classes in sub.get_valid_classes())
if classes[1] == 'samples':
- eq_(sub.get_values_and_class(key),
- (list(range(time_idx, 5 * 7, 5)), ('vector', 'samples'))
- )
+ assert sub.get_values_and_class(key) == (list(range(time_idx, 5 * 7, 5)), ('vector', 'samples'))
elif classes[1] == 'slices':
- eq_(sub.get_values_and_class(key),
- (self.ext.get_values(key), ('vector', 'slices')))
+ assert sub.get_values_and_class(key) == (self.ext.get_values(key), ('vector', 'slices'))
elif classes[0] == 'vector':
if classes[1] == 'samples':
- eq_(sub.get_values_and_class(key),
- self.ext.get_values_and_class(key)
- )
+ assert sub.get_values_and_class(key) == self.ext.get_values_and_class(key)
elif classes[1] == 'slices':
start = time_idx * 3
end = start + 3
- eq_(sub.get_values_and_class(key),
- (list(range(start, end)), ('vector', 'slices')))
+ assert sub.get_values_and_class(key) == (list(range(start, end)), ('vector', 'slices'))
else:
if classes[1] == 'const':
- eq_(sub.get_values_and_class(key),
- self.ext.get_values_and_class(key)
- )
+ assert sub.get_values_and_class(key) == self.ext.get_values_and_class(key)
elif classes[1] == 'slices':
vals = []
for vec_idx in range(7):
start = (vec_idx * (3 * 5)) + (time_idx * 3)
end = start + 3
vals += list(range(start, end))
- eq_(sub.get_values_and_class(key),
- (vals, ('global', 'slices')))
+ assert sub.get_values_and_class(key) == (vals, ('global', 'slices'))
def test_time_sample_subset_simplify(self):
#Test for simplification of time samples that become constant
@@ -553,8 +537,7 @@ class TestGetSubset(object):
for time_idx in range(5):
sub = self.ext.get_subset(3, time_idx)
sub.check_valid()
- eq_(sub.get_values_and_class('time_smp_to_const'),
- (time_idx, ('global', 'const')))
+ assert sub.get_values_and_class('time_smp_to_const') == (time_idx, ('global', 'const'))
#Test for simplification of vector slices that become constant
vals = []
@@ -581,10 +564,8 @@ class TestGetSubset(object):
sub = self.ext.get_subset(3, 1)
sub.check_valid()
- eq_(sub.get_values_and_class('vec_slc_to_const'),
- (1, ('global', 'const')))
- eq_(sub.get_values_and_class('glb_slc_to_const'),
- (1, ('global', 'const')))
+ assert sub.get_values_and_class('vec_slc_to_const') == (1, ('global', 'const'))
+ assert sub.get_values_and_class('glb_slc_to_const') == (1, ('global', 'const'))
#Test simplification of global slices that become vector slices or
#samples
@@ -603,11 +584,9 @@ class TestGetSubset(object):
sub = self.ext.get_subset(3, time_idx)
sub.check_valid()
if time_idx == 1:
- eq_(sub.get_values_and_class('glb_slc_to_vec'),
- (list(range(3)), ('vector', 'slices')))
+ assert sub.get_values_and_class('glb_slc_to_vec') == (list(range(3)), ('vector', 'slices'))
else:
- eq_(sub.get_values_and_class('glb_slc_to_vec'),
- (list(range(7)), ('vector', 'samples')))
+ assert sub.get_values_and_class('glb_slc_to_vec') == (list(range(7)), ('vector', 'samples'))
def test_vector_sample_subset(self):
for vector_idx in range(7):
@@ -616,35 +595,25 @@ class TestGetSubset(object):
for classes in self.ext.get_valid_classes():
key = '%s_%s_test' % classes
if classes[0] == 'vector':
- ok_(not classes in sub.get_valid_classes())
+ assert(not classes in sub.get_valid_classes())
if classes[1] == 'samples':
- eq_(sub.get_values_and_class(key),
- (vector_idx, ('global', 'const'))
- )
+ assert sub.get_values_and_class(key) == (vector_idx, ('global', 'const'))
elif classes[1] == 'slices':
- eq_(sub.get_values_and_class(key),
- (list(range(3 * 5)), ('global', 'slices'))
- )
+ assert sub.get_values_and_class(key) == (list(range(3 * 5)), ('global', 'slices'))
elif classes[0] == 'time':
if classes[1] == 'samples': #Could be const
start = vector_idx * 5
end = start + 5
- eq_(sub.get_values_and_class(key),
- (list(range(start, end)), classes)
- )
+ assert sub.get_values_and_class(key) == (list(range(start, end)), classes)
elif classes[1] == 'slices':
- eq_(sub.get_values_and_class(key),
- self.ext.get_values_and_class(key))
+ assert sub.get_values_and_class(key) == self.ext.get_values_and_class(key)
else:
if classes[1] == 'const':
- eq_(sub.get_values_and_class(key),
- self.ext.get_values_and_class(key)
- )
+ assert sub.get_values_and_class(key) == self.ext.get_values_and_class(key)
elif classes[1] == 'slices': #Could be const or time samples or time slices
start = vector_idx * (3 * 5)
end = start + (3 * 5)
- eq_(sub.get_values_and_class(key),
- (list(range(start, end)), classes))
+ assert sub.get_values_and_class(key) == (list(range(start, end)), classes)
def test_vector_sample_subset_simplify(self):
@@ -659,8 +628,7 @@ class TestGetSubset(object):
self.ext.get_class_dict(('time', 'samples'))['time_smp_to_const'] = \
vals
sub = self.ext.get_subset(4, 1)
- eq_(sub.get_values_and_class('time_smp_to_const'),
- (1, ('global', 'const')))
+ assert sub.get_values_and_class('time_smp_to_const') == (1, ('global', 'const'))
#Test for simplification of global slices that become constant, time
#samples, or time slices
@@ -681,14 +649,11 @@ class TestGetSubset(object):
sub = self.ext.get_subset(4, vector_idx)
sub.check_valid()
if vector_idx == 1:
- eq_(sub.get_values_and_class('glb_slc'),
- (1, ('global', 'const')))
+ assert sub.get_values_and_class('glb_slc') == (1, ('global', 'const'))
elif vector_idx == 2:
- eq_(sub.get_values_and_class('glb_slc'),
- (list(range(3)), ('time', 'slices')))
+ assert sub.get_values_and_class('glb_slc') == (list(range(3)), ('time', 'slices'))
else:
- eq_(sub.get_values_and_class('glb_slc'),
- (list(range(5)), ('time', 'samples')))
+ assert sub.get_values_and_class('glb_slc') == (list(range(5)), ('time', 'samples'))
class TestChangeClass(object):
def setUp(self):
@@ -707,80 +672,55 @@ class TestChangeClass(object):
vals = list(range(mult))
self.ext.get_class_dict(classes)[key] = vals
+ def setup_method(self, setUp):
+ self.setUp()
+
def test_change_none(self):
- eq_(self.ext._get_changed_class('None_test', ('global', 'const')),
- None)
- eq_(self.ext._get_changed_class('None_test', ('global', 'slices')),
- [None] * (3 * 5 * 7))
- eq_(self.ext._get_changed_class('None_test', ('time', 'samples')),
- [None] * (5 * 7))
- eq_(self.ext._get_changed_class('None_test', ('time', 'slices')),
- [None] * 3)
- eq_(self.ext._get_changed_class('None_test', ('vector', 'samples')),
- [None] * 7)
- eq_(self.ext._get_changed_class('None_test', ('vector', 'slices')),
- [None] * (3 * 5))
+ assert self.ext._get_changed_class('None_test', ('global', 'const')) == None
+ assert self.ext._get_changed_class('None_test', ('global', 'slices')) == [None] * (3 * 5 * 7)
+ assert self.ext._get_changed_class('None_test', ('time', 'samples')) ==[None] * (5 * 7)
+ assert self.ext._get_changed_class('None_test', ('time', 'slices')) == [None] * 3
+ assert self.ext._get_changed_class('None_test', ('vector', 'samples')) == [None] * 7
+ assert self.ext._get_changed_class('None_test', ('vector', 'slices')) == [None] * (3 * 5)
def test_change_global_const(self):
- eq_(self.ext._get_changed_class('global_const_test',
- ('global', 'slices')),
- [0] * (3 * 5 * 7))
- eq_(self.ext._get_changed_class('global_const_test',
- ('time', 'samples')),
- [0] * (5 * 7))
- eq_(self.ext._get_changed_class('global_const_test',
- ('time', 'slices')),
- [0] * 3)
- eq_(self.ext._get_changed_class('global_const_test',
- ('vector', 'samples')),
- [0] * 7)
- eq_(self.ext._get_changed_class('global_const_test',
- ('vector', 'slices')),
- [0] * (3 * 5))
+ assert self.ext._get_changed_class('global_const_test', ('global', 'slices')) == [0] * (3 * 5 * 7)
+ assert self.ext._get_changed_class('global_const_test', ('time', 'samples')) == [0] * (5 * 7)
+ assert self.ext._get_changed_class('global_const_test', ('time', 'slices')) == [0] * 3
+ assert self.ext._get_changed_class('global_const_test', ('vector', 'samples')) == [0] * 7
+ assert self.ext._get_changed_class('global_const_test', ('vector', 'slices')) == [0] * (3 * 5)
def test_change_vector_samples(self):
vals = []
for vector_idx in range(7):
vals += [vector_idx] * 15
- eq_(self.ext._get_changed_class('vector_samples_test',
- ('global', 'slices')),
- vals)
+ assert self.ext._get_changed_class('vector_samples_test', ('global', 'slices')) == vals
vals = []
for vector_idx in range(7):
vals += [vector_idx] * 5
- eq_(self.ext._get_changed_class('vector_samples_test',
- ('time', 'samples')),
- vals)
+ assert self.ext._get_changed_class('vector_samples_test', ('time', 'samples')) == vals
def test_change_time_samples(self):
vals = []
for time_idx in range(5 * 7):
vals += [time_idx] * 3
- eq_(self.ext._get_changed_class('time_samples_test',
- ('global', 'slices')),
- vals)
+ assert self.ext._get_changed_class('time_samples_test', ('global', 'slices')) == vals
def test_time_slices(self):
vals = []
for time_idx in range(5 * 7):
vals += list(range(3))
- eq_(self.ext._get_changed_class('time_slices_test',
- ('global', 'slices')),
- vals)
+ assert self.ext._get_changed_class('time_slices_test', ('global', 'slices')) == vals
vals = []
for time_idx in range(5):
vals += list(range(3))
- eq_(self.ext._get_changed_class('time_slices_test',
- ('vector', 'slices')),
- vals)
+ assert self.ext._get_changed_class('time_slices_test', ('vector', 'slices')) == vals
def test_vector_slices(self):
vals = []
for vector_idx in range(7):
vals += list(range(15))
- eq_(self.ext._get_changed_class('vector_slices_test',
- ('global', 'slices')),
- vals)
+ assert self.ext._get_changed_class('vector_slices_test', ('global', 'slices')) == vals
def test_from_sequence_2d_to_3d():
@@ -799,12 +739,9 @@ def test_from_sequence_2d_to_3d():
ext2.get_class_dict(('global', 'const'))['var'] = 2
merged = dcmmeta.DcmMetaExtension.from_sequence([ext1, ext2], 2)
- eq_(merged.get_values_and_class('const'),
- (1, ('global', 'const')))
- eq_(merged.get_values_and_class('var'),
- ([1, 2], ('global', 'slices')))
- eq_(merged.get_values_and_class('missing'),
- ([1, None], ('global', 'slices')))
+ assert merged.get_values_and_class('const') == (1, ('global', 'const'))
+ assert merged.get_values_and_class('var') == ([1, 2], ('global', 'slices'))
+ assert merged.get_values_and_class('missing') == ([1, None], ('global', 'slices'))
def test_from_sequence_3d_to_4d():
for dim_name, dim in (('time', 3), ('vector', 4)):
@@ -828,18 +765,12 @@ def test_from_sequence_3d_to_4d():
ext2.get_class_dict(('global', 'slices'))['global_slices_var'] = [1, 2]
merged = dcmmeta.DcmMetaExtension.from_sequence([ext1, ext2], dim)
- eq_(merged.get_values_and_class('global_const_const'),
- (1, ('global', 'const')))
- eq_(merged.get_values_and_class('global_const_var'),
- ([1, 2], (dim_name, 'samples')))
- eq_(merged.get_values_and_class('global_const_missing'),
- ([1, None], (dim_name, 'samples')))
- eq_(merged.get_values_and_class('global_slices_const'),
- ([0, 1], (dim_name, 'slices')))
- eq_(merged.get_values_and_class('global_slices_var'),
- ([0, 1, 1, 2], ('global', 'slices')))
- eq_(merged.get_values_and_class('global_slices_missing'),
- ([0, 1, None, None], ('global', 'slices')))
+ assert merged.get_values_and_class('global_const_const'), (1, ('global', 'const'))
+ assert merged.get_values_and_class('global_const_var') == ([1, 2], (dim_name, 'samples'))
+ assert merged.get_values_and_class('global_const_missing') == ([1, None], (dim_name, 'samples'))
+ assert merged.get_values_and_class('global_slices_const') == ([0, 1], (dim_name, 'slices'))
+ assert merged.get_values_and_class('global_slices_var') == ([0, 1, 1, 2], ('global', 'slices'))
+ assert merged.get_values_and_class('global_slices_missing') == ([0, 1, None, None], ('global', 'slices'))
def test_from_sequence_4d_time_to_5d():
ext1 = dcmmeta.DcmMetaExtension.make_empty((2, 2, 2, 2),
@@ -873,30 +804,18 @@ def test_from_sequence_4d_time_to_5d():
ext2.get_class_dict(('time', 'slices'))['time_slices_var'] = [1, 2]
merged = dcmmeta.DcmMetaExtension.from_sequence([ext1, ext2], 4)
- eq_(merged.get_values_and_class('global_const_const'),
- (1, ('global', 'const')))
- eq_(merged.get_values_and_class('global_const_var'),
- ([1, 2], ('vector', 'samples')))
- eq_(merged.get_values_and_class('global_const_missing'),
- ([1, None], ('vector', 'samples')))
- eq_(merged.get_values_and_class('global_slices_const'),
- ([0, 1, 2, 3], ('vector', 'slices')))
- eq_(merged.get_values_and_class('global_slices_var'),
- ([0, 1, 2, 3, 1, 2, 3, 4], ('global', 'slices')))
- eq_(merged.get_values_and_class('global_slices_missing'),
- ([0, 1, 2, 3, None, None, None, None], ('global', 'slices')))
- eq_(merged.get_values_and_class('time_samples_const'),
- ([0, 1, 0, 1], ('time', 'samples')))
- eq_(merged.get_values_and_class('time_samples_var'),
- ([0, 1, 1, 2], ('time', 'samples')))
- eq_(merged.get_values_and_class('time_samples_missing'),
- ([0, 1, None, None], ('time', 'samples')))
- eq_(merged.get_values_and_class('time_slices_const'),
- ([0, 1], ('time', 'slices')))
- eq_(merged.get_values_and_class('time_slices_var'),
- ([0, 1, 0, 1, 1, 2, 1, 2], ('global', 'slices')))
- eq_(merged.get_values_and_class('time_slices_missing'),
- ([0, 1, 0, 1, None, None, None, None], ('global', 'slices')))
+ assert merged.get_values_and_class('global_const_const') == (1, ('global', 'const'))
+ assert merged.get_values_and_class('global_const_var') == ([1, 2], ('vector', 'samples'))
+ assert merged.get_values_and_class('global_const_missing') == ([1, None], ('vector', 'samples'))
+ assert merged.get_values_and_class('global_slices_const') == ([0, 1, 2, 3], ('vector', 'slices'))
+ assert merged.get_values_and_class('global_slices_var') == ([0, 1, 2, 3, 1, 2, 3, 4], ('global', 'slices'))
+ assert merged.get_values_and_class('global_slices_missing') == ([0, 1, 2, 3, None, None, None, None], ('global', 'slices'))
+ assert merged.get_values_and_class('time_samples_const') == ([0, 1, 0, 1], ('time', 'samples'))
+ assert merged.get_values_and_class('time_samples_var') == ([0, 1, 1, 2], ('time', 'samples'))
+ assert merged.get_values_and_class('time_samples_missing') == ([0, 1, None, None], ('time', 'samples'))
+ assert merged.get_values_and_class('time_slices_const') == ([0, 1], ('time', 'slices'))
+ assert merged.get_values_and_class('time_slices_var') == ([0, 1, 0, 1, 1, 2, 1, 2], ('global', 'slices'))
+ assert merged.get_values_and_class('time_slices_missing') == ([0, 1, 0, 1, None, None, None, None], ('global', 'slices'))
def test_from_sequence_no_slc():
ext1 = dcmmeta.DcmMetaExtension.make_empty((2, 2, 2), np.eye(4))
@@ -905,19 +824,18 @@ def test_from_sequence_no_slc():
def test_nifti_wrapper_init():
nii = nb.Nifti1Image(np.zeros((5, 5, 5)), np.eye(4))
- assert_raises(dcmmeta.MissingExtensionError,
- dcmmeta.NiftiWrapper,
- nii)
+ with pytest.raises(dcmmeta.MissingExtensionError):
+ dcmmeta.NiftiWrapper(nii)
hdr = nii.header
ext = dcmmeta.DcmMetaExtension.make_empty((5, 5, 5), np.eye(4))
hdr.extensions.append(ext)
nw = dcmmeta.NiftiWrapper(nii)
- eq_(nw.meta_ext, ext)
+ assert nw.meta_ext == ext
nii2 = nb.Nifti1Image(np.zeros((5, 5, 5)), np.eye(4))
nw2 = dcmmeta.NiftiWrapper(nii, True)
ext2 = nw2.meta_ext
- eq_(ext, ext2)
+ assert ext == ext2
class TestMetaValid(object):
def setUp(self):
@@ -926,7 +844,10 @@ class TestMetaValid(object):
hdr.set_dim_info(None, None, 2)
self.nw = dcmmeta.NiftiWrapper(nii, True)
for classes in self.nw.meta_ext.get_valid_classes():
- ok_(self.nw.meta_valid(classes))
+ assert(self.nw.meta_valid(classes))
+
+ def setup_method(self, setUp):
+ self.setUp()
def test_time_samples_changed(self):
self.nw.meta_ext.shape = (5, 5, 5, 3, 9)
@@ -934,9 +855,9 @@ class TestMetaValid(object):
if classes in (('time', 'samples'),
('vector', 'slices'),
('global', 'slices')):
- eq_(self.nw.meta_valid(classes), False)
+ assert self.nw.meta_valid(classes) == False
else:
- ok_(self.nw.meta_valid(classes))
+ assert(self.nw.meta_valid(classes))
def test_vector_samples_changed(self):
self.nw.meta_ext.shape = (5, 5, 5, 7, 3)
@@ -944,17 +865,17 @@ class TestMetaValid(object):
if classes in (('time', 'samples'),
('vector', 'samples'),
('global', 'slices')):
- eq_(self.nw.meta_valid(classes), False)
+ assert self.nw.meta_valid(classes) == False
else:
- ok_(self.nw.meta_valid(classes))
+ assert(self.nw.meta_valid(classes))
def test_slice_dim_changed(self):
self.nw.meta_ext.slice_dim = 0
for classes in self.nw.meta_ext.get_valid_classes():
if classes[1] == 'slices':
- eq_(self.nw.meta_valid(classes), False)
+ assert self.nw.meta_valid(classes) == False
else:
- ok_(self.nw.meta_valid(classes))
+ assert(self.nw.meta_valid(classes))
def test_slice_dir_changed(self):
aff = self.nw.nii_img.affine
@@ -966,9 +887,9 @@ class TestMetaValid(object):
for classes in self.nw.meta_ext.get_valid_classes():
if classes[1] == 'slices':
- eq_(self.nw.meta_valid(classes), False)
+ assert self.nw.meta_valid(classes) == False
else:
- ok_(self.nw.meta_valid(classes))
+ assert(self.nw.meta_valid(classes))
class TestGetMeta(object):
def setUp(self):
@@ -987,93 +908,71 @@ class TestGetMeta(object):
vals = list(range(mult))
self.nw.meta_ext.get_class_dict(classes)[key] = vals
- def test_invalid_index(self):
- assert_raises(IndexError,
- self.nw.get_meta('time_samples_test'),
- (0, 0, 0, 0))
- assert_raises(IndexError,
- self.nw.get_meta('time_samples_test'),
- (0, 0, 0, 0, 0, 0))
- assert_raises(IndexError,
- self.nw.get_meta('time_samples_test'),
- (6, 0, 0, 0, 0))
- assert_raises(IndexError,
- self.nw.get_meta('time_samples_test'),
- (-1, 0, 0, 0, 0))
+ def setup_method(self, setUp):
+ self.setUp()
def test_get_item(self):
for classes in self.nw.meta_ext.get_valid_classes():
key = '%s_%s_test' % classes
if classes == ('global', 'const'):
- eq_(self.nw[key], 0)
+ assert self.nw[key] == 0
else:
- assert_raises(KeyError,
- self.nw.__getitem__,
- key)
+ with pytest.raises(KeyError):
+ self.nw.__getitem__(key)
def test_get_const(self):
- eq_(self.nw.get_meta('global_const_test'), 0)
- eq_(self.nw.get_meta('global_const_test', (0, 0, 0, 0, 0)), 0)
- eq_(self.nw.get_meta('global_const_test', (0, 0, 3, 4, 5)), 0)
+ assert self.nw.get_meta('global_const_test') == 0
+ assert self.nw.get_meta('global_const_test', (0, 0, 0, 0, 0)) == 0
+ assert self.nw.get_meta('global_const_test', (0, 0, 3, 4, 5)) == 0
def test_get_global_slices(self):
- eq_(self.nw.get_meta('global_slices_test'), None)
- eq_(self.nw.get_meta('global_slices_test', None, 0), 0)
+ assert self.nw.get_meta('global_slices_test') == None
+ assert self.nw.get_meta('global_slices_test', None, 0) == 0
for vector_idx in range(9):
for time_idx in range(7):
for slice_idx in range(5):
idx = (0, 0, slice_idx, time_idx, vector_idx)
- eq_(self.nw.get_meta('global_slices_test', idx),
- slice_idx + (time_idx * 5) + (vector_idx * 7 * 5)
- )
+ assert self.nw.get_meta('global_slices_test', idx) == slice_idx + (time_idx * 5) + (vector_idx * 7 * 5)
def test_get_vector_slices(self):
- eq_(self.nw.get_meta('vector_slices_test'), None)
- eq_(self.nw.get_meta('vector_slices_test', None, 0), 0)
+ assert self.nw.get_meta('vector_slices_test') == None
+ assert self.nw.get_meta('vector_slices_test', None, 0) == 0
for vector_idx in range(9):
for time_idx in range(7):
for slice_idx in range(5):
idx = (0, 0, slice_idx, time_idx, vector_idx)
- eq_(self.nw.get_meta('vector_slices_test', idx),
- slice_idx + (time_idx * 5)
- )
+ assert self.nw.get_meta('vector_slices_test', idx) == slice_idx + (time_idx * 5)
def test_get_time_slices(self):
- eq_(self.nw.get_meta('time_slices_test'), None)
- eq_(self.nw.get_meta('time_slices_test', None, 0), 0)
+ assert self.nw.get_meta('time_slices_test') == None
+ assert self.nw.get_meta('time_slices_test', None, 0) == 0
for vector_idx in range(9):
for time_idx in range(7):
for slice_idx in range(5):
idx = (0, 0, slice_idx, time_idx, vector_idx)
- eq_(self.nw.get_meta('time_slices_test', idx),
- slice_idx
- )
+ assert self.nw.get_meta('time_slices_test', idx) == slice_idx
def test_get_vector_samples(self):
- eq_(self.nw.get_meta('vector_samples_test'), None)
- eq_(self.nw.get_meta('vector_samples_test', None, 0), 0)
+ assert self.nw.get_meta('vector_samples_test') == None
+ assert self.nw.get_meta('vector_samples_test', None, 0) == 0
for vector_idx in range(9):
for time_idx in range(7):
for slice_idx in range(5):
idx = (0, 0, slice_idx, time_idx, vector_idx)
- eq_(self.nw.get_meta('vector_samples_test', idx),
- vector_idx
- )
+ assert self.nw.get_meta('vector_samples_test', idx) == vector_idx
def get_time_samples(self):
- eq_(self.nw.get_meta('time_samples_test'), None)
- eq_(self.nw.get_meta('time_samples_test', None, 0), 0)
+ assert self.nw.get_meta('time_samples_test') == None
+ assert self.nw.get_meta('time_samples_test', None, 0) == 0
for vector_idx in range(9):
for time_idx in range(7):
for slice_idx in range(5):
idx = (0, 0, slice_idx, time_idx, vector_idx)
- eq_(self.nw.get_meta('time_samples_test', idx),
- time_idx + (vector_idx * 7)
- )
+ assert self.nw.get_meta('time_samples_test', idx) == time_idx + (vector_idx * 7)
class TestSplit(object):
def setUp(self):
- self.arr = np.arange(3 * 3 * 3 * 5 * 7).reshape(3, 3, 3, 5, 7)
+ self.arr = np.arange(3 * 3 * 3 * 5 * 7, dtype=np.int32).reshape(3, 3, 3, 5, 7)
nii = nb.Nifti1Image(self.arr, np.diag([1.1, 1.1, 1.1, 1.0]))
hdr = nii.header
hdr.set_dim_info(None, None, 2)
@@ -1089,10 +988,13 @@ class TestSplit(object):
vals = list(range(mult))
self.nw.meta_ext.get_class_dict(classes)[key] = vals
+ def setup_method(self, setUp):
+ self.setUp()
+
def test_split_slice(self):
for split_idx, nw_split in enumerate(self.nw.split(2)):
- eq_(nw_split.nii_img.shape, (3, 3, 1, 5, 7))
- ok_(np.allclose(nw_split.nii_img.affine,
+ assert nw_split.nii_img.shape == (3, 3, 1, 5, 7)
+ assert(np.allclose(nw_split.nii_img.affine,
np.c_[[1.1, 0.0, 0.0, 0.0],
[0.0, 1.1, 0.0, 0.0],
[0.0, 0.0, 1.1, 0.0],
@@ -1100,35 +1002,35 @@ class TestSplit(object):
]
)
)
- ok_(np.all(nw_split.nii_img.get_data() ==
+ assert(np.all(np.asanyarray(nw_split.nii_img.dataobj) ==
self.arr[:, :, split_idx:split_idx+1, :, :])
)
def test_split_time(self):
for split_idx, nw_split in enumerate(self.nw.split(3)):
- eq_(nw_split.nii_img.shape, (3, 3, 3, 1, 7))
- ok_(np.allclose(nw_split.nii_img.affine,
+ assert nw_split.nii_img.shape == (3, 3, 3, 1, 7)
+ assert(np.allclose(nw_split.nii_img.affine,
np.diag([1.1, 1.1, 1.1, 1.0])))
- ok_(np.all(nw_split.nii_img.get_data() ==
+ assert(np.all(np.asanyarray(nw_split.nii_img.dataobj) ==
self.arr[:, :, :, split_idx:split_idx+1, :])
)
def test_split_vector(self):
for split_idx, nw_split in enumerate(self.nw.split(4)):
- eq_(nw_split.nii_img.shape, (3, 3, 3, 5))
- ok_(np.allclose(nw_split.nii_img.affine,
+ assert nw_split.nii_img.shape == (3, 3, 3, 5)
+ assert(np.allclose(nw_split.nii_img.affine,
np.diag([1.1, 1.1, 1.1, 1.0])))
- ok_(np.all(nw_split.nii_img.get_data() ==
+ assert(np.all(np.asanyarray(nw_split.nii_img.dataobj) ==
self.arr[:, :, :, :, split_idx])
)
def test_split_keep_spatial():
- arr = np.arange(3 * 3 * 3).reshape(3, 3, 3)
+ arr = np.arange(3 * 3 * 3, dtype=np.int32).reshape(3, 3, 3)
nii = nb.Nifti1Image(arr, np.eye(4))
nw = dcmmeta.NiftiWrapper(nii, True)
for split_idx, nw_split in enumerate(nw.split(2)):
- eq_(nw_split.nii_img.shape, (3, 3, 1))
+ assert nw_split.nii_img.shape == (3, 3, 1)
def test_from_dicom():
@@ -1142,20 +1044,18 @@ def test_from_dicom():
meta = {'EchoTime': 40}
nw = dcmmeta.NiftiWrapper.from_dicom(src_dcm, meta)
hdr = nw.nii_img.header
- eq_(nw.nii_img.shape, (192, 192, 1))
- ok_(np.allclose(np.dot(np.diag([-1., -1., 1., 1.]), src_dw.get_affine()),
+ assert nw.nii_img.shape == (192, 192, 1)
+ assert(np.allclose(np.dot(np.diag([-1., -1., 1., 1.]), src_dw.affine),
nw.nii_img.affine)
)
- eq_(hdr.get_xyzt_units(), ('mm', 'sec'))
- eq_(hdr.get_dim_info(), (0, 1, 2))
- eq_(nw.meta_ext.get_values_and_class('EchoTime'),
- (40, ('global', 'const'))
- )
+ assert hdr.get_xyzt_units() == ('mm', 'sec')
+ assert hdr.get_dim_info() == (0, 1, 2)
+ assert nw.meta_ext.get_values_and_class('EchoTime') == (40, ('global', 'const'))
def test_from_2d_slice_to_3d():
slice_nws = []
for idx in range(3):
- arr = np.arange(idx * (4 * 4), (idx + 1) * (4 * 4)).reshape(4, 4, 1)
+ arr = np.arange(idx * (4 * 4), (idx + 1) * (4 * 4), dtype=np.int32).reshape(4, 4, 1)
aff = np.diag((1.1, 1.1, 1.1, 1.0))
aff[:3, 3] += [0.0, 0.0, idx * 0.5]
nii = nb.Nifti1Image(arr, aff)
@@ -1168,30 +1068,27 @@ def test_from_2d_slice_to_3d():
slice_nws.append(nw)
merged = dcmmeta.NiftiWrapper.from_sequence(slice_nws, 2)
- eq_(merged.nii_img.shape, (4, 4, 3))
- ok_(np.allclose(merged.nii_img.affine,
+ assert merged.nii_img.shape == (4, 4, 3)
+ assert(np.allclose(merged.nii_img.affine,
np.diag((1.1, 1.1, 0.5, 1.0)))
)
- eq_(merged.meta_ext.get_values_and_class('EchoTime'),
- (40, ('global', 'const'))
- )
- eq_(merged.meta_ext.get_values_and_class('SliceLocation'),
- (list(range(3)), ('global', 'slices'))
- )
+ assert merged.meta_ext.get_values_and_class('EchoTime') == (40, ('global', 'const'))
+ assert merged.meta_ext.get_values_and_class('SliceLocation') == (list(range(3)), ('global', 'slices'))
merged_hdr = merged.nii_img.header
- eq_(merged_hdr.get_dim_info(), (0, 1, 2))
- eq_(merged_hdr.get_xyzt_units(), ('mm', 'sec'))
- merged_data = merged.nii_img.get_data()
+ assert merged_hdr.get_dim_info() == (0, 1, 2)
+ assert merged_hdr.get_xyzt_units() == ('mm', 'sec')
+ merged_data = np.asanyarray(merged.nii_img.dataobj)
for idx in range(3):
- ok_(np.all(merged_data[:, :, idx] ==
- np.arange(idx * (4 * 4), (idx + 1) * (4 * 4)).reshape(4, 4))
+ assert(np.all(merged_data[:, :, idx] ==
+ np.arange(idx * (4 * 4), (idx + 1) * (4 * 4), dtype=np.int32).reshape(4, 4))
)
def test_from_3d_time_to_4d():
time_nws = []
for idx in range(3):
arr = np.arange(idx * (4 * 4 * 4),
- (idx + 1) * (4 * 4 * 4)
+ (idx + 1) * (4 * 4 * 4),
+ dtype=np.int32
).reshape(4, 4, 4)
nii = nb.Nifti1Image(arr, np.diag((1.1, 1.1, 1.1, 1.0)))
hdr = nii.header
@@ -1207,37 +1104,31 @@ def test_from_3d_time_to_4d():
time_nws.append(nw)
merged = dcmmeta.NiftiWrapper.from_sequence(time_nws, 3)
- eq_(merged.nii_img.shape, (4, 4, 4, 3))
- ok_(np.allclose(merged.nii_img.affine,
+ assert merged.nii_img.shape == (4, 4, 4, 3)
+ assert(np.allclose(merged.nii_img.affine,
np.diag((1.1, 1.1, 1.1, 1.0)))
)
- eq_(merged.meta_ext.get_values_and_class('PatientID'),
- ('Test', ('global', 'const'))
- )
- eq_(merged.meta_ext.get_values_and_class('EchoTime'),
- ([0, 1, 2], ('time', 'samples'))
- )
- eq_(merged.meta_ext.get_values_and_class('SliceLocation'),
- (list(range(4)), ('time', 'slices'))
- )
- eq_(merged.meta_ext.get_values_and_class('AcquisitionTime'),
- (list(range(4 * 3)), ('global', 'slices'))
- )
+ assert merged.meta_ext.get_values_and_class('PatientID') == ('Test', ('global', 'const'))
+ assert merged.meta_ext.get_values_and_class('EchoTime') == ([0, 1, 2], ('time', 'samples'))
+ assert merged.meta_ext.get_values_and_class('SliceLocation') == (list(range(4)), ('time', 'slices'))
+ assert merged.meta_ext.get_values_and_class('AcquisitionTime') == (list(range(4 * 3)), ('global', 'slices'))
merged_hdr = merged.nii_img.header
- eq_(merged_hdr.get_dim_info(), (0, 1, 2))
- eq_(merged_hdr.get_xyzt_units(), ('mm', 'sec'))
- merged_data = merged.nii_img.get_data()
+ assert merged_hdr.get_dim_info() == (0, 1, 2)
+ assert merged_hdr.get_xyzt_units() == ('mm', 'sec')
+ merged_data = np.asanyarray(merged.nii_img.dataobj)
for idx in range(3):
- ok_(np.all(merged_data[:, :, :, idx] ==
+ assert(np.all(merged_data[:, :, :, idx] ==
np.arange(idx * (4 * 4 * 4),
- (idx + 1) * (4 * 4 * 4)).reshape(4, 4, 4))
+ (idx + 1) * (4 * 4 * 4),
+ dtype=np.int32).reshape(4, 4, 4))
)
def test_from_3d_vector_to_4d():
vector_nws = []
for idx in range(3):
arr = np.arange(idx * (4 * 4 * 4),
- (idx + 1) * (4 * 4 * 4)
+ (idx + 1) * (4 * 4 * 4),
+ dtype=np.int32
).reshape(4, 4, 4)
nii = nb.Nifti1Image(arr, np.diag((1.1, 1.1, 1.1, 1.0)))
hdr = nii.header
@@ -1253,30 +1144,23 @@ def test_from_3d_vector_to_4d():
vector_nws.append(nw)
merged = dcmmeta.NiftiWrapper.from_sequence(vector_nws, 4)
- eq_(merged.nii_img.shape, (4, 4, 4, 1, 3))
- ok_(np.allclose(merged.nii_img.affine,
+ assert merged.nii_img.shape == (4, 4, 4, 1, 3)
+ assert(np.allclose(merged.nii_img.affine,
np.diag((1.1, 1.1, 1.1, 1.0)))
)
- eq_(merged.meta_ext.get_values_and_class('PatientID'),
- ('Test', ('global', 'const'))
- )
- eq_(merged.meta_ext.get_values_and_class('EchoTime'),
- ([0, 1, 2], ('vector', 'samples'))
- )
- eq_(merged.meta_ext.get_values_and_class('SliceLocation'),
- (list(range(4)), ('vector', 'slices'))
- )
- eq_(merged.meta_ext.get_values_and_class('AcquisitionTime'),
- (list(range(4 * 3)), ('global', 'slices'))
- )
+ assert merged.meta_ext.get_values_and_class('PatientID') == ('Test', ('global', 'const'))
+ assert merged.meta_ext.get_values_and_class('EchoTime') == ([0, 1, 2], ('vector', 'samples'))
+ assert merged.meta_ext.get_values_and_class('SliceLocation') == (list(range(4)), ('vector', 'slices'))
+ assert merged.meta_ext.get_values_and_class('AcquisitionTime') == (list(range(4 * 3)), ('global', 'slices'))
merged_hdr = merged.nii_img.header
- eq_(merged_hdr.get_dim_info(), (0, 1, 2))
- eq_(merged_hdr.get_xyzt_units(), ('mm', 'sec'))
- merged_data = merged.nii_img.get_data()
+ assert merged_hdr.get_dim_info() == (0, 1, 2)
+ assert merged_hdr.get_xyzt_units(), ('mm', 'sec')
+ merged_data = np.asanyarray(merged.nii_img.dataobj)
for idx in range(3):
- ok_(np.all(merged_data[:, :, :, 0, idx] ==
+ assert(np.all(merged_data[:, :, :, 0, idx] ==
np.arange(idx * (4 * 4 * 4),
- (idx + 1) * (4 * 4 * 4)).reshape(4, 4, 4))
+ (idx + 1) * (4 * 4 * 4),
+ dtype=np.int32).reshape(4, 4, 4))
)
def test_merge_inconsistent_hdr():
@@ -1285,7 +1169,8 @@ def test_merge_inconsistent_hdr():
time_nws = []
for idx in range(3):
arr = np.arange(idx * (4 * 4 * 4),
- (idx + 1) * (4 * 4 * 4)
+ (idx + 1) * (4 * 4 * 4),
+ dtype=np.int32
).reshape(4, 4, 4)
nii = nb.Nifti1Image(arr, np.diag((1.1, 1.1, 1.1, 1.0)))
hdr = nii.header
@@ -1300,15 +1185,16 @@ def test_merge_inconsistent_hdr():
merged = dcmmeta.NiftiWrapper.from_sequence(time_nws)
merged_hdr = merged.nii_img.header
- eq_(merged_hdr.get_dim_info(), (None, None, 2))
- eq_(merged_hdr.get_xyzt_units(), ('mm', 'unknown'))
+ assert merged_hdr.get_dim_info() == (None, None, 2)
+ assert merged_hdr.get_xyzt_units(), ('mm', 'unknown')
def test_merge_with_slc_and_without():
#Test merging two data sets where one has per slice meta and other does not
input_nws = []
for idx in range(3):
arr = np.arange(idx * (4 * 4 * 4),
- (idx + 1) * (4 * 4 * 4)
+ (idx + 1) * (4 * 4 * 4),
+ dtype=np.int32
).reshape(4, 4, 4)
nii = nb.Nifti1Image(arr, np.diag((1.1, 1.1, 1.1, 1.0)))
hdr = nii.header
@@ -1325,18 +1211,12 @@ def test_merge_with_slc_and_without():
input_nws.append(nw)
merged = dcmmeta.NiftiWrapper.from_sequence(input_nws)
- eq_(merged.nii_img.shape, (4, 4, 4, 3))
- ok_(np.allclose(merged.nii_img.affine,
+ assert merged.nii_img.shape == (4, 4, 4, 3)
+ assert(np.allclose(merged.nii_img.affine,
np.diag((1.1, 1.1, 1.1, 1.0)))
)
- eq_(merged.meta_ext.get_values_and_class('PatientID'),
- ('Test', ('global', 'const'))
- )
- eq_(merged.meta_ext.get_values_and_class('EchoTime'),
- ([0, 1, 2], ('time', 'samples'))
- )
- eq_(merged.meta_ext.get_values_and_class('SliceLocation'),
- (list(range(4)) + ([None] * 8), ('global', 'slices'))
- )
+ assert merged.meta_ext.get_values_and_class('PatientID') == ('Test', ('global', 'const'))
+ assert merged.meta_ext.get_values_and_class('EchoTime') == ([0, 1, 2], ('time', 'samples'))
+ assert merged.meta_ext.get_values_and_class('SliceLocation') == (list(range(4)) + ([None] * 8), ('global', 'slices'))
merged_hdr = merged.nii_img.header
- eq_(merged_hdr.get_xyzt_units(), ('mm', 'sec'))
\ No newline at end of file
+ assert merged_hdr.get_xyzt_units() == ('mm', 'sec')
=====================================
test/test_dcmstack.py
=====================================
@@ -11,7 +11,7 @@ from hashlib import sha256
from os import path
import numpy as np
-from nose.tools import ok_, eq_, assert_raises
+import pytest
from . import test_dir, src_dir
@@ -29,7 +29,10 @@ from nibabel.orientations import aff2axcodes
import dcmstack
-_def_file_meta = pydicom.dataset.Dataset()
+if hasattr(pydicom, "FileMetaDataset"):
+ _def_file_meta = pydicom.dataset.FileMetaDataset()
+else:
+ _def_file_meta = pydicom.dataset.Dataset()
_def_file_meta.TransferSyntaxUID = ExplicitVRLittleEndian
def_dicom_attrs = {'file_meta' : _def_file_meta,
@@ -64,59 +67,39 @@ def make_dicom(attrs=None, pix_val=1):
arr_dtype = np.int16
arr = np.empty((ds.Rows, ds.Columns), dtype=arr_dtype)
arr[:, :] = pix_val
- ds.PixelData = arr.tostring()
+ ds.PixelData = arr.tobytes()
return ds
def test_key_regex_filter():
filt = dcmstack.make_key_regex_filter(['test', 'another'],
['2', 'another test'])
- ok_(filt('test', 1))
- ok_(filt('test another', 1))
- ok_(filt('another tes', 1))
- ok_(not filt('test2', 1))
- ok_(not filt('2 another', 1))
- ok_(not filt('another test', 1))
+ assert(filt('test', 1))
+ assert(filt('test another', 1))
+ assert(filt('another tes', 1))
+ assert(not filt('test2', 1))
+ assert(not filt('2 another', 1))
+ assert(not filt('another test', 1))
class TestReorderVoxels(object):
- def setUp(self):
+ def setup_method(self, method):
self.vox_array = np.arange(16).reshape((2, 2, 2, 2))
self.affine = np.eye(4)
def test_invalid_vox_order(self):
- assert_raises(ValueError,
- dcmstack.reorder_voxels,
- self.vox_array,
- self.affine,
- 'lra',
- )
- assert_raises(ValueError,
- dcmstack.reorder_voxels,
- self.vox_array,
- self.affine,
- 'rpil',
- )
- assert_raises(ValueError,
- dcmstack.reorder_voxels,
- self.vox_array,
- self.affine,
- 'lrz',
- )
+ with pytest.raises(ValueError):
+ dcmstack.reorder_voxels(self.vox_array, self.affine, 'lra')
+ with pytest.raises(ValueError):
+ dcmstack.reorder_voxels(self.vox_array, self.affine, 'rpil')
+ with pytest.raises(ValueError):
+ dcmstack.reorder_voxels(self.vox_array, self.affine, 'lrz')
def test_invalid_vox_array(self):
- assert_raises(ValueError,
- dcmstack.reorder_voxels,
- np.eye(2),
- self.affine,
- 'rpi',
- )
+ with pytest.raises(ValueError):
+ dcmstack.reorder_voxels(np.eye(2), self.affine, 'rpi')
def test_invalid_affine(self):
- assert_raises(ValueError,
- dcmstack.reorder_voxels,
- self.vox_array,
- np.eye(3),
- 'rpi',
- )
+ with pytest.raises(ValueError):
+ dcmstack.reorder_voxels(self.vox_array, np.eye(3), 'rpi')
def test_no_op(self):
vox_order = ''.join(aff2axcodes(self.affine))
@@ -126,11 +109,11 @@ class TestReorderVoxels(object):
ornt_trans) = dcmstack.reorder_voxels(self.vox_array,
self.affine,
vox_order)
- ok_((vox_array == self.vox_array).all())
- ok_((affine == self.affine).all())
- ok_((aff_trans == np.eye(4)).all())
- ok_(np.allclose(ornt_trans, [[0, 1], [1, 1], [2, 1]]))
- eq_(np.may_share_memory(affine, self.affine), False)
+ assert((vox_array == self.vox_array).all())
+ assert((affine == self.affine).all())
+ assert((aff_trans == np.eye(4)).all())
+ assert(np.allclose(ornt_trans, [[0, 1], [1, 1], [2, 1]]))
+ assert np.may_share_memory(affine, self.affine) == False
def test_reorder(self):
(vox_array,
@@ -139,7 +122,7 @@ class TestReorderVoxels(object):
ornt_trans) = dcmstack.reorder_voxels(self.vox_array,
self.affine,
'PRS')
- ok_(np.all(vox_array == np.array([[[[4, 5],
+ assert(np.all(vox_array == np.array([[[[4, 5],
[6, 7]],
[[12, 13],
[14,15]]
@@ -153,7 +136,7 @@ class TestReorderVoxels(object):
)
)
)
- ok_(np.allclose(affine,
+ assert(np.allclose(affine,
np.array([[0,1,0,0],
[-1,0,0,1],
[0,0,1,0],
@@ -170,7 +153,7 @@ class TestReorderVoxels(object):
ornt_trans) = dcmstack.reorder_voxels(self.vox_array,
self.affine,
'PLS')
- ok_(np.allclose(affine,
+ assert(np.allclose(affine,
np.array([[0,-1,0,1],
[-1,0,0,3],
[0,0,1,0],
@@ -179,50 +162,46 @@ class TestReorderVoxels(object):
)
def test_dcm_time_to_sec():
- eq_(dcmstack.dcm_time_to_sec('100235.123456'), 36155.123456)
- eq_(dcmstack.dcm_time_to_sec('100235'), 36155)
- eq_(dcmstack.dcm_time_to_sec('1002'), 36120)
- eq_(dcmstack.dcm_time_to_sec('10'), 36000)
+ assert dcmstack.dcm_time_to_sec('100235.123456') == 36155.123456
+ assert dcmstack.dcm_time_to_sec('100235') == 36155
+ assert dcmstack.dcm_time_to_sec('1002') == 36120
+ assert dcmstack.dcm_time_to_sec('10') == 36000
#Allow older NEMA style values
- eq_(dcmstack.dcm_time_to_sec('10:02:35.123456'), 36155.123456)
- eq_(dcmstack.dcm_time_to_sec('10:02:35'), 36155)
- eq_(dcmstack.dcm_time_to_sec('10:02'), 36120)
- eq_(dcmstack.dcm_time_to_sec('10'), 36000)
+ assert dcmstack.dcm_time_to_sec('10:02:35.123456') == 36155.123456
+ assert dcmstack.dcm_time_to_sec('10:02:35') == 36155
+ assert dcmstack.dcm_time_to_sec('10:02') == 36120
+ assert dcmstack.dcm_time_to_sec('10') == 36000
class TestDicomOrdering(object):
- def setUp(self):
+ def setup_method(self, method):
self.ds = {'EchoTime' : 2}
def test_missing_key(self):
ordering = dcmstack.DicomOrdering('blah')
- eq_(ordering.get_ordinate(self.ds), None)
+ assert ordering.get_ordinate(self.ds) == None
def test_non_abs(self):
ordering = dcmstack.DicomOrdering('EchoTime')
- eq_(ordering.get_ordinate(self.ds), self.ds['EchoTime'])
+ assert ordering.get_ordinate(self.ds) == self.ds['EchoTime']
def test_abs(self):
abs_order = [1,2,3]
ordering = dcmstack.DicomOrdering('EchoTime', abs_ordering=abs_order)
- eq_(ordering.get_ordinate(self.ds),
- abs_order.index(self.ds['EchoTime']))
+ assert ordering.get_ordinate(self.ds) == abs_order.index(self.ds['EchoTime'])
def test_abs_as_str(self):
abs_order = ['1','2','3']
ordering = dcmstack.DicomOrdering('EchoTime',
abs_ordering=abs_order,
abs_as_str=True)
- eq_(ordering.get_ordinate(self.ds),
- abs_order.index(str(self.ds['EchoTime'])))
+ assert ordering.get_ordinate(self.ds) == abs_order.index(str(self.ds['EchoTime']))
def test_abs_missing(self):
abs_order = [1,3]
ordering = dcmstack.DicomOrdering('EchoTime', abs_ordering=abs_order)
- assert_raises(ValueError,
- ordering.get_ordinate,
- self.ds
- )
+ with pytest.raises(ValueError):
+ ordering.get_ordinate(self.ds)
def test_image_collision():
dcm_path = path.join(test_dir,
@@ -233,12 +212,11 @@ def test_image_collision():
dcm = pydicom.read_file(dcm_path)
stack = dcmstack.DicomStack('EchoTime')
stack.add_dcm(dcm)
- assert_raises(dcmstack.ImageCollisionError,
- stack.add_dcm,
- dcm)
+ with pytest.raises(dcmstack.ImageCollisionError):
+ stack.add_dcm(dcm)
class TestIncongruentImage(object):
- def setUp(self):
+ def setup_method(self, method):
dcm_path = path.join(test_dir,
'data',
'dcmstack',
@@ -251,9 +229,8 @@ class TestIncongruentImage(object):
self.dcm = pydicom.read_file(dcm_path)
def _chk_raises(self):
- assert_raises(dcmstack.IncongruentImageError,
- self.stack.add_dcm,
- self.dcm)
+ with pytest.raises(dcmstack.IncongruentImageError):
+ self.stack.add_dcm(self.dcm)
def test_rows(self):
self.dcm.Rows += 1
@@ -289,7 +266,7 @@ class TestIncongruentImage(object):
class TestInvalidStack(object):
- def setUp(self):
+ def setup_method(self, method):
data_dir = path.join(test_dir,
'data',
'dcmstack',
@@ -304,29 +281,19 @@ class TestInvalidStack(object):
]
def _chk(self):
- assert_raises(dcmstack.InvalidStackError,
- self.stack.get_shape)
- assert_raises(dcmstack.InvalidStackError,
- self.stack.get_affine)
- assert_raises(dcmstack.InvalidStackError,
- self.stack.get_data)
- assert_raises(dcmstack.InvalidStackError,
- self.stack.to_nifti)
+ with pytest.raises(dcmstack.InvalidStackError):
+ self.stack.get_shape()
+ with pytest.raises(dcmstack.InvalidStackError):
+ self.stack.get_affine()
+ with pytest.raises(dcmstack.InvalidStackError):
+ self.stack.get_data()
+ with pytest.raises(dcmstack.InvalidStackError):
+ self.stack.to_nifti()
def test_empty(self):
self.stack = dcmstack.DicomStack()
self._chk()
- def test_only_dummy(self):
- self.stack = dcmstack.DicomStack(allow_dummies=True)
- del self.inputs[0].Rows
- del self.inputs[0].Columns
- del self.inputs[1].Rows
- del self.inputs[1].Columns
- self.stack.add_dcm(self.inputs[0])
- self.stack.add_dcm(self.inputs[1])
- self._chk()
-
def test_missing_slice(self):
self.stack = dcmstack.DicomStack()
self.stack.add_dcm(self.inputs[0])
@@ -350,7 +317,7 @@ class TestInvalidStack(object):
self._chk()
class TestGetShape(object):
- def setUp(self):
+ def setup_method(self, method):
data_dir = path.join(test_dir,
'data',
'dcmstack',
@@ -367,14 +334,14 @@ class TestGetShape(object):
stack = dcmstack.DicomStack()
stack.add_dcm(self.inputs[0])
shape = stack.shape
- eq_(shape, (192, 192, 1))
+ assert shape == (192, 192, 1)
def test_three_dim(self):
stack = dcmstack.DicomStack()
stack.add_dcm(self.inputs[0])
stack.add_dcm(self.inputs[1])
shape = stack.shape
- eq_(shape, (192, 192, 2))
+ assert shape == (192, 192, 2)
def test_four_dim(self):
stack = dcmstack.DicomStack(time_order='EchoTime')
@@ -383,7 +350,7 @@ class TestGetShape(object):
stack.add_dcm(self.inputs[2])
stack.add_dcm(self.inputs[3])
shape = stack.shape
- eq_(shape, (192, 192, 2, 2))
+ assert shape == (192, 192, 2, 2)
def test_five_dim(self):
stack = dcmstack.DicomStack(vector_order='EchoTime')
@@ -392,19 +359,10 @@ class TestGetShape(object):
stack.add_dcm(self.inputs[2])
stack.add_dcm(self.inputs[3])
shape = stack.shape
- eq_(shape, (192, 192, 2, 1, 2))
-
- def test_allow_dummy(self):
- del self.inputs[0].Rows
- del self.inputs[0].Columns
- stack = dcmstack.DicomStack(allow_dummies=True)
- stack.add_dcm(self.inputs[0])
- stack.add_dcm(self.inputs[1])
- shape = stack.shape
- eq_(shape, (192, 192, 2))
+ assert shape == (192, 192, 2, 1, 2)
class TestGuessDim(object):
- def setUp(self):
+ def setup_method(self, method):
data_dir = path.join(test_dir,
'data',
'dcmstack',
@@ -436,7 +394,7 @@ class TestGuessDim(object):
for idx, in_dcm in enumerate(self.inputs):
setattr(in_dcm, key, self._get_vr_ord(key, idx))
stack.add_dcm(in_dcm)
- eq_(stack.shape, (192, 192, 2, 2))
+ assert stack.shape == (192, 192, 2, 2)
for in_dcm in self.inputs:
delattr(in_dcm, key)
@@ -451,10 +409,10 @@ class TestGuessDim(object):
dcmstack.DicomStack.sort_guesses[-1],
self._get_vr_ord(key, idx) )
stack.add_dcm(in_dcm)
- eq_(stack.shape, (192, 192, 2, 2))
+ assert stack.shape == (192, 192, 2, 2)
class TestGetData(object):
- def setUp(self):
+ def setup_method(self, method):
data_dir = path.join(test_dir,
'data',
'dcmstack',
@@ -471,18 +429,18 @@ class TestGetData(object):
stack = dcmstack.DicomStack()
stack.add_dcm(self.inputs[0])
data = stack.get_data()
- eq_(data.shape, stack.shape)
- eq_(sha256(data).hexdigest(),
- '15cfa107ca73810a1c97f1c1872a7a4a05808ba6147e039cef3f63fa08735f5d')
+ assert data.shape == stack.shape
+ assert sha256(data).hexdigest() == \
+ '15cfa107ca73810a1c97f1c1872a7a4a05808ba6147e039cef3f63fa08735f5d'
def test_three_dim(self):
stack = dcmstack.DicomStack()
stack.add_dcm(self.inputs[0])
stack.add_dcm(self.inputs[1])
data = stack.get_data()
- eq_(data.shape, stack.shape)
- eq_(sha256(data).hexdigest(),
- 'ab5225fdbedceeea3442b2c9387e1abcbf398c71f525e0017251849c3cfbf49c')
+ assert data.shape == stack.shape
+ assert sha256(data).hexdigest() == \
+ 'ab5225fdbedceeea3442b2c9387e1abcbf398c71f525e0017251849c3cfbf49c'
def test_four_dim(self):
stack = dcmstack.DicomStack(time_order='EchoTime')
@@ -491,9 +449,9 @@ class TestGetData(object):
stack.add_dcm(self.inputs[2])
stack.add_dcm(self.inputs[3])
data = stack.get_data()
- eq_(data.shape, stack.shape)
- eq_(sha256(data).hexdigest(),
- 'bb3639a6ece13dc9a11d65f1b09ab3ccaed63b22dcf0f96fb5d3dd8805cc7b8a')
+ assert data.shape == stack.shape
+ assert sha256(data).hexdigest() == \
+ 'bb3639a6ece13dc9a11d65f1b09ab3ccaed63b22dcf0f96fb5d3dd8805cc7b8a'
def test_five_dim(self):
stack = dcmstack.DicomStack(vector_order='EchoTime')
@@ -502,24 +460,12 @@ class TestGetData(object):
stack.add_dcm(self.inputs[2])
stack.add_dcm(self.inputs[3])
data = stack.get_data()
- eq_(data.shape, stack.shape)
- eq_(sha256(data).hexdigest(),
- 'bb3639a6ece13dc9a11d65f1b09ab3ccaed63b22dcf0f96fb5d3dd8805cc7b8a')
-
- def test_allow_dummy(self):
- del self.inputs[0].Rows
- del self.inputs[0].Columns
- stack = dcmstack.DicomStack(allow_dummies=True)
- stack.add_dcm(self.inputs[0])
- stack.add_dcm(self.inputs[1])
- data = stack.get_data()
- eq_(data.shape, stack.shape)
- ok_(np.all(data[:, :, -1] == np.iinfo(np.int16).max))
- eq_(sha256(data).hexdigest(),
- '7d85fbcb60a5021a45df3975613dcb7ac731830e0a268590cc798dc39897c04b')
+ assert data.shape == stack.shape
+ assert sha256(data).hexdigest() == \
+ 'bb3639a6ece13dc9a11d65f1b09ab3ccaed63b22dcf0f96fb5d3dd8805cc7b8a'
class TestGetAffine(object):
- def setUp(self):
+ def setup_method(self, method):
self.data_dir = path.join(test_dir,
'data',
'dcmstack',
@@ -535,7 +481,7 @@ class TestGetAffine(object):
stack.add_dcm(self.inputs[0])
affine = stack.affine
ref = np.load(path.join(self.data_dir, 'single_slice_aff.npy'))
- ok_(np.allclose(affine, ref))
+ assert(np.allclose(affine, ref))
def test_three_dim(self):
stack = dcmstack.DicomStack()
@@ -543,7 +489,7 @@ class TestGetAffine(object):
stack.add_dcm(self.inputs[1])
affine = stack.affine
ref = np.load(path.join(self.data_dir, 'single_vol_aff.npy'))
- ok_(np.allclose(affine, ref))
+ assert(np.allclose(affine, ref))
class TestToNifti(object):
@@ -586,7 +532,7 @@ class TestToNifti(object):
'srow_z',
]
- def setUp(self):
+ def setup_method(self, method):
self.data_dir = path.join(test_dir,
'data',
'dcmstack',
@@ -648,7 +594,7 @@ class TestToNifti(object):
for key in self.close_keys:
print("Testing key %s" % key)
- ok_(np.allclose(hdr[key], ref_hdr[key]))
+ assert(np.allclose(hdr[key], ref_hdr[key]))
def test_single_slice(self):
for tst in ('single_slice', 'single_slice_meta'):
@@ -675,19 +621,9 @@ class TestToNifti(object):
nii = self._build_nii(tst)
self._chk(nii, tst)
- def test_allow_dummies(self):
- del self.inputs[0].Rows
- del self.inputs[0].Columns
- stack = dcmstack.DicomStack(allow_dummies=True)
- stack.add_dcm(self.inputs[0])
- stack.add_dcm(self.inputs[1])
- nii = stack.to_nifti()
- data = nii.get_data()
- ok_(np.all(data[:, :, 0] == np.iinfo(np.int16).max))
-
class TestParseAndGroup(object):
- def setUp(self):
+ def setup_method(self, method):
self.data_dir = path.join(test_dir,
'data',
'dcmstack',
@@ -702,18 +638,18 @@ class TestParseAndGroup(object):
def test_default(self):
res = dcmstack.parse_and_group(self.in_paths)
- eq_(len(res), 1)
+ assert len(res) == 1
ds = pydicom.read_file(self.in_paths[0])
group_key = list(res.keys())[0]
for attr_idx, attr in enumerate(dcmstack.default_group_keys):
if attr in dcmstack.default_close_keys:
- ok_(np.allclose(group_key[attr_idx], getattr(ds, attr)))
+ assert(np.allclose(group_key[attr_idx], getattr(ds, attr)))
else:
- eq_(group_key[attr_idx], getattr(ds, attr))
+ assert group_key[attr_idx] == getattr(ds, attr)
class TestParseAndStack(object):
- def setUp(self):
+ def setup_method(self, method):
self.data_dir = path.join(test_dir,
'data',
'dcmstack',
@@ -728,18 +664,18 @@ class TestParseAndStack(object):
def test_default(self):
res = dcmstack.parse_and_stack(self.in_paths)
- eq_(len(res), 1)
+ assert len(res) == 1
ds = pydicom.read_file(self.in_paths[0])
group_key = list(res.keys())[0]
for attr_idx, attr in enumerate(dcmstack.default_group_keys):
if attr in dcmstack.default_close_keys:
- ok_(np.allclose(group_key[attr_idx], getattr(ds, attr)))
+ assert(np.allclose(group_key[attr_idx], getattr(ds, attr)))
else:
- eq_(group_key[attr_idx], getattr(ds, attr))
+ assert group_key[attr_idx] == getattr(ds, attr)
stack = list(res.values())[0]
- ok_(isinstance(stack, dcmstack.DicomStack))
+ assert(isinstance(stack, dcmstack.DicomStack))
stack_data = stack.get_data()
- eq_(stack_data.ndim, 4)
+ assert stack_data.ndim == 4
def test_fsl_hack():
@@ -747,8 +683,8 @@ def test_fsl_hack():
stack = dcmstack.DicomStack()
stack.add_dcm(ds)
data = stack.get_data()
- eq_(np.max(data), (2**14 - 1))
- eq_(data.dtype, np.int16)
+ assert np.max(data) == (2**14 - 1)
+ assert data.dtype == np.int16
def test_pix_overflow():
@@ -756,5 +692,5 @@ def test_pix_overflow():
stack = dcmstack.DicomStack()
stack.add_dcm(ds)
data = stack.get_data()
- eq_(np.max(data), (2**16 - 1))
- eq_(data.dtype, np.uint16)
+ assert np.max(data) == (2**16 - 1)
+ assert data.dtype == np.uint16
=====================================
test/test_extract.py
=====================================
@@ -4,7 +4,7 @@ Tests for dcmstack.extract
import sys, warnings
from os import path
-from nose.tools import ok_, eq_, assert_raises
+import pytest
from nibabel.nicom import csareader
try:
import pydicom
@@ -18,65 +18,61 @@ with warnings.catch_warnings():
from dcmstack import extract
class TestCsa(object):
- def setUp(self):
+ def setup_method(self, method):
data_fn = path.join(test_dir, 'data', 'extract', 'csa_test.dcm')
self.data = pydicom.read_file(data_fn)
- def tearDown(self):
+ def teardown_method(self, method):
del self.data
def test_simplify(self):
- eq_(extract.simplify_csa_dict(None), None)
+ assert extract.simplify_csa_dict(None) == None
csa_dict = csareader.read(self.data[pydicom.tag.Tag(0x29, 0x1010)].value)
simp_dict = extract.simplify_csa_dict(csa_dict)
for tag in csa_dict['tags']:
items = csa_dict['tags'][tag]['items']
if len(items) == 0:
- ok_(not tag in simp_dict)
+ assert(not tag in simp_dict)
elif len(items) == 1:
- eq_(simp_dict[tag], items[0])
+ assert simp_dict[tag] == items[0]
else:
- eq_(simp_dict[tag], items)
+ assert simp_dict[tag] == items
def test_csa_image_trans(self):
csa_dict = extract.csa_series_trans_func(self.data[(0x29, 0x1010)])
- eq_(csa_dict["EchoLinePosition"], 64)
+ assert csa_dict["EchoLinePosition"] == 64
def test_parse_phx_line(self):
- ok_(extract._parse_phoenix_line("") is None)
- ok_(extract._parse_phoenix_line("#test = 2") is None)
-
- eq_(extract._parse_phoenix_line('test = "" 2 ""'), ('test', ' 2 '))
- eq_(extract._parse_phoenix_line('test = "" #2 ""'), ('test', ' #2 '))
- eq_(extract._parse_phoenix_line('test = "" 2 ""#='),
- ('test', ' 2 '))
- eq_(extract._parse_phoenix_line("test = 2#"), ('test', 2))
- eq_(extract._parse_phoenix_line("test = 0x2"), ('test', 2))
- eq_(extract._parse_phoenix_line("test = 2."), ('test', 2.0))
-
- assert_raises(extract.PhoenixParseError,
- extract._parse_phoenix_line,
- 'test = blah')
- assert_raises(extract.PhoenixParseError,
- extract._parse_phoenix_line,
- '==')
- assert_raises(extract.PhoenixParseError,
- extract._parse_phoenix_line,
- 'test')
- assert_raises(extract.PhoenixParseError,
- extract._parse_phoenix_line,
- 'test = "" 2 ""3')
+ assert(extract._parse_phoenix_line("") is None)
+ assert(extract._parse_phoenix_line("#test = 2") is None)
+
+ assert extract._parse_phoenix_line('test = "" 2 ""') == ('test', ' 2 ')
+ assert extract._parse_phoenix_line('test = "" #2 ""'), ('test', ' #2 ')
+ assert extract._parse_phoenix_line('test = "" 2 ""#=') == ('test', ' 2 ')
+ assert extract._parse_phoenix_line("test = 2#") == ('test', 2)
+ assert extract._parse_phoenix_line("test = 0x2") == ('test', 2)
+ assert extract._parse_phoenix_line("test = 2.") == ('test', 2.0)
+
+
+ with pytest.raises(extract.PhoenixParseError):
+ extract._parse_phoenix_line('test = blah')
+ with pytest.raises(extract.PhoenixParseError):
+ extract._parse_phoenix_line('==')
+ with pytest.raises(extract.PhoenixParseError):
+ extract._parse_phoenix_line('test')
+ with pytest.raises(extract.PhoenixParseError):
+ extract._parse_phoenix_line('test = "" 2 ""3')
def test_csa_series_trans(self):
csa_dict = extract.csa_series_trans_func(self.data[(0x29, 0x1020)])
- eq_(csa_dict['MrPhoenixProtocol.sEFISPEC.bEFIDataValid'], 1)
+ assert csa_dict['MrPhoenixProtocol.sEFISPEC.bEFIDataValid'] == 1
class TestMetaExtractor(object):
- def setUp(self):
+ def setup_method(self, method):
data_fn = path.join(test_dir, 'data', 'extract', 'csa_test.dcm')
self.data = pydicom.read_file(data_fn)
- def tearDown(self):
+ def teardown_method(self,method):
del self.data
def test_get_elem_key(self):
@@ -84,9 +80,9 @@ class TestMetaExtractor(object):
extractor = extract.MetaExtractor(ignore_rules=ignore_rules)
for elem in self.data:
key = extractor._get_elem_key(elem)
- ok_(key.strip() != '')
- ok_(key[0].isalpha())
- ok_(key[-1].isalnum())
+ assert(key.strip() != '')
+ assert(key[0].isalpha())
+ assert(key[-1].isalnum())
def test_get_elem_value(self):
ignore_rules = (extract.ignore_pixel_data,)
@@ -94,17 +90,18 @@ class TestMetaExtractor(object):
for elem in self.data:
value = extractor._get_elem_value(elem)
if elem.VM > 1:
- ok_(isinstance(value, list))
+ assert(isinstance(value, list))
if elem.VR in list(extract.unpack_vr_map) + ['DS', 'IS']:
if elem.VM == 1:
- ok_(not isinstance(value, str))
+ assert(not isinstance(value, str))
else:
- ok_(not any(isinstance(val, str) for val in value))
+ assert(not any(isinstance(val, str) for val in value))
def test_dup_trans(self):
translators = [extract.csa_image_trans, extract.csa_image_trans]
extractor = extract.MetaExtractor(translators=translators)
- assert_raises(ValueError, extractor, self.data)
+ with pytest.raises(ValueError):
+ extractor(self.data)
def test_reloc_private(self):
extractor = extract.MetaExtractor()
@@ -112,11 +109,11 @@ class TestMetaExtractor(object):
self.data[(0x29, 0x1010)].tag = pydicom.tag.Tag((0x29, 0x2010))
self.data[(0x29, 0x1020)].tag = pydicom.tag.Tag((0x29, 0x2020))
meta_dict = extractor(self.data)
- eq_(meta_dict["CsaImage.EchoLinePosition"], 64)
- ok_(meta_dict['CsaSeries.MrPhoenixProtocol.sEFISPEC.bEFIDataValid'], 1)
+ assert meta_dict["CsaImage.EchoLinePosition"] == 64
+ assert meta_dict['CsaSeries.MrPhoenixProtocol.sEFISPEC.bEFIDataValid'] == 1
def test_non_reloc_private(self):
extractor = extract.MetaExtractor()
meta_dict = extractor(self.data)
- eq_(meta_dict["CsaImage.EchoLinePosition"], 64)
- ok_(meta_dict['CsaSeries.MrPhoenixProtocol.sEFISPEC.bEFIDataValid'], 1)
\ No newline at end of file
+ assert meta_dict["CsaImage.EchoLinePosition"] == 64
+ assert meta_dict['CsaSeries.MrPhoenixProtocol.sEFISPEC.bEFIDataValid'] == 1
View it on GitLab: https://salsa.debian.org/med-team/dcmstack/-/commit/4f7a3831f277facc82b75fdbb9f30abbe0d1fc05
--
View it on GitLab: https://salsa.debian.org/med-team/dcmstack/-/commit/4f7a3831f277facc82b75fdbb9f30abbe0d1fc05
You're receiving this email because of your account on salsa.debian.org.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/debian-med-commit/attachments/20220930/396c788e/attachment-0001.htm>
More information about the debian-med-commit
mailing list