diff --git a/CHANGES b/CHANGES index 98aab9f0d0..f7761f7b91 100644 --- a/CHANGES +++ b/CHANGES @@ -1,6 +1,7 @@ Upcoming release (0.14.0) ================ +* FIX: Testing maintainance and improvements (https://github.com/nipy/nipype/pull/2252) * ENH: Add elapsed_time and final metric_value to ants.Registration (https://github.com/nipy/nipype/pull/1985) * ENH: Improve terminal_output feature (https://github.com/nipy/nipype/pull/2209) * ENH: Simple interface to FSL std2imgcoords (https://github.com/nipy/nipype/pull/2209, prev #1398) diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000000..f2d52f5f85 --- /dev/null +++ b/conftest.py @@ -0,0 +1,12 @@ +import pytest +import numpy, os + +@pytest.fixture(autouse=True) +def add_np(doctest_namespace): + doctest_namespace['np'] = numpy + doctest_namespace['os'] = os + + + filepath = os.path.dirname(os.path.realpath(__file__)) + datadir = os.path.realpath(os.path.join(filepath, 'nipype/testing/data')) + doctest_namespace["datadir"] = datadir diff --git a/nipype/algorithms/confounds.py b/nipype/algorithms/confounds.py index 1d31f2ab6c..39cafebe8c 100644 --- a/nipype/algorithms/confounds.py +++ b/nipype/algorithms/confounds.py @@ -30,7 +30,7 @@ from ..utils import NUMPY_MMAP from ..utils.misc import normalize_mc_params -IFLOG = logging.getLogger('interface') +IFLOGGER = logging.getLogger('interface') class ComputeDVARSInputSpec(BaseInterfaceInputSpec): @@ -286,7 +286,7 @@ def _run_interface(self, runtime): tr = self.inputs.series_tr if self.inputs.normalize and tr is None: - IFLOG.warn('FD plot cannot be normalized if TR is not set') + IFLOGGER.warn('FD plot cannot be normalized if TR is not set') self._results['out_figure'] = op.abspath(self.inputs.out_figure) fig = plot_confound(fd_res, self.inputs.figsize, 'FD', units='mm', @@ -601,8 +601,8 @@ def _process_masks(self, mask_images, timeseries=None): # save mask mask_file = os.path.abspath('mask_{:03d}.nii.gz'.format(i)) out_image.to_filename(mask_file) - IFLOG.debug('tCompcor computed and saved mask of shape {} to ' - 'mask_file {}'.format(mask.shape, mask_file)) + IFLOGGER.debug('tCompcor computed and saved mask of shape %s to ' + 'mask_file %s', str(mask.shape), mask_file) self._mask_files.append(mask_file) out_images.append(out_image) return out_images @@ -919,7 +919,8 @@ def regress_poly(degree, data, remove_mean=True, axis=-1): :param int axis: numpy array axes along which regression is performed """ - IFLOG.debug('Performing polynomial regression on data of shape ' + str(data.shape)) + IFLOGGER.debug('Performing polynomial regression on data of shape %s', + str(data.shape)) datashape = data.shape timepoints = datashape[axis] @@ -1147,7 +1148,7 @@ def _full_rank(X, cmax=1e15): c = smax / smin if c < cmax: return X, c - IFLOG.warn('Matrix is singular at working precision, regularizing...') + IFLOGGER.warn('Matrix is singular at working precision, regularizing...') lda = (smax - cmax * smin) / (cmax - 1) s = s + lda X = np.dot(U, np.dot(np.diag(s), V)) diff --git a/nipype/algorithms/misc.py b/nipype/algorithms/misc.py index f1cd8179fa..a16507bf36 100644 --- a/nipype/algorithms/misc.py +++ b/nipype/algorithms/misc.py @@ -362,26 +362,23 @@ def _run_interface(self, runtime): if isinstance(in_dict[key][0], np.ndarray): saved_variables.append(key) else: - iflogger.info('One of the keys in the input file, {k}, is not a Numpy array'.format(k=key)) + iflogger.info('One of the keys in the input file, %s, is ' + 'not a Numpy array', key) if len(saved_variables) > 1: - iflogger.info( - '{N} variables found:'.format(N=len(saved_variables))) + iflogger.info('%i variables found:', len(saved_variables)) iflogger.info(saved_variables) for variable in saved_variables: - iflogger.info( - '...Converting {var} - type {ty} - to\ - CSV'.format(var=variable, ty=type(in_dict[variable])) - ) - matlab2csv( - in_dict[variable], variable, self.inputs.reshape_matrix) + iflogger.info('...Converting %s - type %s - to CSV', + variable, type(in_dict[variable])) + matlab2csv(in_dict[variable], variable, self.inputs.reshape_matrix) elif len(saved_variables) == 1: _, name, _ = split_filename(self.inputs.in_file) variable = saved_variables[0] - iflogger.info('Single variable found {var}, type {ty}:'.format( - var=variable, ty=type(in_dict[variable]))) - iflogger.info('...Converting {var} to CSV from {f}'.format( - var=variable, f=self.inputs.in_file)) + iflogger.info('Single variable found %s, type %s:', variable, + type(in_dict[variable])) + iflogger.info('...Converting %s to CSV from %s', variable, + self.inputs.in_file) matlab2csv(in_dict[variable], name, self.inputs.reshape_matrix) else: iflogger.error('No values in the MATLAB file?!') @@ -396,8 +393,8 @@ def _list_outputs(self): if isinstance(in_dict[key][0], np.ndarray): saved_variables.append(key) else: - iflogger.error('One of the keys in the input file, {k}, is\ - not a Numpy array'.format(k=key)) + iflogger.error('One of the keys in the input file, %s, is ' + 'not a Numpy array', key) if len(saved_variables) > 1: outputs['csv_files'] = replaceext(saved_variables, '.csv') @@ -555,19 +552,16 @@ def _run_interface(self, runtime): iflogger.info('Column headings have been provided:') headings = self.inputs.column_headings else: - iflogger.info( - 'Column headings not provided! Pulled from input filenames:') + iflogger.info('Column headings not provided! Pulled from input filenames:') headings = remove_identical_paths(self.inputs.in_files) if isdefined(self.inputs.extra_field): if isdefined(self.inputs.extra_column_heading): extraheading = self.inputs.extra_column_heading - iflogger.info('Extra column heading provided: {col}'.format( - col=extraheading)) + iflogger.info('Extra column heading provided: %s', extraheading) else: extraheading = 'type' - iflogger.info( - 'Extra column heading was not defined. Using "type"') + iflogger.info('Extra column heading was not defined. Using "type"') headings.append(extraheading) extraheadingBool = True @@ -575,8 +569,8 @@ def _run_interface(self, runtime): iflogger.warn('Only one file input!') if isdefined(self.inputs.row_headings): - iflogger.info('Row headings have been provided. Adding "labels"\ - column header.') + iflogger.info('Row headings have been provided. Adding "labels"' + 'column header.') prefix = '"{p}","'.format(p=self.inputs.row_heading_title) csv_headings = prefix + '","'.join(itertools.chain( headings)) + '"\n' @@ -1310,7 +1304,7 @@ def merge_rois(in_files, in_idxs, in_ref, # to avoid memory errors if op.splitext(in_ref)[1] == '.gz': try: - iflogger.info('uncompress %i' % in_ref) + iflogger.info('uncompress %i', in_ref) sp.check_call(['gunzip', in_ref], stdout=sp.PIPE, shell=True) in_ref = op.splitext(in_ref)[0] except: diff --git a/nipype/algorithms/modelgen.py b/nipype/algorithms/modelgen.py index 87367f7955..2c994bf20d 100644 --- a/nipype/algorithms/modelgen.py +++ b/nipype/algorithms/modelgen.py @@ -374,9 +374,9 @@ def _generate_standard_design(self, infolist, functional_runs=None, for f in filename_to_list(sessinfo[i]['scans']): shape = load(f, mmap=NUMPY_MMAP).shape if len(shape) == 3 or shape[3] == 1: - iflogger.warning(('You are using 3D instead of 4D ' - 'files. Are you sure this was ' - 'intended?')) + iflogger.warning('You are using 3D instead of 4D ' + 'files. Are you sure this was ' + 'intended?') numscans += 1 else: numscans += shape[3] @@ -686,7 +686,7 @@ def _gen_regress(self, i_onsets, i_durations, i_amplitudes, nscans): if dt < 1: raise Exception('Time multiple less than 1 ms') - iflogger.info('Setting dt = %d ms\n' % dt) + iflogger.info('Setting dt = %d ms\n', dt) npts = int(np.ceil(total_time / dt)) times = np.arange(0, total_time, dt) * 1e-3 timeline = np.zeros((npts)) @@ -705,9 +705,9 @@ def _gen_regress(self, i_onsets, i_durations, i_amplitudes, nscans): if isdefined(self.inputs.model_hrf) and self.inputs.model_hrf: response = np.convolve(boxcar, hrf) reg_scale = 1.0 / response.max() - iflogger.info('response sum: %.4f max: %.4f' % (response.sum(), - response.max())) - iflogger.info('reg_scale: %.4f' % reg_scale) + iflogger.info('response sum: %.4f max: %.4f', response.sum(), + response.max()) + iflogger.info('reg_scale: %.4f', reg_scale) for i, t in enumerate(onsets): idx = int(np.round(t / dt)) diff --git a/nipype/algorithms/tests/test_compcor.py b/nipype/algorithms/tests/test_compcor.py index a458e8a0a6..9407e6ef0d 100644 --- a/nipype/algorithms/tests/test_compcor.py +++ b/nipype/algorithms/tests/test_compcor.py @@ -21,8 +21,7 @@ class TestCompCor(): @pytest.fixture(autouse=True) def setup_class(self, tmpdir): # setup - self.temp_dir = str(tmpdir) - os.chdir(self.temp_dir) + tmpdir.chdir() noise = np.fromfunction(self.fake_noise_fun, self.fake_data.shape) self.realigned_file = utils.save_toy_nii(self.fake_data + noise, self.filenames['functionalnii']) diff --git a/nipype/algorithms/tests/test_confounds.py b/nipype/algorithms/tests/test_confounds.py index 7d6eff1283..8c2626457e 100644 --- a/nipype/algorithms/tests/test_confounds.py +++ b/nipype/algorithms/tests/test_confounds.py @@ -20,7 +20,7 @@ def test_fd(tmpdir): - tempdir = str(tmpdir) + tempdir = tmpdir.strpath ground_truth = np.loadtxt(example_data('fsl_motion_outliers_fd.txt')) fdisplacement = FramewiseDisplacement(in_file=example_data('fsl_mcflirt_movpar.txt'), out_file=tempdir + '/fd.txt', @@ -43,7 +43,7 @@ def test_dvars(tmpdir): in_mask=example_data('ds003_sub-01_mc_brainmask.nii.gz'), save_all=True, intensity_normalization=0) - os.chdir(str(tmpdir)) + tmpdir.chdir() res = dvars.run() dv1 = np.loadtxt(res.outputs.out_all, skiprows=1) @@ -66,7 +66,8 @@ def test_dvars(tmpdir): assert (np.abs(dv1[:, 2] - ground_truth[:, 2]).sum() / len(dv1)) < 0.05 -def test_outliers(tmpdir): + +def test_outliers(): np.random.seed(0) in_data = np.random.randn(100) in_data[0] += 10 diff --git a/nipype/algorithms/tests/test_errormap.py b/nipype/algorithms/tests/test_errormap.py index a700725e41..4b40d14907 100644 --- a/nipype/algorithms/tests/test_errormap.py +++ b/nipype/algorithms/tests/test_errormap.py @@ -11,7 +11,6 @@ def test_errormap(tmpdir): - tempdir = str(tmpdir) # Single-Spectual # Make two fake 2*2*2 voxel volumes volume1 = np.array([[[2.0, 8.0], [1.0, 2.0]], [[1.0, 9.0], [0.0, 3.0]]]) # John von Neumann's birthday @@ -22,15 +21,15 @@ def test_errormap(tmpdir): img2 = nb.Nifti1Image(volume2, np.eye(4)) maskimg = nb.Nifti1Image(mask, np.eye(4)) - nb.save(img1, os.path.join(tempdir, 'von.nii.gz')) - nb.save(img2, os.path.join(tempdir, 'alan.nii.gz')) - nb.save(maskimg, os.path.join(tempdir, 'mask.nii.gz')) + nb.save(img1, tmpdir.join('von.nii.gz').strpath) + nb.save(img2, tmpdir.join('alan.nii.gz').strpath) + nb.save(maskimg, tmpdir.join('mask.nii.gz').strpath) # Default metric errmap = ErrorMap() - errmap.inputs.in_tst = os.path.join(tempdir, 'von.nii.gz') - errmap.inputs.in_ref = os.path.join(tempdir, 'alan.nii.gz') - errmap.out_map = os.path.join(tempdir, 'out_map.nii.gz') + errmap.inputs.in_tst = tmpdir.join('von.nii.gz').strpath + errmap.inputs.in_ref = tmpdir.join('alan.nii.gz').strpath + errmap.out_map = tmpdir.join('out_map.nii.gz').strpath result = errmap.run() assert result.outputs.distance == 1.125 @@ -45,7 +44,7 @@ def test_errormap(tmpdir): assert result.outputs.distance == 0.875 # Masked - errmap.inputs.mask = os.path.join(tempdir, 'mask.nii.gz') + errmap.inputs.mask = tmpdir.join('mask.nii.gz').strpath result = errmap.run() assert result.outputs.distance == 1.0 @@ -62,11 +61,11 @@ def test_errormap(tmpdir): msvolume2[:, :, :, 1] = volume1 msimg2 = nb.Nifti1Image(msvolume2, np.eye(4)) - nb.save(msimg1, os.path.join(tempdir, 'von-ray.nii.gz')) - nb.save(msimg2, os.path.join(tempdir, 'alan-ray.nii.gz')) + nb.save(msimg1, tmpdir.join('von-ray.nii.gz').strpath) + nb.save(msimg2, tmpdir.join('alan-ray.nii.gz').strpath) - errmap.inputs.in_tst = os.path.join(tempdir, 'von-ray.nii.gz') - errmap.inputs.in_ref = os.path.join(tempdir, 'alan-ray.nii.gz') + errmap.inputs.in_tst = tmpdir.join('von-ray.nii.gz').strpath + errmap.inputs.in_ref = tmpdir.join('alan-ray.nii.gz').strpath errmap.inputs.metric = 'sqeuclidean' result = errmap.run() assert result.outputs.distance == 5.5 diff --git a/nipype/algorithms/tests/test_mesh_ops.py b/nipype/algorithms/tests/test_mesh_ops.py index fa7ebebe54..9d510dee2b 100644 --- a/nipype/algorithms/tests/test_mesh_ops.py +++ b/nipype/algorithms/tests/test_mesh_ops.py @@ -15,14 +15,13 @@ @pytest.mark.skipif(VTKInfo.no_tvtk(), reason="tvtk is not installed") def test_ident_distances(tmpdir): - tempdir = str(tmpdir) - os.chdir(tempdir) + tmpdir.chdir() in_surf = example_data('surf01.vtk') dist_ident = m.ComputeMeshWarp() dist_ident.inputs.surface1 = in_surf dist_ident.inputs.surface2 = in_surf - dist_ident.inputs.out_file = os.path.join(tempdir, 'distance.npy') + dist_ident.inputs.out_file = tmpdir.join('distance.npy') res = dist_ident.run() assert res.outputs.distance == 0.0 @@ -33,11 +32,11 @@ def test_ident_distances(tmpdir): @pytest.mark.skipif(VTKInfo.no_tvtk(), reason="tvtk is not installed") def test_trans_distances(tmpdir): - tempdir = str(tmpdir) + tempdir = tmpdir.strpath from ...interfaces.vtkbase import tvtk in_surf = example_data('surf01.vtk') - warped_surf = os.path.join(tempdir, 'warped.vtk') + warped_surf = tmpdir.join('warped.vtk') inc = np.array([0.7, 0.3, -0.2]) @@ -53,7 +52,7 @@ def test_trans_distances(tmpdir): dist = m.ComputeMeshWarp() dist.inputs.surface1 = in_surf dist.inputs.surface2 = warped_surf - dist.inputs.out_file = os.path.join(tempdir, 'distance.npy') + dist.inputs.out_file = tmpdir.join('distance.npy') res = dist.run() assert np.allclose(res.outputs.distance, np.linalg.norm(inc), 4) dist.inputs.weighting = 'area' @@ -63,14 +62,14 @@ def test_trans_distances(tmpdir): @pytest.mark.skipif(VTKInfo.no_tvtk(), reason="tvtk is not installed") def test_warppoints(tmpdir): - os.chdir(str(tmpdir)) + tmpdir.chdir() # TODO: include regression tests for when tvtk is installed @pytest.mark.skipif(VTKInfo.no_tvtk(), reason="tvtk is not installed") def test_meshwarpmaths(tmpdir): - os.chdir(str(tmpdir)) + tmpdir.chdir() # TODO: include regression tests for when tvtk is installed diff --git a/nipype/algorithms/tests/test_modelgen.py b/nipype/algorithms/tests/test_modelgen.py index cb10304fea..3c9ec4096b 100644 --- a/nipype/algorithms/tests/test_modelgen.py +++ b/nipype/algorithms/tests/test_modelgen.py @@ -17,9 +17,8 @@ def test_modelgen1(tmpdir): - tempdir = str(tmpdir) - filename1 = os.path.join(tempdir, 'test1.nii') - filename2 = os.path.join(tempdir, 'test2.nii') + filename1 = tmpdir.join('test1.nii').strpath + filename2 = tmpdir.join('test2.nii').strpath Nifti1Image(np.random.rand(10, 10, 10, 200), np.eye(4)).to_filename(filename1) Nifti1Image(np.random.rand(10, 10, 10, 200), np.eye(4)).to_filename(filename2) s = SpecifyModel() @@ -56,9 +55,8 @@ def test_modelgen1(tmpdir): def test_modelgen_spm_concat(tmpdir): - tempdir = str(tmpdir) - filename1 = os.path.join(tempdir, 'test1.nii') - filename2 = os.path.join(tempdir, 'test2.nii') + filename1 = tmpdir.join('test1.nii').strpath + filename2 = tmpdir.join('test2.nii').strpath Nifti1Image(np.random.rand(10, 10, 10, 30), np.eye(4)).to_filename(filename1) Nifti1Image(np.random.rand(10, 10, 10, 30), np.eye(4)).to_filename(filename2) @@ -97,7 +95,7 @@ def test_modelgen_spm_concat(tmpdir): npt.assert_almost_equal(np.array(res.outputs.session_info[0]['cond'][0]['onset']), np.array([2.0, 50.0, 100.0, 170.0])) # Test case for variable number of events in separate runs, sometimes unique. - filename3 = os.path.join(tempdir, 'test3.nii') + filename3 = tmpdir.join('test3.nii').strpath Nifti1Image(np.random.rand(10, 10, 10, 30), np.eye(4)).to_filename(filename3) s.inputs.functional_runs = [filename1, filename2, filename3] info = [Bunch(conditions=['cond1', 'cond2'], onsets=[[2, 3], [2]], durations=[[1, 1], [1]]), @@ -122,9 +120,8 @@ def test_modelgen_spm_concat(tmpdir): def test_modelgen_sparse(tmpdir): - tempdir = str(tmpdir) - filename1 = os.path.join(tempdir, 'test1.nii') - filename2 = os.path.join(tempdir, 'test2.nii') + filename1 = tmpdir.join('test1.nii').strpath + filename2 = tmpdir.join('test2.nii').strpath Nifti1Image(np.random.rand(10, 10, 10, 50), np.eye(4)).to_filename(filename1) Nifti1Image(np.random.rand(10, 10, 10, 50), np.eye(4)).to_filename(filename2) s = SpecifySparseModel() diff --git a/nipype/algorithms/tests/test_moments.py b/nipype/algorithms/tests/test_moments.py index 12de44750a..17c8e922b2 100644 --- a/nipype/algorithms/tests/test_moments.py +++ b/nipype/algorithms/tests/test_moments.py @@ -1,10 +1,9 @@ # -*- coding: utf-8 -*- import numpy as np -import tempfile from nipype.algorithms.misc import calc_moments -def test_skew(): +def test_skew(tmpdir): data = """14.62418305 5.916396751 -1.658088086 4.71113546 1.598428608 5.612553811 -5.004056368 -4.057513911 11.16365251 17.32688599 -3.099920667 2.630189741 2.389709914 0.379332731 -0.2899694205 -4.363591482 2.059205599 23.90705054 0.7180462297 -1.976963652 7.487682025 -5.583986129 1.094800525 -2.319858134 @@ -126,13 +125,12 @@ def test_skew(): -0.5057854071 -2.415896554 -9.663571931 -5.714041661 -6.037933426 8.673756933 10.03557773 8.629816199 3.622185659 0.4716627142 -10.92515308 -3.705286841 -2.776089545 2.271920902 9.251504922 5.744980887 """ - with tempfile.NamedTemporaryFile(mode='w', delete=True) as f: - f.write(data) - f.flush() - skewness = calc_moments(f.name, 3) - assert np.allclose(skewness, np.array( - [-0.23418937314622, 0.2946365564954823, -0.05781002053540932, - -0.3512508282578762, - - 0.07035664150233077, - - 0.01935867699166935, - 0.00483863369427428, 0.21879460029850167])) + f = tmpdir.join("filetest") + f.write(data) + skewness = calc_moments(f.strpath, 3) + assert np.allclose(skewness, np.array( + [-0.23418937314622, 0.2946365564954823, -0.05781002053540932, + -0.3512508282578762, - + 0.07035664150233077, - + 0.01935867699166935, + 0.00483863369427428, 0.21879460029850167])) diff --git a/nipype/algorithms/tests/test_normalize_tpms.py b/nipype/algorithms/tests/test_normalize_tpms.py index 19a183bee0..5d0fc5c47b 100644 --- a/nipype/algorithms/tests/test_normalize_tpms.py +++ b/nipype/algorithms/tests/test_normalize_tpms.py @@ -18,7 +18,6 @@ def test_normalize_tpms(tmpdir): - tempdir = str(tmpdir) in_mask = example_data('tpms_msk.nii.gz') mskdata = nb.load(in_mask, mmap=NUMPY_MMAP).get_data() @@ -30,8 +29,8 @@ def test_normalize_tpms(tmpdir): for i in range(3): mapname = example_data('tpm_%02d.nii.gz' % i) - filename = os.path.join(tempdir, 'modtpm_%02d.nii.gz' % i) - out_files.append(os.path.join(tempdir, 'normtpm_%02d.nii.gz' % i)) + filename = tmpdir.join('modtpm_%02d.nii.gz' % i).strpath + out_files.append(tmpdir.join('normtpm_%02d.nii.gz' % i).strpath) im = nb.load(mapname, mmap=NUMPY_MMAP) data = im.get_data() diff --git a/nipype/algorithms/tests/test_overlap.py b/nipype/algorithms/tests/test_overlap.py index ab0f564b1a..e0ec5bcfcb 100644 --- a/nipype/algorithms/tests/test_overlap.py +++ b/nipype/algorithms/tests/test_overlap.py @@ -20,7 +20,7 @@ def check_close(val1, val2): in1 = example_data('segmentation0.nii.gz') in2 = example_data('segmentation1.nii.gz') - os.chdir(str(tmpdir)) + tmpdir.chdir() overlap = Overlap() overlap.inputs.volume1 = in1 overlap.inputs.volume2 = in1 diff --git a/nipype/algorithms/tests/test_splitmerge.py b/nipype/algorithms/tests/test_splitmerge.py index e122fef077..d7e98a47ba 100644 --- a/nipype/algorithms/tests/test_splitmerge.py +++ b/nipype/algorithms/tests/test_splitmerge.py @@ -14,13 +14,13 @@ def test_split_and_merge(tmpdir): from nipype.algorithms.misc import split_rois, merge_rois in_mask = example_data('tpms_msk.nii.gz') - dwfile = op.join(str(tmpdir), 'dwi.nii.gz') + dwfile = tmpdir.join('dwi.nii.gz').strpath mskdata = nb.load(in_mask, mmap=NUMPY_MMAP).get_data() aff = nb.load(in_mask, mmap=NUMPY_MMAP).affine dwshape = (mskdata.shape[0], mskdata.shape[1], mskdata.shape[2], 6) dwdata = np.random.normal(size=dwshape) - os.chdir(str(tmpdir)) + tmpdir.chdir() nb.Nifti1Image(dwdata.astype(np.float32), aff, None).to_filename(dwfile) diff --git a/nipype/algorithms/tests/test_tsnr.py b/nipype/algorithms/tests/test_tsnr.py index e53ffd2f34..f4bac9a17d 100644 --- a/nipype/algorithms/tests/test_tsnr.py +++ b/nipype/algorithms/tests/test_tsnr.py @@ -30,8 +30,7 @@ class TestTSNR(): @pytest.fixture(autouse=True) def setup_class(self, tmpdir): # setup temp folder - self.temp_dir = str(tmpdir) - os.chdir(self.temp_dir) + tmpdir.chdir() utils.save_toy_nii(self.fake_data, self.in_filenames['in_file']) diff --git a/nipype/caching/tests/test_memory.py b/nipype/caching/tests/test_memory.py index d2968ae3f2..50f56d4700 100644 --- a/nipype/caching/tests/test_memory.py +++ b/nipype/caching/tests/test_memory.py @@ -25,7 +25,7 @@ def test_caching(tmpdir): try: # Prevent rerun to check that evaluation is computed only once config.set('execution', 'stop_on_first_rerun', 'true') - mem = Memory(str(tmpdir)) + mem = Memory(tmpdir.strpath) first_nb_run = nb_runs results = mem.cache(SideEffectInterface)(input1=2, input2=1) assert nb_runs == first_nb_run + 1 diff --git a/nipype/interfaces/afni/base.py b/nipype/interfaces/afni/base.py index 3405f96cfa..1097a28d46 100644 --- a/nipype/interfaces/afni/base.py +++ b/nipype/interfaces/afni/base.py @@ -14,45 +14,26 @@ from ...utils.filemanip import split_filename, fname_presuffix from ..base import ( - CommandLine, traits, CommandLineInputSpec, isdefined, File, TraitedSpec) + CommandLine, traits, CommandLineInputSpec, isdefined, File, TraitedSpec, + PackageInfo) from ...external.due import BibTeX # Use nipype's logging system IFLOGGER = logging.getLogger('interface') -class Info(object): +class Info(PackageInfo): """Handle afni output type and version information. """ __outputtype = 'AFNI' ftypes = {'NIFTI': '.nii', 'AFNI': '', 'NIFTI_GZ': '.nii.gz'} + version_cmd = 'afni --version' @staticmethod - def version(): - """Check for afni version on system - - Parameters - ---------- - None - - Returns - ------- - version : str - Version number as string or None if AFNI not found - - """ - try: - clout = CommandLine(command='afni --version', - resource_monitor=False, - terminal_output='allatonce').run() - except IOError: - # If afni_vcheck is not present, return None - IFLOGGER.warn('afni executable not found.') - return None - - version_stamp = clout.runtime.stdout.split('\n')[0].split('Version ')[1] + def parse_version(raw_info): + version_stamp = raw_info.split('\n')[0].split('Version ')[1] if version_stamp.startswith('AFNI'): version_stamp = version_stamp.split('AFNI_')[1] elif version_stamp.startswith('Debian'): diff --git a/nipype/interfaces/afni/model.py b/nipype/interfaces/afni/model.py index 4fdc533a1b..d5730d15f9 100644 --- a/nipype/interfaces/afni/model.py +++ b/nipype/interfaces/afni/model.py @@ -260,7 +260,7 @@ class Deconvolve(AFNICommand): >>> deconvolve.inputs.stim_label = [(1, 'Houses')] >>> deconvolve.inputs.gltsym = ['SYM: +Houses'] >>> deconvolve.inputs.glt_label = [(1, 'Houses')] - >>> deconvolve.cmdline # doctest: +ALLOW_UNICODE + >>> deconvolve.cmdline "3dDeconvolve -input functional.nii functional2.nii -bucket output.nii -x1D output.1D -num_stimts 1 -stim_times 1 timeseries.txt 'SPMG1(4)' -stim_label 1 Houses -num_glt 1 -gltsym 'SYM: +Houses' -glt_label 1 Houses" >>> res = deconvolve.run() # doctest: +SKIP """ @@ -574,7 +574,7 @@ class Remlfit(AFNICommand): >>> remlfit.inputs.out_file = 'output.nii' >>> remlfit.inputs.matrix = 'output.1D' >>> remlfit.inputs.gltsym = [('SYM: +Lab1 -Lab2', 'TestSYM'), ('timeseries.txt', 'TestFile')] - >>> remlfit.cmdline # doctest: +ALLOW_UNICODE + >>> remlfit.cmdline '3dREMLfit -gltsym "SYM: +Lab1 -Lab2" TestSYM -gltsym "timeseries.txt" TestFile -input "functional.nii functional2.nii" -matrix output.1D -Rbuck output.nii' >>> res = remlfit.run() # doctest: +SKIP """ @@ -660,7 +660,7 @@ class Synthesize(AFNICommand): >>> synthesize.inputs.cbucket = 'functional.nii' >>> synthesize.inputs.matrix = 'output.1D' >>> synthesize.inputs.select = ['baseline'] - >>> synthesize.cmdline # doctest: +ALLOW_UNICODE + >>> synthesize.cmdline '3dSynthesize -cbucket functional.nii -matrix output.1D -select baseline' >>> syn = synthesize.run() # doctest: +SKIP """ diff --git a/nipype/interfaces/afni/preprocess.py b/nipype/interfaces/afni/preprocess.py index a769811df1..3d7d47c673 100644 --- a/nipype/interfaces/afni/preprocess.py +++ b/nipype/interfaces/afni/preprocess.py @@ -169,7 +169,7 @@ class AlignEpiAnatPy(AFNIPythonCommand): >>> al_ea.inputs.volreg = 'off' >>> al_ea.inputs.tshift = 'off' >>> al_ea.inputs.save_skullstrip = True - >>> al_ea.cmdline # doctest: +ALLOW_UNICODE +ELLIPSIS + >>> al_ea.cmdline # doctest: +ELLIPSIS 'python2 ...align_epi_anat.py -anat structural.nii -epi_base 0 -epi_strip 3dAutomask -epi functional.nii -save_skullstrip -suffix _al -tshift off -volreg off' >>> res = allineate.run() # doctest: +SKIP """ @@ -462,7 +462,7 @@ class Allineate(AFNICommand): >>> allineate.inputs.in_file = 'functional.nii' >>> allineate.inputs.out_file = 'functional_allineate.nii' >>> allineate.inputs.in_matrix = 'cmatrix.mat' - >>> allineate.cmdline # doctest: +ALLOW_UNICODE + >>> allineate.cmdline '3dAllineate -source functional.nii -prefix functional_allineate.nii -1Dmatrix_apply cmatrix.mat' >>> res = allineate.run() # doctest: +SKIP @@ -471,7 +471,7 @@ class Allineate(AFNICommand): >>> allineate.inputs.in_file = 'functional.nii' >>> allineate.inputs.reference = 'structural.nii' >>> allineate.inputs.allcostx = 'out.allcostX.txt' - >>> allineate.cmdline # doctest: +ALLOW_UNICODE + >>> allineate.cmdline '3dAllineate -source functional.nii -base structural.nii -allcostx |& tee out.allcostX.txt' >>> res = allineate.run() # doctest: +SKIP """ @@ -574,7 +574,7 @@ class AutoTcorrelate(AFNICommand): >>> corr.inputs.eta2 = True >>> corr.inputs.mask = 'mask.nii' >>> corr.inputs.mask_only_targets = True - >>> corr.cmdline # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE +ALLOW_UNICODE + >>> corr.cmdline # doctest: +ELLIPSIS '3dAutoTcorrelate -eta2 -mask mask.nii -mask_only_targets -prefix functional_similarity_matrix.1D -polort -1 functional.nii' >>> res = corr.run() # doctest: +SKIP """ @@ -643,7 +643,7 @@ class Automask(AFNICommand): >>> automask.inputs.in_file = 'functional.nii' >>> automask.inputs.dilate = 1 >>> automask.inputs.outputtype = 'NIFTI' - >>> automask.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> automask.cmdline # doctest: +ELLIPSIS '3dAutomask -apply_prefix functional_masked.nii -dilate 1 -prefix functional_mask.nii functional.nii' >>> res = automask.run() # doctest: +SKIP @@ -737,7 +737,7 @@ class AutoTLRC(AFNICommand): >>> autoTLRC.inputs.in_file = 'structural.nii' >>> autoTLRC.inputs.no_ss = True >>> autoTLRC.inputs.base = "TT_N27+tlrc" - >>> autoTLRC.cmdline # doctest: +ALLOW_UNICODE + >>> autoTLRC.cmdline '@auto_tlrc -base TT_N27+tlrc -input structural.nii -no_ss' >>> res = autoTLRC.run() # doctest: +SKIP @@ -849,7 +849,7 @@ class Bandpass(AFNICommand): >>> bandpass.inputs.in_file = 'functional.nii' >>> bandpass.inputs.highpass = 0.005 >>> bandpass.inputs.lowpass = 0.1 - >>> bandpass.cmdline # doctest: +ALLOW_UNICODE + >>> bandpass.cmdline '3dBandpass -prefix functional_bp 0.005000 0.100000 functional.nii' >>> res = bandpass.run() # doctest: +SKIP @@ -917,7 +917,7 @@ class BlurInMask(AFNICommand): >>> bim.inputs.in_file = 'functional.nii' >>> bim.inputs.mask = 'mask.nii' >>> bim.inputs.fwhm = 5.0 - >>> bim.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> bim.cmdline # doctest: +ELLIPSIS '3dBlurInMask -input functional.nii -FWHM 5.000000 -mask mask.nii -prefix functional_blur' >>> res = bim.run() # doctest: +SKIP @@ -968,7 +968,7 @@ class BlurToFWHM(AFNICommand): >>> blur = afni.preprocess.BlurToFWHM() >>> blur.inputs.in_file = 'epi.nii' >>> blur.inputs.fwhm = 2.5 - >>> blur.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> blur.cmdline # doctest: +ELLIPSIS '3dBlurToFWHM -FWHM 2.500000 -input epi.nii -prefix epi_afni' >>> res = blur.run() # doctest: +SKIP @@ -1019,7 +1019,7 @@ class ClipLevel(AFNICommandBase): >>> from nipype.interfaces.afni import preprocess >>> cliplevel = preprocess.ClipLevel() >>> cliplevel.inputs.in_file = 'anatomical.nii' - >>> cliplevel.cmdline # doctest: +ALLOW_UNICODE + >>> cliplevel.cmdline '3dClipLevel anatomical.nii' >>> res = cliplevel.run() # doctest: +SKIP @@ -1102,7 +1102,7 @@ class DegreeCentrality(AFNICommand): >>> degree.inputs.mask = 'mask.nii' >>> degree.inputs.sparsity = 1 # keep the top one percent of connections >>> degree.inputs.out_file = 'out.nii' - >>> degree.cmdline # doctest: +ALLOW_UNICODE + >>> degree.cmdline '3dDegreeCentrality -mask mask.nii -prefix out.nii -sparsity 1.000000 functional.nii' >>> res = degree.run() # doctest: +SKIP @@ -1152,7 +1152,7 @@ class Despike(AFNICommand): >>> from nipype.interfaces import afni >>> despike = afni.Despike() >>> despike.inputs.in_file = 'functional.nii' - >>> despike.cmdline # doctest: +ALLOW_UNICODE + >>> despike.cmdline '3dDespike -prefix functional_despike functional.nii' >>> res = despike.run() # doctest: +SKIP @@ -1193,7 +1193,7 @@ class Detrend(AFNICommand): >>> detrend.inputs.in_file = 'functional.nii' >>> detrend.inputs.args = '-polort 2' >>> detrend.inputs.outputtype = 'AFNI' - >>> detrend.cmdline # doctest: +ALLOW_UNICODE + >>> detrend.cmdline '3dDetrend -polort 2 -prefix functional_detrend functional.nii' >>> res = detrend.run() # doctest: +SKIP @@ -1265,7 +1265,7 @@ class ECM(AFNICommand): >>> ecm.inputs.mask = 'mask.nii' >>> ecm.inputs.sparsity = 0.1 # keep top 0.1% of connections >>> ecm.inputs.out_file = 'out.nii' - >>> ecm.cmdline # doctest: +ALLOW_UNICODE + >>> ecm.cmdline '3dECM -mask mask.nii -prefix out.nii -sparsity 0.100000 functional.nii' >>> res = ecm.run() # doctest: +SKIP @@ -1322,7 +1322,7 @@ class Fim(AFNICommand): >>> fim.inputs.out_file = 'functional_corr.nii' >>> fim.inputs.out = 'Correlation' >>> fim.inputs.fim_thr = 0.0009 - >>> fim.cmdline # doctest: +ALLOW_UNICODE + >>> fim.cmdline '3dfim+ -input functional.nii -ideal_file seed.1D -fim_thr 0.000900 -out Correlation -bucket functional_corr.nii' >>> res = fim.run() # doctest: +SKIP @@ -1376,7 +1376,7 @@ class Fourier(AFNICommand): >>> fourier.inputs.retrend = True >>> fourier.inputs.highpass = 0.005 >>> fourier.inputs.lowpass = 0.1 - >>> fourier.cmdline # doctest: +ALLOW_UNICODE + >>> fourier.cmdline '3dFourier -highpass 0.005000 -lowpass 0.100000 -prefix functional_fourier -retrend functional.nii' >>> res = fourier.run() # doctest: +SKIP @@ -1449,7 +1449,7 @@ class Hist(AFNICommandBase): >>> from nipype.interfaces import afni >>> hist = afni.Hist() >>> hist.inputs.in_file = 'functional.nii' - >>> hist.cmdline # doctest: +ALLOW_UNICODE + >>> hist.cmdline '3dHist -input functional.nii -prefix functional_hist' >>> res = hist.run() # doctest: +SKIP @@ -1513,7 +1513,7 @@ class LFCD(AFNICommand): >>> lfcd.inputs.mask = 'mask.nii' >>> lfcd.inputs.thresh = 0.8 # keep all connections with corr >= 0.8 >>> lfcd.inputs.out_file = 'out.nii' - >>> lfcd.cmdline # doctest: +ALLOW_UNICODE + >>> lfcd.cmdline '3dLFCD -mask mask.nii -prefix out.nii -thresh 0.800000 functional.nii' >>> res = lfcd.run() # doctest: +SKIP """ @@ -1564,7 +1564,7 @@ class Maskave(AFNICommand): >>> maskave.inputs.in_file = 'functional.nii' >>> maskave.inputs.mask= 'seed_mask.nii' >>> maskave.inputs.quiet= True - >>> maskave.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> maskave.cmdline # doctest: +ELLIPSIS '3dmaskave -mask seed_mask.nii -quiet functional.nii > functional_maskave.1D' >>> res = maskave.run() # doctest: +SKIP @@ -1635,7 +1635,7 @@ class Means(AFNICommand): >>> means.inputs.in_file_a = 'im1.nii' >>> means.inputs.in_file_b = 'im2.nii' >>> means.inputs.out_file = 'output.nii' - >>> means.cmdline # doctest: +ALLOW_UNICODE + >>> means.cmdline '3dMean -prefix output.nii im1.nii im2.nii' >>> res = means.run() # doctest: +SKIP @@ -1644,7 +1644,7 @@ class Means(AFNICommand): >>> means.inputs.in_file_a = 'im1.nii' >>> means.inputs.out_file = 'output.nii' >>> means.inputs.datum = 'short' - >>> means.cmdline # doctest: +ALLOW_UNICODE + >>> means.cmdline '3dMean -datum short -prefix output.nii im1.nii' >>> res = means.run() # doctest: +SKIP @@ -1742,7 +1742,7 @@ class OutlierCount(CommandLine): >>> from nipype.interfaces import afni >>> toutcount = afni.OutlierCount() >>> toutcount.inputs.in_file = 'functional.nii' - >>> toutcount.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> toutcount.cmdline # doctest: +ELLIPSIS '3dToutcount functional.nii' >>> res = toutcount.run() # doctest: +SKIP @@ -1855,7 +1855,7 @@ class QualityIndex(CommandLine): >>> from nipype.interfaces import afni >>> tqual = afni.QualityIndex() >>> tqual.inputs.in_file = 'functional.nii' - >>> tqual.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> tqual.cmdline # doctest: +ELLIPSIS '3dTqual functional.nii > functional_tqual' >>> res = tqual.run() # doctest: +SKIP @@ -1912,7 +1912,7 @@ class ROIStats(AFNICommandBase): >>> roistats.inputs.in_file = 'functional.nii' >>> roistats.inputs.mask = 'skeleton_mask.nii.gz' >>> roistats.inputs.quiet = True - >>> roistats.cmdline # doctest: +ALLOW_UNICODE + >>> roistats.cmdline '3dROIstats -quiet -mask skeleton_mask.nii.gz functional.nii' >>> res = roistats.run() # doctest: +SKIP @@ -2007,7 +2007,7 @@ class Retroicor(AFNICommand): >>> ret.inputs.card = 'mask.1D' >>> ret.inputs.resp = 'resp.1D' >>> ret.inputs.outputtype = 'NIFTI' - >>> ret.cmdline # doctest: +ALLOW_UNICODE + >>> ret.cmdline '3dretroicor -prefix functional_retroicor.nii -resp resp.1D -card mask.1D functional.nii' >>> res = ret.run() # doctest: +SKIP @@ -2090,7 +2090,7 @@ class Seg(AFNICommandBase): >>> seg = preprocess.Seg() >>> seg.inputs.in_file = 'structural.nii' >>> seg.inputs.mask = 'AUTO' - >>> seg.cmdline # doctest: +ALLOW_UNICODE + >>> seg.cmdline '3dSeg -mask AUTO -anat structural.nii' >>> res = seg.run() # doctest: +SKIP @@ -2146,7 +2146,7 @@ class SkullStrip(AFNICommand): >>> skullstrip = afni.SkullStrip() >>> skullstrip.inputs.in_file = 'functional.nii' >>> skullstrip.inputs.args = '-o_ply' - >>> skullstrip.cmdline # doctest: +ALLOW_UNICODE + >>> skullstrip.cmdline '3dSkullStrip -input functional.nii -o_ply -prefix functional_skullstrip' >>> res = skullstrip.run() # doctest: +SKIP @@ -2225,7 +2225,7 @@ class TCorr1D(AFNICommand): >>> tcorr1D = afni.TCorr1D() >>> tcorr1D.inputs.xset= 'u_rc1s1_Template.nii' >>> tcorr1D.inputs.y_1d = 'seed.1D' - >>> tcorr1D.cmdline # doctest: +ALLOW_UNICODE + >>> tcorr1D.cmdline '3dTcorr1D -prefix u_rc1s1_Template_correlation.nii.gz u_rc1s1_Template.nii seed.1D' >>> res = tcorr1D.run() # doctest: +SKIP @@ -2367,7 +2367,7 @@ class TCorrMap(AFNICommand): >>> tcm.inputs.in_file = 'functional.nii' >>> tcm.inputs.mask = 'mask.nii' >>> tcm.mean_file = 'functional_meancorr.nii' - >>> tcm.cmdline # doctest: +ALLOW_UNICODE +SKIP + >>> tcm.cmdline # doctest: +SKIP '3dTcorrMap -input functional.nii -mask mask.nii -Mean functional_meancorr.nii' >>> res = tcm.run() # doctest: +SKIP @@ -2435,7 +2435,7 @@ class TCorrelate(AFNICommand): >>> tcorrelate.inputs.out_file = 'functional_tcorrelate.nii.gz' >>> tcorrelate.inputs.polort = -1 >>> tcorrelate.inputs.pearson = True - >>> tcorrelate.cmdline # doctest: +ALLOW_UNICODE + >>> tcorrelate.cmdline '3dTcorrelate -prefix functional_tcorrelate.nii.gz -pearson -polort -1 u_rc1s1_Template.nii u_rc1s2_Template.nii' >>> res = tcarrelate.run() # doctest: +SKIP @@ -2497,7 +2497,7 @@ class TNorm(AFNICommand): >>> tnorm.inputs.in_file = 'functional.nii' >>> tnorm.inputs.norm2 = True >>> tnorm.inputs.out_file = 'rm.errts.unit errts+tlrc' - >>> tnorm.cmdline # doctest: +ALLOW_UNICODE + >>> tnorm.cmdline '3dTnorm -norm2 -prefix rm.errts.unit errts+tlrc functional.nii' >>> res = tshift.run() # doctest: +SKIP @@ -2567,7 +2567,7 @@ class TShift(AFNICommand): >>> tshift.inputs.in_file = 'functional.nii' >>> tshift.inputs.tpattern = 'alt+z' >>> tshift.inputs.tzero = 0.0 - >>> tshift.cmdline # doctest: +ALLOW_UNICODE + >>> tshift.cmdline '3dTshift -prefix functional_tshift -tpattern alt+z -tzero 0.0 functional.nii' >>> res = tshift.run() # doctest: +SKIP @@ -2663,7 +2663,7 @@ class Volreg(AFNICommand): >>> volreg.inputs.args = '-Fourier -twopass' >>> volreg.inputs.zpad = 4 >>> volreg.inputs.outputtype = 'NIFTI' - >>> volreg.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> volreg.cmdline # doctest: +ELLIPSIS '3dvolreg -Fourier -twopass -1Dfile functional.1D -1Dmatrix_save functional.aff12.1D -prefix functional_volreg.nii -zpad 4 -maxdisp1D functional_md.1D functional.nii' >>> res = volreg.run() # doctest: +SKIP @@ -2677,7 +2677,7 @@ class Volreg(AFNICommand): >>> volreg.inputs.out_file = 'rm.epi.volreg.r1' >>> volreg.inputs.oned_file = 'dfile.r1.1D' >>> volreg.inputs.oned_matrix_save = 'mat.r1.tshift+orig.1D' - >>> volreg.cmdline # doctest: +ALLOW_UNICODE + >>> volreg.cmdline '3dvolreg -cubic -1Dfile dfile.r1.1D -1Dmatrix_save mat.r1.tshift+orig.1D -prefix rm.epi.volreg.r1 -verbose -base functional.nii -zpad 1 -maxdisp1D functional_md.1D functional.nii' >>> res = volreg.run() # doctest: +SKIP @@ -2752,7 +2752,7 @@ class Warp(AFNICommand): >>> warp.inputs.in_file = 'structural.nii' >>> warp.inputs.deoblique = True >>> warp.inputs.out_file = 'trans.nii.gz' - >>> warp.cmdline # doctest: +ALLOW_UNICODE + >>> warp.cmdline '3dWarp -deoblique -prefix trans.nii.gz structural.nii' >>> res = warp.run() # doctest: +SKIP @@ -2760,7 +2760,7 @@ class Warp(AFNICommand): >>> warp_2.inputs.in_file = 'structural.nii' >>> warp_2.inputs.newgrid = 1.0 >>> warp_2.inputs.out_file = 'trans.nii.gz' - >>> warp_2.cmdline # doctest: +ALLOW_UNICODE + >>> warp_2.cmdline '3dWarp -newgrid 1.000000 -prefix trans.nii.gz structural.nii' >>> res = warp_2.run() # doctest: +SKIP @@ -2854,7 +2854,7 @@ class QwarpPlusMinus(CommandLine): >>> qwarp.inputs.source_file = 'sub-01_dir-LR_epi.nii.gz' >>> qwarp.inputs.nopadWARP = True >>> qwarp.inputs.base_file = 'sub-01_dir-RL_epi.nii.gz' - >>> qwarp.cmdline # doctest: +ALLOW_UNICODE + >>> qwarp.cmdline '3dQwarp -prefix Qwarp.nii.gz -plusminus -base sub-01_dir-RL_epi.nii.gz -nopadWARP -source sub-01_dir-LR_epi.nii.gz' >>> res = warp.run() # doctest: +SKIP @@ -3426,7 +3426,7 @@ class Qwarp(AFNICommand): >>> qwarp.inputs.nopadWARP = True >>> qwarp.inputs.base_file = 'sub-01_dir-RL_epi.nii.gz' >>> qwarp.inputs.plusminus = True - >>> qwarp.cmdline # doctest: +ALLOW_UNICODE + >>> qwarp.cmdline '3dQwarp -base sub-01_dir-RL_epi.nii.gz -source sub-01_dir-LR_epi.nii.gz -nopadWARP -prefix sub-01_dir-LR_epi_QW -plusminus' >>> res = qwarp.run() # doctest: +SKIP @@ -3435,7 +3435,7 @@ class Qwarp(AFNICommand): >>> qwarp.inputs.in_file = 'structural.nii' >>> qwarp.inputs.base_file = 'mni.nii' >>> qwarp.inputs.resample = True - >>> qwarp.cmdline # doctest: +ALLOW_UNICODE + >>> qwarp.cmdline '3dQwarp -base mni.nii -source structural.nii -prefix structural_QW -resample' >>> res = qwarp.run() # doctest: +SKIP @@ -3449,7 +3449,7 @@ class Qwarp(AFNICommand): >>> qwarp.inputs.verb = True >>> qwarp.inputs.iwarp = True >>> qwarp.inputs.blur = [0,3] - >>> qwarp.cmdline # doctest: +ALLOW_UNICODE + >>> qwarp.cmdline '3dQwarp -base epi.nii -blur 0.0 3.0 -source structural.nii -iwarp -prefix anatSSQ.nii.gz -resample -verb -lpc' >>> res = qwarp.run() # doctest: +SKIP @@ -3459,7 +3459,7 @@ class Qwarp(AFNICommand): >>> qwarp.inputs.base_file = 'mni.nii' >>> qwarp.inputs.duplo = True >>> qwarp.inputs.blur = [0,3] - >>> qwarp.cmdline # doctest: +ALLOW_UNICODE + >>> qwarp.cmdline '3dQwarp -base mni.nii -blur 0.0 3.0 -duplo -source structural.nii -prefix structural_QW' >>> res = qwarp.run() # doctest: +SKIP @@ -3471,7 +3471,7 @@ class Qwarp(AFNICommand): >>> qwarp.inputs.minpatch = 25 >>> qwarp.inputs.blur = [0,3] >>> qwarp.inputs.out_file = 'Q25' - >>> qwarp.cmdline # doctest: +ALLOW_UNICODE + >>> qwarp.cmdline '3dQwarp -base mni.nii -blur 0.0 3.0 -duplo -source structural.nii -minpatch 25 -prefix Q25' >>> res = qwarp.run() # doctest: +SKIP >>> qwarp2 = afni.Qwarp() @@ -3481,7 +3481,7 @@ class Qwarp(AFNICommand): >>> qwarp2.inputs.out_file = 'Q11' >>> qwarp2.inputs.inilev = 7 >>> qwarp2.inputs.iniwarp = ['Q25_warp+tlrc.HEAD'] - >>> qwarp2.cmdline # doctest: +ALLOW_UNICODE + >>> qwarp2.cmdline '3dQwarp -base mni.nii -blur 0.0 2.0 -source structural.nii -inilev 7 -iniwarp Q25_warp+tlrc.HEAD -prefix Q11' >>> res2 = qwarp2.run() # doctest: +SKIP >>> res2 = qwarp2.run() # doctest: +SKIP @@ -3519,7 +3519,6 @@ def _list_outputs(self): else: ext = prefix[ext_ind:] suffix = '' - print(ext,"ext") outputs['warped_source'] = fname_presuffix(prefix, suffix=suffix, use_ext=False) + ext if not self.inputs.nowarp: diff --git a/nipype/interfaces/afni/tests/test_auto_Refit.py b/nipype/interfaces/afni/tests/test_auto_Refit.py index 06c5f98255..63ab824617 100644 --- a/nipype/interfaces/afni/tests/test_auto_Refit.py +++ b/nipype/interfaces/afni/tests/test_auto_Refit.py @@ -42,6 +42,8 @@ def test_Refit_inputs(): ), xorigin=dict(argstr='-xorigin %s', ), + xyzscale=dict(argstr='-xyzscale %f', + ), ydel=dict(argstr='-ydel %f', ), yorigin=dict(argstr='-yorigin %s', diff --git a/nipype/interfaces/afni/utils.py b/nipype/interfaces/afni/utils.py index 8245578780..e492b39d47 100644 --- a/nipype/interfaces/afni/utils.py +++ b/nipype/interfaces/afni/utils.py @@ -74,7 +74,7 @@ class ABoverlap(AFNICommand): >>> aboverlap.inputs.in_file_a = 'functional.nii' >>> aboverlap.inputs.in_file_b = 'structural.nii' >>> aboverlap.inputs.out_file = 'out.mask_ae_overlap.txt' - >>> aboverlap.cmdline # doctest: +ALLOW_UNICODE + >>> aboverlap.cmdline '3dABoverlap functional.nii structural.nii |& tee out.mask_ae_overlap.txt' >>> res = aboverlap.run() # doctest: +SKIP @@ -139,7 +139,7 @@ class AFNItoNIFTI(AFNICommand): >>> a2n = afni.AFNItoNIFTI() >>> a2n.inputs.in_file = 'afni_output.3D' >>> a2n.inputs.out_file = 'afni_output.nii' - >>> a2n.cmdline # doctest: +ALLOW_UNICODE + >>> a2n.cmdline '3dAFNItoNIFTI -prefix afni_output.nii afni_output.3D' >>> res = a2n.run() # doctest: +SKIP @@ -207,7 +207,7 @@ class Autobox(AFNICommand): >>> abox = afni.Autobox() >>> abox.inputs.in_file = 'structural.nii' >>> abox.inputs.padding = 5 - >>> abox.cmdline # doctest: +ALLOW_UNICODE + >>> abox.cmdline '3dAutobox -input structural.nii -prefix structural_autobox -npad 5' >>> res = abox.run() # doctest: +SKIP @@ -288,7 +288,7 @@ class BrickStat(AFNICommandBase): >>> brickstat.inputs.in_file = 'functional.nii' >>> brickstat.inputs.mask = 'skeleton_mask.nii.gz' >>> brickstat.inputs.min = True - >>> brickstat.cmdline # doctest: +ALLOW_UNICODE + >>> brickstat.cmdline '3dBrickStat -min -mask skeleton_mask.nii.gz functional.nii' >>> res = brickstat.run() # doctest: +SKIP @@ -395,7 +395,7 @@ class Bucket(AFNICommand): >>> bucket = afni.Bucket() >>> bucket.inputs.in_file = [('functional.nii',"{2..$}"), ('functional.nii',"{1}")] >>> bucket.inputs.out_file = 'vr_base' - >>> bucket.cmdline # doctest: +ALLOW_UNICODE + >>> bucket.cmdline "3dbucket -prefix vr_base functional.nii'{2..$}' functional.nii'{1}'" >>> res = bucket.run() # doctest: +SKIP @@ -469,7 +469,7 @@ class Calc(AFNICommand): >>> calc.inputs.expr='a*b' >>> calc.inputs.out_file = 'functional_calc.nii.gz' >>> calc.inputs.outputtype = 'NIFTI' - >>> calc.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> calc.cmdline # doctest: +ELLIPSIS '3dcalc -a functional.nii -b functional2.nii -expr "a*b" -prefix functional_calc.nii.gz' >>> res = calc.run() # doctest: +SKIP @@ -479,7 +479,7 @@ class Calc(AFNICommand): >>> calc.inputs.expr = '1' >>> calc.inputs.out_file = 'rm.epi.all1' >>> calc.inputs.overwrite = True - >>> calc.cmdline # doctest: +ALLOW_UNICODE + >>> calc.cmdline '3dcalc -a functional.nii -expr "1" -prefix rm.epi.all1 -overwrite' >>> res = calc.run() # doctest: +SKIP @@ -574,7 +574,7 @@ class Cat(AFNICommand): >>> cat1d.inputs.sel = "'[0,2]'" >>> cat1d.inputs.in_files = ['f1.1D', 'f2.1D'] >>> cat1d.inputs.out_file = 'catout.1d' - >>> cat1d.cmdline # doctest: +ALLOW_UNICODE + >>> cat1d.cmdline "1dcat -sel '[0,2]' f1.1D f2.1D > catout.1d" >>> res = cat1d.run() # doctest: +SKIP @@ -627,7 +627,7 @@ class CatMatvec(AFNICommand): >>> cmv = afni.CatMatvec() >>> cmv.inputs.in_file = [('structural.BRIK::WARP_DATA','I')] >>> cmv.inputs.out_file = 'warp.anat.Xat.1D' - >>> cmv.cmdline # doctest: +ALLOW_UNICODE + >>> cmv.cmdline 'cat_matvec structural.BRIK::WARP_DATA -I > warp.anat.Xat.1D' >>> res = cmv.run() # doctest: +SKIP @@ -719,7 +719,7 @@ class CenterMass(AFNICommandBase): >>> cm.inputs.in_file = 'structural.nii' >>> cm.inputs.cm_file = 'cm.txt' >>> cm.inputs.roi_vals = [2, 10] - >>> cm.cmdline # doctest: +ALLOW_UNICODE + >>> cm.cmdline '3dCM -roi_vals 2 10 structural.nii > cm.txt' >>> res = 3dcm.run() # doctest: +SKIP """ @@ -766,26 +766,26 @@ class Copy(AFNICommand): >>> from nipype.interfaces import afni >>> copy3d = afni.Copy() >>> copy3d.inputs.in_file = 'functional.nii' - >>> copy3d.cmdline # doctest: +ALLOW_UNICODE + >>> copy3d.cmdline '3dcopy functional.nii functional_copy' >>> res = copy3d.run() # doctest: +SKIP >>> from copy import deepcopy >>> copy3d_2 = deepcopy(copy3d) >>> copy3d_2.inputs.outputtype = 'NIFTI' - >>> copy3d_2.cmdline # doctest: +ALLOW_UNICODE + >>> copy3d_2.cmdline '3dcopy functional.nii functional_copy.nii' >>> res = copy3d_2.run() # doctest: +SKIP >>> copy3d_3 = deepcopy(copy3d) >>> copy3d_3.inputs.outputtype = 'NIFTI_GZ' - >>> copy3d_3.cmdline # doctest: +ALLOW_UNICODE + >>> copy3d_3.cmdline '3dcopy functional.nii functional_copy.nii.gz' >>> res = copy3d_3.run() # doctest: +SKIP >>> copy3d_4 = deepcopy(copy3d) >>> copy3d_4.inputs.out_file = 'new_func.nii' - >>> copy3d_4.cmdline # doctest: +ALLOW_UNICODE + >>> copy3d_4.cmdline '3dcopy functional.nii new_func.nii' >>> res = copy3d_4.run() # doctest: +SKIP @@ -857,7 +857,7 @@ class Dot(AFNICommand): >>> dot.inputs.in_files = ['functional.nii[0]', 'structural.nii'] >>> dot.inputs.dodice = True >>> dot.inputs.out_file = 'out.mask_ae_dice.txt' - >>> dot.cmdline # doctest: +ALLOW_UNICODE + >>> dot.cmdline '3dDot -dodice functional.nii[0] structural.nii |& tee out.mask_ae_dice.txt' >>> res = copy3d.run() # doctest: +SKIP @@ -948,7 +948,7 @@ class Edge3(AFNICommand): >>> edge3.inputs.in_file = 'functional.nii' >>> edge3.inputs.out_file = 'edges.nii' >>> edge3.inputs.datum = 'byte' - >>> edge3.cmdline # doctest: +ALLOW_UNICODE + >>> edge3.cmdline '3dedge3 -input functional.nii -datum byte -prefix edges.nii' >>> res = edge3.run() # doctest: +SKIP @@ -1019,7 +1019,7 @@ class Eval(AFNICommand): >>> eval.inputs.expr = 'a*b' >>> eval.inputs.out1D = True >>> eval.inputs.out_file = 'data_calc.1D' - >>> eval.cmdline # doctest: +ALLOW_UNICODE + >>> eval.cmdline '1deval -a seed.1D -b resp.1D -expr "a*b" -1D -prefix data_calc.1D' >>> res = eval.run() # doctest: +SKIP @@ -1170,7 +1170,7 @@ class FWHMx(AFNICommandBase): >>> from nipype.interfaces import afni >>> fwhm = afni.FWHMx() >>> fwhm.inputs.in_file = 'functional.nii' - >>> fwhm.cmdline # doctest: +ALLOW_UNICODE + >>> fwhm.cmdline '3dFWHMx -input functional.nii -out functional_subbricks.out > functional_fwhmx.out' >>> res = fwhm.run() # doctest: +SKIP @@ -1397,7 +1397,7 @@ class MaskTool(AFNICommand): >>> masktool = afni.MaskTool() >>> masktool.inputs.in_file = 'functional.nii' >>> masktool.inputs.outputtype = 'NIFTI' - >>> masktool.cmdline # doctest: +ALLOW_UNICODE + >>> masktool.cmdline '3dmask_tool -prefix functional_mask.nii -input functional.nii' >>> res = automask.run() # doctest: +SKIP @@ -1446,7 +1446,7 @@ class Merge(AFNICommand): >>> merge.inputs.blurfwhm = 4 >>> merge.inputs.doall = True >>> merge.inputs.out_file = 'e7.nii' - >>> merge.cmdline # doctest: +ALLOW_UNICODE + >>> merge.cmdline '3dmerge -1blur_fwhm 4 -doall -prefix e7.nii functional.nii functional2.nii' >>> res = merge.run() # doctest: +SKIP @@ -1501,7 +1501,7 @@ class Notes(CommandLine): >>> notes.inputs.in_file = 'functional.HEAD' >>> notes.inputs.add = 'This note is added.' >>> notes.inputs.add_history = 'This note is added to history.' - >>> notes.cmdline # doctest: +ALLOW_UNICODE + >>> notes.cmdline '3dNotes -a "This note is added." -h "This note is added to history." functional.HEAD' >>> res = notes.run() # doctest: +SKIP """ @@ -1579,7 +1579,7 @@ class NwarpApply(AFNICommandBase): >>> nwarp.inputs.in_file = 'Fred+orig' >>> nwarp.inputs.master = 'NWARP' >>> nwarp.inputs.warp = "'Fred_WARP+tlrc Fred.Xaff12.1D'" - >>> nwarp.cmdline # doctest: +ALLOW_UNICODE + >>> nwarp.cmdline "3dNwarpApply -source Fred+orig -master NWARP -prefix Fred+orig_Nwarp -nwarp \'Fred_WARP+tlrc Fred.Xaff12.1D\'" >>> res = nwarp.run() # doctest: +SKIP @@ -1766,7 +1766,7 @@ class OneDToolPy(AFNIPythonCommand): >>> odt.inputs.set_nruns = 3 >>> odt.inputs.demean = True >>> odt.inputs.out_file = 'motion_dmean.1D' - >>> odt.cmdline # doctest: +ALLOW_UNICODE +ELLIPSIS + >>> odt.cmdline # doctest: +ELLIPSIS 'python2 ...1d_tool.py -demean -infile f1.1D -write motion_dmean.1D -set_nruns 3' >>> res = odt.run() # doctest: +SKIP """ @@ -1821,6 +1821,9 @@ class RefitInputSpec(CommandLineInputSpec): zdel = traits.Float( desc='new z voxel dimension in mm', argstr='-zdel %f') + xyzscale = traits.Float( + desc='Scale the size of the dataset voxels by the given factor', + argstr='-xyzscale %f') space = traits.Enum( 'TLRC', 'MNI', 'ORIG', argstr='-space %s', @@ -1881,14 +1884,14 @@ class Refit(AFNICommandBase): >>> refit = afni.Refit() >>> refit.inputs.in_file = 'structural.nii' >>> refit.inputs.deoblique = True - >>> refit.cmdline # doctest: +ALLOW_UNICODE + >>> refit.cmdline '3drefit -deoblique structural.nii' >>> res = refit.run() # doctest: +SKIP >>> refit_2 = afni.Refit() >>> refit_2.inputs.in_file = 'structural.nii' >>> refit_2.inputs.atrfloat = ("IJK_TO_DICOM_REAL", "'1 0.2 0 0 -0.2 1 0 0 0 0 1 0'") - >>> refit_2.cmdline # doctest: +ALLOW_UNICODE + >>> refit_2.cmdline "3drefit -atrfloat IJK_TO_DICOM_REAL '1 0.2 0 0 -0.2 1 0 0 0 0 1 0' structural.nii" >>> res = refit_2.run() # doctest: +SKIP """ @@ -1948,7 +1951,7 @@ class Resample(AFNICommand): >>> resample.inputs.in_file = 'functional.nii' >>> resample.inputs.orientation= 'RPI' >>> resample.inputs.outputtype = 'NIFTI' - >>> resample.cmdline # doctest: +ALLOW_UNICODE + >>> resample.cmdline '3dresample -orient RPI -prefix functional_resample.nii -inset functional.nii' >>> res = resample.run() # doctest: +SKIP @@ -2001,7 +2004,7 @@ class TCat(AFNICommand): >>> tcat.inputs.in_files = ['functional.nii', 'functional2.nii'] >>> tcat.inputs.out_file= 'functional_tcat.nii' >>> tcat.inputs.rlt = '+' - >>> tcat.cmdline # doctest: +ALLOW_UNICODE +NORMALIZE_WHITESPACE + >>> tcat.cmdline '3dTcat -rlt+ -prefix functional_tcat.nii functional.nii functional2.nii' >>> res = tcat.run() # doctest: +SKIP @@ -2051,7 +2054,7 @@ class TCatSubBrick(AFNICommand): >>> tcsb.inputs.in_files = [('functional.nii', "'{2..$}'"), ('functional2.nii', "'{2..$}'")] >>> tcsb.inputs.out_file= 'functional_tcat.nii' >>> tcsb.inputs.rlt = '+' - >>> tcsb.cmdline # doctest: +ALLOW_UNICODE +NORMALIZE_WHITESPACE + >>> tcsb.cmdline "3dTcat -rlt+ -prefix functional_tcat.nii functional.nii'{2..$}' functional2.nii'{2..$}' " >>> res = tcsb.run() # doctest: +SKIP @@ -2102,7 +2105,7 @@ class TStat(AFNICommand): >>> tstat.inputs.in_file = 'functional.nii' >>> tstat.inputs.args = '-mean' >>> tstat.inputs.out_file = 'stats' - >>> tstat.cmdline # doctest: +ALLOW_UNICODE + >>> tstat.cmdline '3dTstat -mean -prefix stats functional.nii' >>> res = tstat.run() # doctest: +SKIP @@ -2164,7 +2167,7 @@ class To3D(AFNICommand): >>> to3d.inputs.in_folder = '.' >>> to3d.inputs.out_file = 'dicomdir.nii' >>> to3d.inputs.filetype = 'anat' - >>> to3d.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> to3d.cmdline # doctest: +ELLIPSIS 'to3d -datum float -anat -prefix dicomdir.nii ./*.dcm' >>> res = to3d.run() # doctest: +SKIP @@ -2268,7 +2271,7 @@ class Undump(AFNICommand): >>> unndump = afni.Undump() >>> unndump.inputs.in_file = 'structural.nii' >>> unndump.inputs.out_file = 'structural_undumped.nii' - >>> unndump.cmdline # doctest: +ALLOW_UNICODE + >>> unndump.cmdline '3dUndump -prefix structural_undumped.nii -master structural.nii' >>> res = unndump.run() # doctest: +SKIP @@ -2371,7 +2374,7 @@ class Unifize(AFNICommand): >>> unifize = afni.Unifize() >>> unifize.inputs.in_file = 'structural.nii' >>> unifize.inputs.out_file = 'structural_unifized.nii' - >>> unifize.cmdline # doctest: +ALLOW_UNICODE + >>> unifize.cmdline '3dUnifize -prefix structural_unifized.nii -input structural.nii' >>> res = unifize.run() # doctest: +SKIP @@ -2414,7 +2417,7 @@ class ZCutUp(AFNICommand): >>> zcutup.inputs.in_file = 'functional.nii' >>> zcutup.inputs.out_file = 'functional_zcutup.nii' >>> zcutup.inputs.keep= '0 10' - >>> zcutup.cmdline # doctest: +ALLOW_UNICODE + >>> zcutup.cmdline '3dZcutup -keep 0 10 -prefix functional_zcutup.nii functional.nii' >>> res = zcutup.run() # doctest: +SKIP @@ -2466,7 +2469,7 @@ class GCOR(CommandLine): >>> gcor = afni.GCOR() >>> gcor.inputs.in_file = 'structural.nii' >>> gcor.inputs.nfirst = 4 - >>> gcor.cmdline # doctest: +ALLOW_UNICODE + >>> gcor.cmdline '@compute_gcor -nfirst 4 -input structural.nii' >>> res = gcor.run() # doctest: +SKIP @@ -2538,7 +2541,7 @@ class Axialize(AFNICommand): >>> axial3d = afni.Axialize() >>> axial3d.inputs.in_file = 'functional.nii' >>> axial3d.inputs.out_file = 'axialized.nii' - >>> axial3d.cmdline # doctest: +ALLOW_UNICODE + >>> axial3d.cmdline '3daxialize -prefix axialized.nii functional.nii' >>> res = axial3d.run() # doctest: +SKIP @@ -2600,7 +2603,7 @@ class Zcat(AFNICommand): >>> zcat = afni.Zcat() >>> zcat.inputs.in_files = ['functional2.nii', 'functional3.nii'] >>> zcat.inputs.out_file = 'cat_functional.nii' - >>> zcat.cmdline # doctest: +ALLOW_UNICODE + >>> zcat.cmdline '3dZcat -prefix cat_functional.nii functional2.nii functional3.nii' >>> res = zcat.run() # doctest: +SKIP """ @@ -2702,7 +2705,7 @@ class Zeropad(AFNICommand): >>> zeropad.inputs.P = 10 >>> zeropad.inputs.R = 10 >>> zeropad.inputs.L = 10 - >>> zeropad.cmdline # doctest: +ALLOW_UNICODE + >>> zeropad.cmdline '3dZeropad -A 10 -I 10 -L 10 -P 10 -R 10 -S 10 -prefix pad_functional.nii functional.nii' >>> res = zeropad.run() # doctest: +SKIP """ diff --git a/nipype/interfaces/ants/base.py b/nipype/interfaces/ants/base.py index 3ab50a24f5..00553fd977 100644 --- a/nipype/interfaces/ants/base.py +++ b/nipype/interfaces/ants/base.py @@ -6,12 +6,12 @@ from builtins import str import os -import subprocess # Local imports from ... import logging, LooseVersion -from ..base import CommandLine, CommandLineInputSpec, traits, isdefined -logger = logging.getLogger('interface') +from ..base import (CommandLine, CommandLineInputSpec, traits, isdefined, + PackageInfo) +iflogger = logging.getLogger('interface') # -Using -1 gives primary responsibilty to ITKv4 to do the correct # thread limitings. @@ -29,32 +29,21 @@ ALT_ITKv4_THREAD_LIMIT_VARIABLE = 'ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS' -class Info(object): - _version = None +class Info(PackageInfo): + version_cmd = os.path.join(os.getenv('ANTSPATH', ''), + 'antsRegistration') + ' --version' - @property - def version(self): - if self._version is None: - try: - basedir = os.environ['ANTSPATH'] - except KeyError: - return None - - cmd = os.path.join(basedir, 'antsRegistration') - try: - res = subprocess.check_output([cmd, '--version']).decode('utf-8') - except OSError: - return None - - for line in res.splitlines(): - if line.startswith('ANTs Version: '): - self._version = line.split()[2] - break - else: - return None + @staticmethod + def parse_version(raw_info): + for line in raw_info.splitlines(): + if line.startswith('ANTs Version: '): + v_string = line.split()[2] + break + else: + return None # -githash may or may not be appended - v_string = self._version.split('-')[0] + v_string = v_string.split('-')[0] # 2.2.0-equivalent version string if 'post' in v_string and LooseVersion(v_string) >= LooseVersion('2.1.0.post789'): @@ -125,4 +114,4 @@ def set_default_num_threads(cls, num_threads): @property def version(self): - return Info().version + return Info.version() diff --git a/nipype/interfaces/ants/legacy.py b/nipype/interfaces/ants/legacy.py index f545f3ed08..7df1731fa1 100644 --- a/nipype/interfaces/ants/legacy.py +++ b/nipype/interfaces/ants/legacy.py @@ -86,7 +86,7 @@ class antsIntroduction(ANTSCommand): >>> warp.inputs.reference_image = 'Template_6.nii' >>> warp.inputs.input_image = 'structural.nii' >>> warp.inputs.max_iterations = [30,90,20] - >>> warp.cmdline # doctest: +ALLOW_UNICODE + >>> warp.cmdline 'antsIntroduction.sh -d 3 -i structural.nii -m 30x90x20 -o ants_ -r Template_6.nii -t GR' """ @@ -204,7 +204,7 @@ class buildtemplateparallel(ANTSCommand): >>> tmpl = buildtemplateparallel() >>> tmpl.inputs.in_files = ['T1.nii', 'structural.nii'] >>> tmpl.inputs.max_iterations = [30, 90, 20] - >>> tmpl.cmdline # doctest: +ALLOW_UNICODE + >>> tmpl.cmdline 'buildtemplateparallel.sh -d 3 -i 4 -m 30x90x20 -o antsTMPL_ -c 0 -t GR T1.nii structural.nii' """ diff --git a/nipype/interfaces/ants/registration.py b/nipype/interfaces/ants/registration.py index 0b0e8f581e..6d82a2e9f1 100644 --- a/nipype/interfaces/ants/registration.py +++ b/nipype/interfaces/ants/registration.py @@ -119,7 +119,7 @@ class ANTS(ANTSCommand): >>> ants.inputs.regularization_gradient_field_sigma = 3 >>> ants.inputs.regularization_deformation_field_sigma = 0 >>> ants.inputs.number_of_affine_iterations = [10000,10000,10000,10000,10000] - >>> ants.cmdline # doctest: +ALLOW_UNICODE + >>> ants.cmdline 'ANTS 3 --MI-option 32x16000 --image-metric CC[ T1.nii, resting.nii, 1, 5 ] --number-of-affine-iterations \ 10000x10000x10000x10000x10000 --number-of-iterations 50x35x15 --output-naming MY --regularization Gauss[3.0,0.0] \ --transformation-model SyN[0.25] --use-Histogram-Matching 1' @@ -517,7 +517,7 @@ class Registration(ANTSCommand): >>> reg.inputs.use_estimate_learning_rate_once = [True, True] >>> reg.inputs.use_histogram_matching = [True, True] # This is the default >>> reg.inputs.output_warped_image = 'output_warped_image.nii.gz' - >>> reg.cmdline # doctest: +ALLOW_UNICODE + >>> reg.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --initial-moving-transform [ trans.mat, 0 ] \ --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ @@ -533,7 +533,7 @@ class Registration(ANTSCommand): >>> reg.inputs.invert_initial_moving_transform = True >>> reg1 = copy.deepcopy(reg) >>> reg1.inputs.winsorize_lower_quantile = 0.025 - >>> reg1.cmdline # doctest: +ALLOW_UNICODE + >>> reg1.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --initial-moving-transform [ trans.mat, 1 ] \ --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ @@ -549,7 +549,7 @@ class Registration(ANTSCommand): >>> reg2 = copy.deepcopy(reg) >>> reg2.inputs.winsorize_upper_quantile = 0.975 - >>> reg2.cmdline # doctest: +ALLOW_UNICODE + >>> reg2.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --initial-moving-transform [ trans.mat, 1 ] \ --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ @@ -566,7 +566,7 @@ class Registration(ANTSCommand): >>> reg3 = copy.deepcopy(reg) >>> reg3.inputs.winsorize_lower_quantile = 0.025 >>> reg3.inputs.winsorize_upper_quantile = 0.975 - >>> reg3.cmdline # doctest: +ALLOW_UNICODE + >>> reg3.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --initial-moving-transform [ trans.mat, 1 ] \ --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ @@ -580,7 +580,7 @@ class Registration(ANTSCommand): >>> reg3a = copy.deepcopy(reg) >>> reg3a.inputs.float = True - >>> reg3a.cmdline # doctest: +ALLOW_UNICODE + >>> reg3a.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --float 1 \ --initial-moving-transform [ trans.mat, 1 ] --initialize-transforms-per-stage 0 --interpolation Linear \ --output [ output_, output_warped_image.nii.gz ] --transform Affine[ 2.0 ] \ @@ -595,7 +595,7 @@ class Registration(ANTSCommand): >>> reg3b = copy.deepcopy(reg) >>> reg3b.inputs.float = False - >>> reg3b.cmdline # doctest: +ALLOW_UNICODE + >>> reg3b.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --float 0 \ --initial-moving-transform [ trans.mat, 1 ] --initialize-transforms-per-stage 0 --interpolation Linear \ --output [ output_, output_warped_image.nii.gz ] --transform Affine[ 2.0 ] \ @@ -616,7 +616,7 @@ class Registration(ANTSCommand): >>> reg4.inputs.initialize_transforms_per_stage = True >>> reg4.inputs.collapse_output_transforms = True >>> outputs = reg4._list_outputs() - >>> pprint.pprint(outputs) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE +ALLOW_UNICODE + >>> pprint.pprint(outputs) # doctest: +ELLIPSIS, {'composite_transform': '.../nipype/testing/data/output_Composite.h5', 'elapsed_time': , 'forward_invert_flags': [], @@ -628,7 +628,7 @@ class Registration(ANTSCommand): 'reverse_transforms': [], 'save_state': '.../nipype/testing/data/trans.mat', 'warped_image': '.../nipype/testing/data/output_warped_image.nii.gz'} - >>> reg4.cmdline # doctest: +ALLOW_UNICODE + >>> reg4.cmdline 'antsRegistration --collapse-output-transforms 1 --dimensionality 3 --initial-moving-transform [ trans.mat, 1 ] \ --initialize-transforms-per-stage 1 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --restore-state trans.mat --save-state trans.mat --transform Affine[ 2.0 ] \ @@ -644,7 +644,7 @@ class Registration(ANTSCommand): >>> reg4b = copy.deepcopy(reg4) >>> reg4b.inputs.write_composite_transform = False >>> outputs = reg4b._list_outputs() - >>> pprint.pprint(outputs) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE +ALLOW_UNICODE + >>> pprint.pprint(outputs) # doctest: +ELLIPSIS, {'composite_transform': , 'elapsed_time': , 'forward_invert_flags': [False, False], @@ -659,7 +659,7 @@ class Registration(ANTSCommand): 'save_state': '.../nipype/testing/data/trans.mat', 'warped_image': '.../nipype/testing/data/output_warped_image.nii.gz'} >>> reg4b.aggregate_outputs() # doctest: +SKIP - >>> reg4b.cmdline # doctest: +ALLOW_UNICODE + >>> reg4b.cmdline 'antsRegistration --collapse-output-transforms 1 --dimensionality 3 --initial-moving-transform [ trans.mat, 1 ] \ --initialize-transforms-per-stage 1 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --restore-state trans.mat --save-state trans.mat --transform Affine[ 2.0 ] \ @@ -672,7 +672,7 @@ class Registration(ANTSCommand): One can use multiple similarity metrics in a single registration stage.The Node below first performs a linear registation using only the Mutual Information ('Mattes')-metric. - In a second stage, it performs a non-linear registration ('Syn') using both a + In a second stage, it performs a non-linear registration ('Syn') using both a Mutual Information and a local cross-correlation ('CC')-metric. Both metrics are weighted equally ('metric_weight' is .5 for both). The Mutual Information- metric uses 32 bins. The local cross-correlations (correlations between every voxel's neighborhoods) is computed @@ -687,7 +687,7 @@ class Registration(ANTSCommand): >>> reg5.inputs.radius_or_number_of_bins = [32, [32, 4] ] >>> reg5.inputs.sampling_strategy = ['Random', None] # use default strategy in second stage >>> reg5.inputs.sampling_percentage = [0.05, [0.05, 0.10]] - >>> reg5.cmdline # doctest: +ALLOW_UNICODE + >>> reg5.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --initial-moving-transform [ trans.mat, 1 ] \ --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ @@ -708,7 +708,7 @@ class Registration(ANTSCommand): >>> reg6 = copy.deepcopy(reg5) >>> reg6.inputs.fixed_image = ['fixed1.nii', 'fixed2.nii'] >>> reg6.inputs.moving_image = ['moving1.nii', 'moving2.nii'] - >>> reg6.cmdline # doctest: +ALLOW_UNICODE + >>> reg6.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --initial-moving-transform [ trans.mat, 1 ] \ --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ @@ -725,7 +725,7 @@ class Registration(ANTSCommand): >>> reg7a = copy.deepcopy(reg) >>> reg7a.inputs.interpolation = 'BSpline' >>> reg7a.inputs.interpolation_parameters = (3,) - >>> reg7a.cmdline # doctest: +ALLOW_UNICODE + >>> reg7a.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --initial-moving-transform [ trans.mat, 1 ] \ --initialize-transforms-per-stage 0 --interpolation BSpline[ 3 ] --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ @@ -739,7 +739,7 @@ class Registration(ANTSCommand): >>> reg7b = copy.deepcopy(reg) >>> reg7b.inputs.interpolation = 'Gaussian' >>> reg7b.inputs.interpolation_parameters = (1.0, 1.0) - >>> reg7b.cmdline # doctest: +ALLOW_UNICODE + >>> reg7b.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --initial-moving-transform [ trans.mat, 1 ] \ --initialize-transforms-per-stage 0 --interpolation Gaussian[ 1.0, 1.0 ] \ --output [ output_, output_warped_image.nii.gz ] --transform Affine[ 2.0 ] \ @@ -756,7 +756,7 @@ class Registration(ANTSCommand): >>> reg8 = copy.deepcopy(reg) >>> reg8.inputs.transforms = ['Affine', 'BSplineSyN'] >>> reg8.inputs.transform_parameters = [(2.0,), (0.25, 26, 0, 3)] - >>> reg8.cmdline # doctest: +ALLOW_UNICODE + >>> reg8.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --initial-moving-transform [ trans.mat, 1 ] \ --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ @@ -771,7 +771,7 @@ class Registration(ANTSCommand): >>> # Test masking >>> reg9 = copy.deepcopy(reg) >>> reg9.inputs.fixed_image_masks = ['NULL', 'fixed1.nii'] - >>> reg9.cmdline # doctest: +ALLOW_UNICODE + >>> reg9.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --initial-moving-transform [ trans.mat, 1 ] \ --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ @@ -790,7 +790,7 @@ class Registration(ANTSCommand): >>> reg10 = copy.deepcopy(reg) >>> reg10.inputs.initial_moving_transform = ['func_to_struct.mat', 'ants_Warp.nii.gz'] >>> reg10.inputs.invert_initial_moving_transform = [False, False] - >>> reg10.cmdline # doctest: +ALLOW_UNICODE + >>> reg10.cmdline 'antsRegistration --collapse-output-transforms 0 --dimensionality 3 --initial-moving-transform \ [ func_to_struct.mat, 0 ] [ ants_Warp.nii.gz, 0 ] --initialize-transforms-per-stage 0 --interpolation Linear \ --output [ output_, output_warped_image.nii.gz ] --transform Affine[ 2.0 ] \ @@ -1290,7 +1290,7 @@ class MeasureImageSimilarity(ANTSCommand): >>> sim.inputs.sampling_percentage = 1.0 >>> sim.inputs.fixed_image_mask = 'mask.nii' >>> sim.inputs.moving_image_mask = 'mask.nii.gz' - >>> sim.cmdline # doctest: +ALLOW_UNICODE + >>> sim.cmdline u'MeasureImageSimilarity --dimensionality 3 --masks ["mask.nii","mask.nii.gz"] \ --metric MI["T1.nii","resting.nii",1.0,5,Regular,1.0]' """ diff --git a/nipype/interfaces/ants/resampling.py b/nipype/interfaces/ants/resampling.py index 9ee9243a61..e268cb43e2 100644 --- a/nipype/interfaces/ants/resampling.py +++ b/nipype/interfaces/ants/resampling.py @@ -66,7 +66,7 @@ class WarpTimeSeriesImageMultiTransform(ANTSCommand): >>> wtsimt.inputs.input_image = 'resting.nii' >>> wtsimt.inputs.reference_image = 'ants_deformed.nii.gz' >>> wtsimt.inputs.transformation_series = ['ants_Warp.nii.gz','ants_Affine.txt'] - >>> wtsimt.cmdline # doctest: +ALLOW_UNICODE + >>> wtsimt.cmdline 'WarpTimeSeriesImageMultiTransform 4 resting.nii resting_wtsimt.nii -R ants_deformed.nii.gz ants_Warp.nii.gz \ ants_Affine.txt' @@ -179,7 +179,7 @@ class WarpImageMultiTransform(ANTSCommand): >>> wimt.inputs.input_image = 'structural.nii' >>> wimt.inputs.reference_image = 'ants_deformed.nii.gz' >>> wimt.inputs.transformation_series = ['ants_Warp.nii.gz','ants_Affine.txt'] - >>> wimt.cmdline # doctest: +ALLOW_UNICODE + >>> wimt.cmdline 'WarpImageMultiTransform 3 structural.nii structural_wimt.nii -R ants_deformed.nii.gz ants_Warp.nii.gz \ ants_Affine.txt' @@ -189,7 +189,7 @@ class WarpImageMultiTransform(ANTSCommand): >>> wimt.inputs.transformation_series = ['func2anat_coreg_Affine.txt','func2anat_InverseWarp.nii.gz', \ 'dwi2anat_Warp.nii.gz','dwi2anat_coreg_Affine.txt'] >>> wimt.inputs.invert_affine = [1] # this will invert the 1st Affine file: 'func2anat_coreg_Affine.txt' - >>> wimt.cmdline # doctest: +ALLOW_UNICODE + >>> wimt.cmdline 'WarpImageMultiTransform 3 diffusion_weighted.nii diffusion_weighted_wimt.nii -R functional.nii \ -i func2anat_coreg_Affine.txt func2anat_InverseWarp.nii.gz dwi2anat_Warp.nii.gz dwi2anat_coreg_Affine.txt' @@ -305,7 +305,7 @@ class ApplyTransforms(ANTSCommand): >>> at.inputs.input_image = 'moving1.nii' >>> at.inputs.reference_image = 'fixed1.nii' >>> at.inputs.transforms = 'identity' - >>> at.cmdline # doctest: +ALLOW_UNICODE + >>> at.cmdline 'antsApplyTransforms --default-value 0 --input moving1.nii \ --interpolation Linear --output moving1_trans.nii \ --reference-image fixed1.nii -t identity' @@ -319,7 +319,7 @@ class ApplyTransforms(ANTSCommand): >>> at.inputs.default_value = 0 >>> at.inputs.transforms = ['ants_Warp.nii.gz', 'trans.mat'] >>> at.inputs.invert_transform_flags = [False, False] - >>> at.cmdline # doctest: +ALLOW_UNICODE + >>> at.cmdline 'antsApplyTransforms --default-value 0 --dimensionality 3 --input moving1.nii --interpolation Linear \ --output deformed_moving1.nii --reference-image fixed1.nii --transform [ ants_Warp.nii.gz, 0 ] \ --transform [ trans.mat, 0 ]' @@ -334,7 +334,7 @@ class ApplyTransforms(ANTSCommand): >>> at1.inputs.default_value = 0 >>> at1.inputs.transforms = ['ants_Warp.nii.gz', 'trans.mat'] >>> at1.inputs.invert_transform_flags = [False, False] - >>> at1.cmdline # doctest: +ALLOW_UNICODE + >>> at1.cmdline 'antsApplyTransforms --default-value 0 --dimensionality 3 --input moving1.nii --interpolation BSpline[ 5 ] \ --output deformed_moving1.nii --reference-image fixed1.nii --transform [ ants_Warp.nii.gz, 0 ] \ --transform [ trans.mat, 0 ]' @@ -442,7 +442,7 @@ class ApplyTransformsToPoints(ANTSCommand): >>> at.inputs.input_file = 'moving.csv' >>> at.inputs.transforms = ['trans.mat', 'ants_Warp.nii.gz'] >>> at.inputs.invert_transform_flags = [False, False] - >>> at.cmdline # doctest: +ALLOW_UNICODE + >>> at.cmdline 'antsApplyTransformsToPoints --dimensionality 3 --input moving.csv --output moving_transformed.csv \ --transform [ trans.mat, 0 ] --transform [ ants_Warp.nii.gz, 0 ]' diff --git a/nipype/interfaces/ants/segmentation.py b/nipype/interfaces/ants/segmentation.py index 042303227a..64ca7205ca 100644 --- a/nipype/interfaces/ants/segmentation.py +++ b/nipype/interfaces/ants/segmentation.py @@ -91,7 +91,7 @@ class Atropos(ANTSCommand): >>> at.inputs.posterior_formulation = 'Socrates' >>> at.inputs.use_mixture_model_proportions = True >>> at.inputs.save_posteriors = True - >>> at.cmdline # doctest: +ALLOW_UNICODE + >>> at.cmdline 'Atropos --image-dimensionality 3 --icm [1,1] \ --initialization PriorProbabilityImages[2,priors/priorProbImages%02d.nii,0.8,1e-07] --intensity-image structural.nii \ --likelihood-model Gaussian --mask-image mask.nii --mrf [0.2,1x1x1] --convergence [5,1e-06] \ @@ -209,7 +209,7 @@ class LaplacianThickness(ANTSCommand): >>> cort_thick.inputs.input_wm = 'white_matter.nii.gz' >>> cort_thick.inputs.input_gm = 'gray_matter.nii.gz' >>> cort_thick.inputs.output_image = 'output_thickness.nii.gz' - >>> cort_thick.cmdline # doctest: +ALLOW_UNICODE + >>> cort_thick.cmdline 'LaplacianThickness white_matter.nii.gz gray_matter.nii.gz output_thickness.nii.gz' """ @@ -294,7 +294,7 @@ class N4BiasFieldCorrection(ANTSCommand): >>> n4.inputs.bspline_fitting_distance = 300 >>> n4.inputs.shrink_factor = 3 >>> n4.inputs.n_iterations = [50,50,30,20] - >>> n4.cmdline # doctest: +ALLOW_UNICODE + >>> n4.cmdline 'N4BiasFieldCorrection --bspline-fitting [ 300 ] \ -d 3 --input-image structural.nii \ --convergence [ 50x50x30x20 ] --output structural_corrected.nii \ @@ -302,7 +302,7 @@ class N4BiasFieldCorrection(ANTSCommand): >>> n4_2 = copy.deepcopy(n4) >>> n4_2.inputs.convergence_threshold = 1e-6 - >>> n4_2.cmdline # doctest: +ALLOW_UNICODE + >>> n4_2.cmdline 'N4BiasFieldCorrection --bspline-fitting [ 300 ] \ -d 3 --input-image structural.nii \ --convergence [ 50x50x30x20, 1e-06 ] --output structural_corrected.nii \ @@ -310,7 +310,7 @@ class N4BiasFieldCorrection(ANTSCommand): >>> n4_3 = copy.deepcopy(n4_2) >>> n4_3.inputs.bspline_order = 5 - >>> n4_3.cmdline # doctest: +ALLOW_UNICODE + >>> n4_3.cmdline 'N4BiasFieldCorrection --bspline-fitting [ 300, 5 ] \ -d 3 --input-image structural.nii \ --convergence [ 50x50x30x20, 1e-06 ] --output structural_corrected.nii \ @@ -320,7 +320,7 @@ class N4BiasFieldCorrection(ANTSCommand): >>> n4_4.inputs.input_image = 'structural.nii' >>> n4_4.inputs.save_bias = True >>> n4_4.inputs.dimension = 3 - >>> n4_4.cmdline # doctest: +ALLOW_UNICODE + >>> n4_4.cmdline 'N4BiasFieldCorrection -d 3 --input-image structural.nii \ --output [ structural_corrected.nii, structural_bias.nii ]' """ @@ -530,7 +530,7 @@ class CorticalThickness(ANTSCommand): ... 'BrainSegmentationPrior03.nii.gz', ... 'BrainSegmentationPrior04.nii.gz'] >>> corticalthickness.inputs.t1_registration_template = 'brain_study_template.nii.gz' - >>> corticalthickness.cmdline # doctest: +ALLOW_UNICODE + >>> corticalthickness.cmdline 'antsCorticalThickness.sh -a T1.nii.gz -m ProbabilityMaskOfStudyTemplate.nii.gz -e study_template.nii.gz -d 3 \ -s nii.gz -o antsCT_ -p nipype_priors/BrainSegmentationPrior%02d.nii.gz -t brain_study_template.nii.gz' @@ -709,7 +709,7 @@ class BrainExtraction(ANTSCommand): >>> brainextraction.inputs.anatomical_image ='T1.nii.gz' >>> brainextraction.inputs.brain_template = 'study_template.nii.gz' >>> brainextraction.inputs.brain_probability_mask ='ProbabilityMaskOfStudyTemplate.nii.gz' - >>> brainextraction.cmdline # doctest: +ALLOW_UNICODE + >>> brainextraction.cmdline 'antsBrainExtraction.sh -a T1.nii.gz -m ProbabilityMaskOfStudyTemplate.nii.gz -e study_template.nii.gz -d 3 \ -s nii.gz -o highres001_' """ @@ -900,7 +900,7 @@ class JointFusion(ANTSCommand): ... 'segmentation1.nii.gz', ... 'segmentation1.nii.gz'] >>> at.inputs.target_image = 'T1.nii' - >>> at.cmdline # doctest: +ALLOW_UNICODE + >>> at.cmdline 'jointfusion 3 1 -m Joint[0.1,2] -tg T1.nii -g im1.nii -g im2.nii -g im3.nii -l segmentation0.nii.gz \ -l segmentation1.nii.gz -l segmentation1.nii.gz fusion_labelimage_output.nii' @@ -909,7 +909,7 @@ class JointFusion(ANTSCommand): >>> at.inputs.beta = 1 >>> at.inputs.patch_radius = [3,2,1] >>> at.inputs.search_radius = [1,2,3] - >>> at.cmdline # doctest: +ALLOW_UNICODE + >>> at.cmdline 'jointfusion 3 1 -m Joint[0.5,1] -rp 3x2x1 -rs 1x2x3 -tg T1.nii -g im1.nii -g im2.nii -g im3.nii \ -l segmentation0.nii.gz -l segmentation1.nii.gz -l segmentation1.nii.gz fusion_labelimage_output.nii' """ @@ -986,20 +986,20 @@ class DenoiseImage(ANTSCommand): >>> denoise = DenoiseImage() >>> denoise.inputs.dimension = 3 >>> denoise.inputs.input_image = 'im1.nii' - >>> denoise.cmdline # doctest: +ALLOW_UNICODE + >>> denoise.cmdline 'DenoiseImage -d 3 -i im1.nii -n Gaussian -o im1_noise_corrected.nii -s 1' >>> denoise_2 = copy.deepcopy(denoise) >>> denoise_2.inputs.output_image = 'output_corrected_image.nii.gz' >>> denoise_2.inputs.noise_model = 'Rician' >>> denoise_2.inputs.shrink_factor = 2 - >>> denoise_2.cmdline # doctest: +ALLOW_UNICODE + >>> denoise_2.cmdline 'DenoiseImage -d 3 -i im1.nii -n Rician -o output_corrected_image.nii.gz -s 2' >>> denoise_3 = DenoiseImage() >>> denoise_3.inputs.input_image = 'im1.nii' >>> denoise_3.inputs.save_noise = True - >>> denoise_3.cmdline # doctest: +ALLOW_UNICODE + >>> denoise_3.cmdline 'DenoiseImage -i im1.nii -n Gaussian -o [ im1_noise_corrected.nii, im1_noise.nii ] -s 1' """ input_spec = DenoiseImageInputSpec @@ -1103,12 +1103,12 @@ class AntsJointFusion(ANTSCommand): >>> antsjointfusion.inputs.atlas_image = [ ['rc1s1.nii','rc1s2.nii'] ] >>> antsjointfusion.inputs.atlas_segmentation_image = ['segmentation0.nii.gz'] >>> antsjointfusion.inputs.target_image = ['im1.nii'] - >>> antsjointfusion.cmdline # doctest: +ALLOW_UNICODE + >>> antsjointfusion.cmdline "antsJointFusion -a 0.1 -g ['rc1s1.nii', 'rc1s2.nii'] -l segmentation0.nii.gz \ -b 2.0 -o ants_fusion_label_output.nii -s 3x3x3 -t ['im1.nii']" >>> antsjointfusion.inputs.target_image = [ ['im1.nii', 'im2.nii'] ] - >>> antsjointfusion.cmdline # doctest: +ALLOW_UNICODE + >>> antsjointfusion.cmdline "antsJointFusion -a 0.1 -g ['rc1s1.nii', 'rc1s2.nii'] -l segmentation0.nii.gz \ -b 2.0 -o ants_fusion_label_output.nii -s 3x3x3 -t ['im1.nii', 'im2.nii']" @@ -1116,7 +1116,7 @@ class AntsJointFusion(ANTSCommand): ... ['rc2s1.nii','rc2s2.nii'] ] >>> antsjointfusion.inputs.atlas_segmentation_image = ['segmentation0.nii.gz', ... 'segmentation1.nii.gz'] - >>> antsjointfusion.cmdline # doctest: +ALLOW_UNICODE + >>> antsjointfusion.cmdline "antsJointFusion -a 0.1 -g ['rc1s1.nii', 'rc1s2.nii'] -g ['rc2s1.nii', 'rc2s2.nii'] \ -l segmentation0.nii.gz -l segmentation1.nii.gz -b 2.0 -o ants_fusion_label_output.nii \ -s 3x3x3 -t ['im1.nii', 'im2.nii']" @@ -1126,7 +1126,7 @@ class AntsJointFusion(ANTSCommand): >>> antsjointfusion.inputs.beta = 1.0 >>> antsjointfusion.inputs.patch_radius = [3,2,1] >>> antsjointfusion.inputs.search_radius = [3] - >>> antsjointfusion.cmdline # doctest: +ALLOW_UNICODE + >>> antsjointfusion.cmdline "antsJointFusion -a 0.5 -g ['rc1s1.nii', 'rc1s2.nii'] -g ['rc2s1.nii', 'rc2s2.nii'] \ -l segmentation0.nii.gz -l segmentation1.nii.gz -b 1.0 -d 3 -o ants_fusion_label_output.nii \ -p 3x2x1 -s 3 -t ['im1.nii', 'im2.nii']" @@ -1135,7 +1135,7 @@ class AntsJointFusion(ANTSCommand): >>> antsjointfusion.inputs.verbose = True >>> antsjointfusion.inputs.exclusion_image = ['roi01.nii', 'roi02.nii'] >>> antsjointfusion.inputs.exclusion_image_label = ['1','2'] - >>> antsjointfusion.cmdline # doctest: +ALLOW_UNICODE + >>> antsjointfusion.cmdline "antsJointFusion -a 0.5 -g ['rc1s1.nii', 'rc1s2.nii'] -g ['rc2s1.nii', 'rc2s2.nii'] \ -l segmentation0.nii.gz -l segmentation1.nii.gz -b 1.0 -d 3 -e 1[roi01.nii] -e 2[roi02.nii] \ -o ants_fusion_label_output.nii -p 3x2x1 -s mask.nii -t ['im1.nii', 'im2.nii'] -v" @@ -1144,7 +1144,7 @@ class AntsJointFusion(ANTSCommand): >>> antsjointfusion.inputs.out_intensity_fusion_name_format = 'ants_joint_fusion_intensity_%d.nii.gz' >>> antsjointfusion.inputs.out_label_post_prob_name_format = 'ants_joint_fusion_posterior_%d.nii.gz' >>> antsjointfusion.inputs.out_atlas_voting_weight_name_format = 'ants_joint_fusion_voting_weight_%d.nii.gz' - >>> antsjointfusion.cmdline # doctest: +ALLOW_UNICODE + >>> antsjointfusion.cmdline "antsJointFusion -a 0.5 -g ['rc1s1.nii', 'rc1s2.nii'] -g ['rc2s1.nii', 'rc2s2.nii'] \ -l segmentation0.nii.gz -l segmentation1.nii.gz -b 1.0 -d 3 -e 1[roi01.nii] -e 2[roi02.nii] \ -o [ants_fusion_label_output.nii, ants_joint_fusion_intensity_%d.nii.gz, \ @@ -1323,7 +1323,7 @@ class KellyKapowski(ANTSCommand): >>> #kk.inputs.use_bspline_smoothing = False >>> kk.inputs.number_integration_points = 10 >>> kk.inputs.thickness_prior_estimate = 10 - >>> kk.cmdline # doctest: +ALLOW_UNICODE + >>> kk.cmdline u'KellyKapowski --convergence "[45,0.0,10]" \ --output "[segmentation0_cortical_thickness.nii.gz,segmentation0_warped_white_matter.nii.gz]" \ --image-dimensionality 3 --gradient-step 0.025000 --number-of-integration-points 10 \ diff --git a/nipype/interfaces/ants/utils.py b/nipype/interfaces/ants/utils.py index 88d6d219a2..0ba918ee27 100644 --- a/nipype/interfaces/ants/utils.py +++ b/nipype/interfaces/ants/utils.py @@ -37,7 +37,7 @@ class AverageAffineTransform(ANTSCommand): >>> avg.inputs.dimension = 3 >>> avg.inputs.transforms = ['trans.mat', 'func_to_struct.mat'] >>> avg.inputs.output_affine_transform = 'MYtemplatewarp.mat' - >>> avg.cmdline # doctest: +ALLOW_UNICODE + >>> avg.cmdline 'AverageAffineTransform 3 MYtemplatewarp.mat trans.mat func_to_struct.mat' """ _cmd = 'AverageAffineTransform' @@ -83,7 +83,7 @@ class AverageImages(ANTSCommand): >>> avg.inputs.output_average_image = "average.nii.gz" >>> avg.inputs.normalize = True >>> avg.inputs.images = ['rc1s1.nii', 'rc1s1.nii'] - >>> avg.cmdline # doctest: +ALLOW_UNICODE + >>> avg.cmdline 'AverageImages 3 average.nii.gz 1 rc1s1.nii rc1s1.nii' """ _cmd = 'AverageImages' @@ -126,7 +126,7 @@ class MultiplyImages(ANTSCommand): >>> test.inputs.first_input = 'moving2.nii' >>> test.inputs.second_input = 0.25 >>> test.inputs.output_product_image = "out.nii" - >>> test.cmdline # doctest: +ALLOW_UNICODE + >>> test.cmdline 'MultiplyImages 3 moving2.nii 0.25 out.nii' """ _cmd = 'MultiplyImages' @@ -170,7 +170,7 @@ class CreateJacobianDeterminantImage(ANTSCommand): >>> jacobian.inputs.imageDimension = 3 >>> jacobian.inputs.deformationField = 'ants_Warp.nii.gz' >>> jacobian.inputs.outputImage = 'out_name.nii.gz' - >>> jacobian.cmdline # doctest: +ALLOW_UNICODE + >>> jacobian.cmdline 'CreateJacobianDeterminantImage 3 ants_Warp.nii.gz out_name.nii.gz' """ @@ -223,7 +223,7 @@ class AffineInitializer(ANTSCommand): >>> init = AffineInitializer() >>> init.inputs.fixed_image = 'fixed1.nii' >>> init.inputs.moving_image = 'moving1.nii' - >>> init.cmdline # doctest: +ALLOW_UNICODE + >>> init.cmdline 'antsAffineInitializer 3 fixed1.nii moving1.nii transform.mat 15.000000 0.100000 0 10' """ @@ -261,7 +261,7 @@ class ComposeMultiTransform(ANTSCommand): >>> compose_transform = ComposeMultiTransform() >>> compose_transform.inputs.dimension = 3 >>> compose_transform.inputs.transforms = ['struct_to_template.mat', 'func_to_struct.mat'] - >>> compose_transform.cmdline # doctest: +ALLOW_UNICODE + >>> compose_transform.cmdline 'ComposeMultiTransform 3 struct_to_template_composed struct_to_template.mat func_to_struct.mat' """ diff --git a/nipype/interfaces/ants/visualization.py b/nipype/interfaces/ants/visualization.py index ef51914e6c..07cf8af086 100644 --- a/nipype/interfaces/ants/visualization.py +++ b/nipype/interfaces/ants/visualization.py @@ -57,7 +57,7 @@ class ConvertScalarImageToRGB(ANTSCommand): >>> converter.inputs.colormap = 'jet' >>> converter.inputs.minimum_input = 0 >>> converter.inputs.maximum_input = 6 - >>> converter.cmdline # doctest: +ALLOW_UNICODE + >>> converter.cmdline 'ConvertScalarImageToRGB 3 T1.nii.gz rgb.nii.gz none jet none 0 6 0 255' """ _cmd = 'ConvertScalarImageToRGB' @@ -143,7 +143,7 @@ class CreateTiledMosaic(ANTSCommand): >>> mosaic_slicer.inputs.direction = 2 >>> mosaic_slicer.inputs.pad_or_crop = '[ -15x -50 , -15x -30 ,0]' >>> mosaic_slicer.inputs.slices = '[2 ,100 ,160]' - >>> mosaic_slicer.cmdline # doctest: +ALLOW_UNICODE + >>> mosaic_slicer.cmdline 'CreateTiledMosaic -a 0.50 -d 2 -i T1.nii.gz -x mask.nii.gz -o output.png -p [ -15x -50 , -15x -30 ,0] \ -r rgb.nii.gz -s [2 ,100 ,160]' """ diff --git a/nipype/interfaces/base.py b/nipype/interfaces/base.py index 7f586d4923..facafa5fc9 100644 --- a/nipype/interfaces/base.py +++ b/nipype/interfaces/base.py @@ -123,10 +123,10 @@ class Bunch(object): -------- >>> from nipype.interfaces.base import Bunch >>> inputs = Bunch(infile='subj.nii', fwhm=6.0, register_to_mean=True) - >>> inputs # doctest: +ALLOW_UNICODE + >>> inputs Bunch(fwhm=6.0, infile='subj.nii', register_to_mean=True) >>> inputs.register_to_mean = False - >>> inputs # doctest: +ALLOW_UNICODE + >>> inputs Bunch(fwhm=6.0, infile='subj.nii', register_to_mean=False) @@ -1225,6 +1225,14 @@ class SimpleInterface(BaseInterface): Examples -------- + + .. testsetup:: + + >>> tmp = getfixture('tmpdir') + >>> old = tmp.chdir() # changing to a temporary directory + + .. doctest:: + >>> def double(x): ... return 2 * x ... @@ -1246,6 +1254,11 @@ class SimpleInterface(BaseInterface): >>> dbl.inputs.x = 2 >>> dbl.run().outputs.doubled 4.0 + + .. testsetup:: + + >>> os.chdir(old.strpath) + """ def __init__(self, from_file=None, resource_monitor=None, **inputs): super(SimpleInterface, self).__init__( @@ -1509,18 +1522,18 @@ class must be instantiated with a command argument >>> from nipype.interfaces.base import CommandLine >>> cli = CommandLine(command='ls', environ={'DISPLAY': ':1'}) >>> cli.inputs.args = '-al' - >>> cli.cmdline # doctest: +ALLOW_UNICODE + >>> cli.cmdline 'ls -al' # Use get_traitsfree() to check all inputs set - >>> pprint.pprint(cli.inputs.get_traitsfree()) # doctest: +NORMALIZE_WHITESPACE +ALLOW_UNICODE + >>> pprint.pprint(cli.inputs.get_traitsfree()) # doctest: {'args': '-al', 'environ': {'DISPLAY': ':1'}, 'ignore_exception': False} - >>> cli.inputs.get_hashval()[0][0] # doctest: +ALLOW_UNICODE + >>> cli.inputs.get_hashval()[0][0] ('args', '-al') - >>> cli.inputs.get_hashval()[1] # doctest: +ALLOW_UNICODE + >>> cli.inputs.get_hashval()[1] '11c37f97649cd61627f4afe5136af8c0' """ @@ -1850,12 +1863,12 @@ class MpiCommandLine(CommandLine): >>> from nipype.interfaces.base import MpiCommandLine >>> mpi_cli = MpiCommandLine(command='my_mpi_prog') >>> mpi_cli.inputs.args = '-v' - >>> mpi_cli.cmdline # doctest: +ALLOW_UNICODE + >>> mpi_cli.cmdline 'my_mpi_prog -v' >>> mpi_cli.inputs.use_mpi = True >>> mpi_cli.inputs.n_procs = 8 - >>> mpi_cli.cmdline # doctest: +ALLOW_UNICODE + >>> mpi_cli.cmdline 'mpiexec -n 8 my_mpi_prog -v' """ input_spec = MpiCommandLineInputSpec @@ -1911,6 +1924,41 @@ def _format_arg(self, name, spec, value): return super(SEMLikeCommandLine, self)._format_arg(name, spec, value) +class PackageInfo(object): + _version = None + version_cmd = None + version_file = None + + @classmethod + def version(klass): + if klass._version is None: + if klass.version_cmd is not None: + try: + clout = CommandLine(command=klass.version_cmd, + resource_monitor=False, + terminal_output='allatonce').run() + except IOError: + return None + + raw_info = clout.runtime.stdout + elif klass.version_file is not None: + try: + with open(klass.version_file, 'rt') as fobj: + raw_info = fobj.read() + except OSError: + return None + else: + return None + + klass._version = klass.parse_version(raw_info) + + return klass._version + + @staticmethod + def parse_version(raw_info): + raise NotImplementedError + + class MultiPath(traits.List): """ Abstract class - shared functionality of input and output MultiPath """ @@ -1965,15 +2013,15 @@ class OutputMultiPath(MultiPath): >>> a.foo = '/software/temp/foo.txt' - >>> a.foo # doctest: +ALLOW_UNICODE + >>> a.foo '/software/temp/foo.txt' >>> a.foo = ['/software/temp/foo.txt'] - >>> a.foo # doctest: +ALLOW_UNICODE + >>> a.foo '/software/temp/foo.txt' >>> a.foo = ['/software/temp/foo.txt', '/software/temp/goo.txt'] - >>> a.foo # doctest: +ALLOW_UNICODE + >>> a.foo ['/software/temp/foo.txt', '/software/temp/goo.txt'] """ @@ -2010,15 +2058,15 @@ class InputMultiPath(MultiPath): >>> a.foo = '/software/temp/foo.txt' - >>> a.foo # doctest: +ALLOW_UNICODE + >>> a.foo ['/software/temp/foo.txt'] >>> a.foo = ['/software/temp/foo.txt'] - >>> a.foo # doctest: +ALLOW_UNICODE + >>> a.foo ['/software/temp/foo.txt'] >>> a.foo = ['/software/temp/foo.txt', '/software/temp/goo.txt'] - >>> a.foo # doctest: +ALLOW_UNICODE + >>> a.foo ['/software/temp/foo.txt', '/software/temp/goo.txt'] """ diff --git a/nipype/interfaces/bru2nii.py b/nipype/interfaces/bru2nii.py index d469f8bda6..579b5229b9 100644 --- a/nipype/interfaces/bru2nii.py +++ b/nipype/interfaces/bru2nii.py @@ -42,7 +42,7 @@ class Bru2(CommandLine): >>> from nipype.interfaces.bru2nii import Bru2 >>> converter = Bru2() >>> converter.inputs.input_dir = "brukerdir" - >>> converter.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> converter.cmdline # doctest: +ELLIPSIS 'Bru2 -o .../nipype/testing/data/brukerdir brukerdir' """ input_spec = Bru2InputSpec diff --git a/nipype/interfaces/c3.py b/nipype/interfaces/c3.py index 8288ab3b17..334500874c 100644 --- a/nipype/interfaces/c3.py +++ b/nipype/interfaces/c3.py @@ -38,7 +38,7 @@ class C3dAffineTool(SEMLikeCommandLine): >>> c3.inputs.source_file = 'cmatrix.mat' >>> c3.inputs.itk_transform = 'affine.txt' >>> c3.inputs.fsl2ras = True - >>> c3.cmdline # doctest: +ALLOW_UNICODE + >>> c3.cmdline 'c3d_affine_tool -src cmatrix.mat -fsl2ras -oitk affine.txt' """ input_spec = C3dAffineToolInputSpec diff --git a/nipype/interfaces/cmtk/cmtk.py b/nipype/interfaces/cmtk/cmtk.py index 4eeec3e370..2f29bbb2e2 100644 --- a/nipype/interfaces/cmtk/cmtk.py +++ b/nipype/interfaces/cmtk/cmtk.py @@ -120,8 +120,11 @@ def create_allpoints_cmat(streamlines, roiData, voxelSize, n_rois): connectivity_matrix = get_connectivity_matrix(n_rois, list_of_roi_crossed_lists) dis = n_fib - len(final_fiber_ids) - iflogger.info("Found %i (%f percent out of %i fibers) fibers that start or terminate in a voxel which is not labeled. (orphans)" % (dis, dis * 100.0 / n_fib, n_fib)) - iflogger.info("Valid fibers: %i (%f percent)" % (n_fib - dis, 100 - dis * 100.0 / n_fib)) + iflogger.info('Found %i (%f percent out of %i fibers) fibers that start or ' + 'terminate in a voxel which is not labeled. (orphans)', + dis, dis * 100.0 / n_fib, n_fib) + iflogger.info('Valid fibers: %i (%f percent)', n_fib - dis, + 100 - dis * 100.0 / n_fib) iflogger.info('Returning the intersecting point connectivity matrix') return connectivity_matrix, final_fiber_ids @@ -181,7 +184,7 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ en_fname = op.abspath(endpoint_name + '_endpoints.npy') en_fnamemm = op.abspath(endpoint_name + '_endpointsmm.npy') - iflogger.info('Reading Trackvis file {trk}'.format(trk=track_file)) + iflogger.info('Reading Trackvis file %s', track_file) fib, hdr = nb.trackvis.read(track_file, False) stats['orig_n_fib'] = len(fib) @@ -191,13 +194,13 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ (endpoints, endpointsmm) = create_endpoints_array(fib, roiVoxelSize) # Output endpoint arrays - iflogger.info('Saving endpoint array: {array}'.format(array=en_fname)) + iflogger.info('Saving endpoint array: %s', en_fname) np.save(en_fname, endpoints) - iflogger.info('Saving endpoint array in mm: {array}'.format(array=en_fnamemm)) + iflogger.info('Saving endpoint array in mm: %s', en_fnamemm) np.save(en_fnamemm, endpointsmm) n = len(fib) - iflogger.info('Number of fibers {num}'.format(num=n)) + iflogger.info('Number of fibers: %i', n) # Create empty fiber label array fiberlabels = np.zeros((n, 2)) @@ -244,7 +247,8 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ startROI = int(roiData[endpoints[i, 0, 0], endpoints[i, 0, 1], endpoints[i, 0, 2]]) endROI = int(roiData[endpoints[i, 1, 0], endpoints[i, 1, 1], endpoints[i, 1, 2]]) except IndexError: - iflogger.error(("AN INDEXERROR EXCEPTION OCCURED FOR FIBER %s. PLEASE CHECK ENDPOINT GENERATION" % i)) + iflogger.error('AN INDEXERROR EXCEPTION OCCURED FOR FIBER %s. ' + 'PLEASE CHECK ENDPOINT GENERATION', i) break # Filter @@ -256,7 +260,7 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ if startROI > nROIs or endROI > nROIs: iflogger.error("Start or endpoint of fiber terminate in a voxel which is labeled higher") iflogger.error("than is expected by the parcellation node information.") - iflogger.error("Start ROI: %i, End ROI: %i" % (startROI, endROI)) + iflogger.error("Start ROI: %i, End ROI: %i", startROI, endROI) iflogger.error("This needs bugfixing!") continue @@ -296,8 +300,10 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ # make final fiber labels as array final_fiberlabels_array = np.array(final_fiberlabels, dtype=int) - iflogger.info("Found %i (%f percent out of %i fibers) fibers that start or terminate in a voxel which is not labeled. (orphans)" % (dis, dis * 100.0 / n, n)) - iflogger.info("Valid fibers: %i (%f percent)" % (n - dis, 100 - dis * 100.0 / n)) + iflogger.info('Found %i (%f percent out of %i fibers) fibers that start or ' + 'terminate in a voxel which is not labeled. (orphans)', + dis, dis * 100.0 / n, n) + iflogger.info('Valid fibers: %i (%f%%)', n - dis, 100 - dis * 100.0 / n) numfib = nx.Graph() numfib.add_nodes_from(G) @@ -326,7 +332,7 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ fibmedian.add_edge(u, v, weight=di['fiber_length_median']) fibdev.add_edge(u, v, weight=di['fiber_length_std']) - iflogger.info('Writing network as {ntwk}'.format(ntwk=matrix_name)) + iflogger.info('Writing network as %s', matrix_name) nx.write_gpickle(G, op.abspath(matrix_name)) numfib_mlab = nx.to_numpy_matrix(numfib, dtype=int) @@ -341,7 +347,7 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ if intersections: path, name, ext = split_filename(matrix_name) intersection_matrix_name = op.abspath(name + '_intersections') + ext - iflogger.info('Writing intersection network as {ntwk}'.format(ntwk=intersection_matrix_name)) + iflogger.info('Writing intersection network as %s', intersection_matrix_name) nx.write_gpickle(I, intersection_matrix_name) path, name, ext = split_filename(matrix_mat_name) @@ -349,37 +355,41 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ ext = '.mat' matrix_mat_name = matrix_mat_name + ext - iflogger.info('Writing matlab matrix as {mat}'.format(mat=matrix_mat_name)) + iflogger.info('Writing matlab matrix as %s', matrix_mat_name) sio.savemat(matrix_mat_name, numfib_dict) if intersections: intersect_dict = {'intersections': intersection_matrix} intersection_matrix_mat_name = op.abspath(name + '_intersections') + ext - iflogger.info('Writing intersection matrix as {mat}'.format(mat=intersection_matrix_mat_name)) + iflogger.info('Writing intersection matrix as %s', intersection_matrix_mat_name) sio.savemat(intersection_matrix_mat_name, intersect_dict) mean_fiber_length_matrix_name = op.abspath(name + '_mean_fiber_length') + ext - iflogger.info('Writing matlab mean fiber length matrix as {mat}'.format(mat=mean_fiber_length_matrix_name)) + iflogger.info('Writing matlab mean fiber length matrix as %s', + mean_fiber_length_matrix_name) sio.savemat(mean_fiber_length_matrix_name, fibmean_dict) median_fiber_length_matrix_name = op.abspath(name + '_median_fiber_length') + ext - iflogger.info('Writing matlab median fiber length matrix as {mat}'.format(mat=median_fiber_length_matrix_name)) + iflogger.info('Writing matlab median fiber length matrix as %s', + median_fiber_length_matrix_name) sio.savemat(median_fiber_length_matrix_name, fibmedian_dict) fiber_length_std_matrix_name = op.abspath(name + '_fiber_length_std') + ext - iflogger.info('Writing matlab fiber length deviation matrix as {mat}'.format(mat=fiber_length_std_matrix_name)) + iflogger.info('Writing matlab fiber length deviation matrix as %s', + fiber_length_std_matrix_name) sio.savemat(fiber_length_std_matrix_name, fibdev_dict) fiberlengths_fname = op.abspath(endpoint_name + '_final_fiberslength.npy') - iflogger.info("Storing final fiber length array as %s" % fiberlengths_fname) + iflogger.info('Storing final fiber length array as %s', fiberlengths_fname) np.save(fiberlengths_fname, final_fiberlength_array) fiberlabels_fname = op.abspath(endpoint_name + '_filtered_fiberslabel.npy') - iflogger.info("Storing all fiber labels (with orphans) as %s" % fiberlabels_fname) + iflogger.info('Storing all fiber labels (with orphans) as %s', fiberlabels_fname) np.save(fiberlabels_fname, np.array(fiberlabels, dtype=np.int32),) fiberlabels_noorphans_fname = op.abspath(endpoint_name + '_final_fiberslabels.npy') - iflogger.info("Storing final fiber labels (no orphans) as %s" % fiberlabels_noorphans_fname) + iflogger.info('Storing final fiber labels (no orphans) as %s', + fiberlabels_noorphans_fname) np.save(fiberlabels_noorphans_fname, final_fiberlabels_array) iflogger.info("Filtering tractography - keeping only no orphan fibers") @@ -389,7 +399,7 @@ def cmat(track_file, roi_file, resolution_network_file, matrix_name, matrix_mat_ stats['intersections_percent'] = float(stats['intersections_n_fib']) / float(stats['orig_n_fib']) * 100 out_stats_file = op.abspath(endpoint_name + '_statistics.mat') - iflogger.info("Saving matrix creation statistics as %s" % out_stats_file) + iflogger.info('Saving matrix creation statistics as %s', out_stats_file) sio.savemat(out_stats_file, stats) @@ -401,7 +411,7 @@ def save_fibers(oldhdr, oldfib, fname, indices): outstreams.append(oldfib[i]) n_fib_out = len(outstreams) hdrnew['n_count'] = n_fib_out - iflogger.info("Writing final non-orphan fibers as %s" % fname) + iflogger.info('Writing final non-orphan fibers as %s', fname) nb.trackvis.write(fname, outstreams, hdrnew) return n_fib_out @@ -620,22 +630,22 @@ class ROIGen(BaseInterface): def _run_interface(self, runtime): aparc_aseg_file = self.inputs.aparc_aseg_file aparcpath, aparcname, aparcext = split_filename(aparc_aseg_file) - iflogger.info('Using Aparc+Aseg file: {name}'.format(name=aparcname + aparcext)) + iflogger.info('Using Aparc+Aseg file: %s', aparcname + aparcext) niiAPARCimg = nb.load(aparc_aseg_file, mmap=NUMPY_MMAP) niiAPARCdata = niiAPARCimg.get_data() niiDataLabels = np.unique(niiAPARCdata) numDataLabels = np.size(niiDataLabels) - iflogger.info('Number of labels in image: {n}'.format(n=numDataLabels)) + iflogger.info('Number of labels in image: %s', numDataLabels) write_dict = True if self.inputs.use_freesurfer_LUT: self.LUT_file = self.inputs.freesurfer_dir + '/FreeSurferColorLUT.txt' - iflogger.info('Using Freesurfer LUT: {name}'.format(name=self.LUT_file)) + iflogger.info('Using Freesurfer LUT: %s', self.LUT_file) prefix = 'fsLUT' elif not self.inputs.use_freesurfer_LUT and isdefined(self.inputs.LUT_file): self.LUT_file = op.abspath(self.inputs.LUT_file) lutpath, lutname, lutext = split_filename(self.LUT_file) - iflogger.info('Using Custom LUT file: {name}'.format(name=lutname + lutext)) + iflogger.info('Using Custom LUT file: %s', lutname + lutext) prefix = lutname else: prefix = 'hardcoded' @@ -652,14 +662,14 @@ def _run_interface(self, runtime): dict_file = op.abspath(prefix + '_' + aparcname + '.pck') if write_dict: - iflogger.info('Lookup table: {name}'.format(name=op.abspath(self.LUT_file))) + iflogger.info('Lookup table: %s', op.abspath(self.LUT_file)) LUTlabelsRGBA = np.loadtxt(self.LUT_file, skiprows=4, usecols=[0, 1, 2, 3, 4, 5], comments='#', dtype={'names': ('index', 'label', 'R', 'G', 'B', 'A'), 'formats': ('int', '|S30', 'int', 'int', 'int', 'int')}) numLUTLabels = np.size(LUTlabelsRGBA) if numLUTLabels < numDataLabels: iflogger.error('LUT file provided does not contain all of the regions in the image') iflogger.error('Removing unmapped regions') - iflogger.info('Number of labels in LUT: {n}'.format(n=numLUTLabels)) + iflogger.info('Number of labels in LUT: %s', numLUTLabels) LUTlabelDict = {} """ Create dictionary for input LUT table""" @@ -687,7 +697,7 @@ def _run_interface(self, runtime): iflogger.info('Grey matter mask created') greyMaskLabels = np.unique(niiGM) numGMLabels = np.size(greyMaskLabels) - iflogger.info('Number of grey matter labels: {num}'.format(num=numGMLabels)) + iflogger.info('Number of grey matter labels: %s', numGMLabels) labelDict = {} GMlabelDict = {} @@ -697,7 +707,7 @@ def _run_interface(self, runtime): if write_dict: GMlabelDict['originalID'] = mapDict[label] except: - iflogger.info('Label {lbl} not in provided mapping'.format(lbl=label)) + iflogger.info('Label %s not in provided mapping', label) if write_dict: del GMlabelDict GMlabelDict = {} @@ -708,11 +718,11 @@ def _run_interface(self, runtime): roi_image = nb.Nifti1Image(niiGM, niiAPARCimg.affine, niiAPARCimg.header) - iflogger.info('Saving ROI File to {path}'.format(path=roi_file)) + iflogger.info('Saving ROI File to %s', roi_file) nb.save(roi_image, roi_file) if write_dict: - iflogger.info('Saving Dictionary File to {path} in Pickle format'.format(path=dict_file)) + iflogger.info('Saving Dictionary File to %s in Pickle format', dict_file) with open(dict_file, 'w') as f: pickle.dump(labelDict, f) return runtime @@ -785,7 +795,7 @@ class CreateNodes(BaseInterface): def _run_interface(self, runtime): iflogger.info('Creating nodes...') create_nodes(self.inputs.roi_file, self.inputs.resolution_network_file, self.inputs.out_filename) - iflogger.info('Saving node network to {path}'.format(path=op.abspath(self.inputs.out_filename))) + iflogger.info('Saving node network to %s', op.abspath(self.inputs.out_filename)) return runtime def _list_outputs(self): diff --git a/nipype/interfaces/cmtk/nbs.py b/nipype/interfaces/cmtk/nbs.py index fde691f3c5..7410227565 100644 --- a/nipype/interfaces/cmtk/nbs.py +++ b/nipype/interfaces/cmtk/nbs.py @@ -118,7 +118,8 @@ def _run_interface(self, runtime): node_ntwk_name = self.inputs.in_group1[0] node_network = nx.read_gpickle(node_ntwk_name) - iflogger.info('Populating node dictionaries with attributes from {node}'.format(node=node_ntwk_name)) + iflogger.info('Populating node dictionaries with attributes from %s', + node_ntwk_name) for nid, ndata in node_network.nodes(data=True): nbsgraph.nodes[nid] = ndata @@ -127,12 +128,12 @@ def _run_interface(self, runtime): path = op.abspath('NBS_Result_' + details) iflogger.info(path) nx.write_gpickle(nbsgraph, path) - iflogger.info('Saving output NBS edge network as {out}'.format(out=path)) + iflogger.info('Saving output NBS edge network as %s', path) pval_path = op.abspath('NBS_P_vals_' + details) iflogger.info(pval_path) nx.write_gpickle(nbs_pval_graph, pval_path) - iflogger.info('Saving output p-value network as {out}'.format(out=pval_path)) + iflogger.info('Saving output p-value network as %s', pval_path) return runtime def _list_outputs(self): diff --git a/nipype/interfaces/cmtk/nx.py b/nipype/interfaces/cmtk/nx.py index c2f6d7c361..ec3c01336c 100644 --- a/nipype/interfaces/cmtk/nx.py +++ b/nipype/interfaces/cmtk/nx.py @@ -38,7 +38,7 @@ def read_unknown_ntwk(ntwk): if not isinstance(ntwk, nx.classes.graph.Graph): - path, name, ext = split_filename(ntwk) + _, _, ext = split_filename(ntwk) if ext == '.pck': ntwk = nx.read_gpickle(ntwk) elif ext == '.graphml': @@ -104,27 +104,24 @@ def average_networks(in_files, ntwk_res_file, group_id): """ import networkx as nx import os.path as op - iflogger.info(("Creating average network for group: " - "{grp}").format(grp=group_id)) + iflogger.info('Creating average network for group: %s', group_id) matlab_network_list = [] if len(in_files) == 1: avg_ntwk = read_unknown_ntwk(in_files[0]) else: count_to_keep_edge = np.round(len(in_files) / 2.0) - iflogger.info(("Number of networks: {L}, an edge must occur in at " - "least {c} to remain in the " - "average network").format(L=len(in_files), - c=count_to_keep_edge)) + iflogger.info('Number of networks: %i, an edge must occur in at ' + 'least %i to remain in the average network', + len(in_files), count_to_keep_edge) ntwk_res_file = read_unknown_ntwk(ntwk_res_file) - iflogger.info(("{n} Nodes found in network resolution " - "file").format(n=ntwk_res_file.number_of_nodes())) + iflogger.info('%i nodes found in network resolution file', + ntwk_res_file.number_of_nodes()) ntwk = remove_all_edges(ntwk_res_file) counting_ntwk = ntwk.copy() # Sums all the relevant variables for index, subject in enumerate(in_files): tmp = nx.read_gpickle(subject) - iflogger.info(('File {s} has {n} ' - 'edges').format(s=subject, n=tmp.number_of_edges())) + iflogger.info('File %s has %i edges', subject, tmp.number_of_edges()) edges = list(tmp.edges()) for edge in edges: data = {} @@ -146,8 +143,7 @@ def average_networks(in_files, ntwk_res_file, group_id): # Divides each value by the number of files nodes = list(ntwk.nodes()) edges = list(ntwk.edges()) - iflogger.info(('Total network has {n} ' - 'edges').format(n=ntwk.number_of_edges())) + iflogger.info('Total network has %i edges', ntwk.number_of_edges()) avg_ntwk = nx.Graph() newdata = {} for node in nodes: @@ -171,7 +167,8 @@ def average_networks(in_files, ntwk_res_file, group_id): avg_ntwk.add_edge(edge[0], edge[1], **data) edge_dict['count'][edge[0] - 1][edge[1] - 1] = ntwk.edge[edge[0]][edge[1]]['count'] - iflogger.info('After thresholding, the average network has has {n} edges'.format(n=avg_ntwk.number_of_edges())) + iflogger.info('After thresholding, the average network has %i edges', + avg_ntwk.number_of_edges()) avg_edges = avg_ntwk.edges() for edge in avg_edges: @@ -187,16 +184,17 @@ def average_networks(in_files, ntwk_res_file, group_id): matlab_network_list.append(op.abspath(network_name)) tmp[key] = edge_dict[key] sio.savemat(op.abspath(network_name), tmp) - iflogger.info('Saving average network for key: {k} as {out}'.format(k=key, out=op.abspath(network_name))) + iflogger.info('Saving average network for key: %s as %s', key, + op.abspath(network_name)) # Writes the networks and returns the name network_name = group_id + '_average.pck' nx.write_gpickle(avg_ntwk, op.abspath(network_name)) - iflogger.info('Saving average network as {out}'.format(out=op.abspath(network_name))) + iflogger.info('Saving average network as %s', op.abspath(network_name)) avg_ntwk = fix_keys_for_gexf(avg_ntwk) network_name = group_id + '_average.gexf' nx.write_gexf(avg_ntwk, op.abspath(network_name)) - iflogger.info('Saving average network as {out}'.format(out=op.abspath(network_name))) + iflogger.info('Saving average network as %s', op.abspath(network_name)) return network_name, matlab_network_list @@ -453,12 +451,12 @@ def _run_interface(self, runtime): out_pickled_extra_measures = op.abspath(self._gen_outfilename(self.inputs.out_pickled_extra_measures, 'pck')) dict_measures = compute_dict_measures(ntwk) - iflogger.info('Saving extra measure file to {path} in Pickle format'.format(path=op.abspath(out_pickled_extra_measures))) - file = open(out_pickled_extra_measures, 'w') - pickle.dump(dict_measures, file) - file.close() + iflogger.info('Saving extra measure file to %s in Pickle format', + op.abspath(out_pickled_extra_measures)) + with open(out_pickled_extra_measures, 'w') as fo: + pickle.dump(dict_measures, fo) - iflogger.info('Saving MATLAB measures as {m}'.format(m=matlab)) + iflogger.info('Saving MATLAB measures as %s', matlab) # Loops through the measures which return a dictionary, # converts the keys and values to a Numpy array, diff --git a/nipype/interfaces/cmtk/parcellation.py b/nipype/interfaces/cmtk/parcellation.py index 7a2340cb4d..22214c0036 100644 --- a/nipype/interfaces/cmtk/parcellation.py +++ b/nipype/interfaces/cmtk/parcellation.py @@ -223,22 +223,22 @@ def create_roi(subject_id, subjects_dir, fs_dir, parcellation_name, dilation): hemi = 'rh' if brv['dn_region'] == 'subcortical': iflogger.info(brv) - iflogger.info("---------------------") - iflogger.info("Work on brain region: %s" % (brv['dn_region'])) - iflogger.info("Freesurfer Name: %s" % brv['dn_fsname']) - iflogger.info("Region %s of %s " % (count, pg.number_of_nodes())) - iflogger.info("---------------------") + iflogger.info('---------------------') + iflogger.info('Work on brain region: %s', brv['dn_region']) + iflogger.info('Freesurfer Name: %s', brv['dn_fsname']) + iflogger.info('Region %s of %s', count, pg.number_of_nodes()) + iflogger.info('---------------------') # if it is subcortical, retrieve roi from aseg idx = np.where(asegd == int(brv['dn_fs_aseg_val'])) rois[idx] = int(brv['dn_correspondence_id']) elif brv['dn_region'] == 'cortical': iflogger.info(brv) - iflogger.info("---------------------") - iflogger.info("Work on brain region: %s" % (brv['dn_region'])) - iflogger.info("Freesurfer Name: %s" % brv['dn_fsname']) - iflogger.info("Region %s of %s " % (count, pg.number_of_nodes())) - iflogger.info("---------------------") + iflogger.info('---------------------') + iflogger.info('Work on brain region: %s', brv['dn_region']) + iflogger.info('Freesurfer Name: %s', brv['dn_fsname']) + iflogger.info('Region %s of %s', count, pg.number_of_nodes()) + iflogger.info('---------------------') labelpath = op.join( output_dir, parval['fs_label_subdir_name'] % hemi) @@ -294,7 +294,7 @@ def create_roi(subject_id, subjects_dir, fs_dir, parcellation_name, dilation): # store volume eg in ROIv_scale33.nii.gz out_roi = op.abspath('ROIv_%s.nii.gz' % parcellation_name) - iflogger.info("Save output image to %s" % out_roi) + iflogger.info('Save output image to %s', out_roi) img = nb.Nifti1Image(rois, aseg.affine, hdr2) nb.save(img, out_roi) @@ -424,22 +424,23 @@ def create_wm_mask(subject_id, subjects_dir, fs_dir, parcellation_name): wmmask[idx] = 1 # check if we should subtract the cortical rois from this parcellation - iflogger.info("Loading %s to subtract cortical ROIs from white matter mask" % ('ROI_%s.nii.gz' % parcellation_name)) + iflogger.info('Loading ROI_%s.nii.gz to subtract cortical ROIs from white ' + 'matter mask', parcellation_name) roi = nb.load(op.join(op.curdir, 'ROI_%s.nii.gz' % parcellation_name)) roid = roi.get_data() assert roid.shape[0] == wmmask.shape[0] pg = nx.read_graphml(pgpath) for brk, brv in pg.nodes(data=True): if brv['dn_region'] == 'cortical': - iflogger.info("Subtracting region %s with intensity value %s" % - (brv['dn_region'], brv['dn_correspondence_id'])) + iflogger.info('Subtracting region %s with intensity value %s', + brv['dn_region'], brv['dn_correspondence_id']) idx = np.where(roid == int(brv['dn_correspondence_id'])) wmmask[idx] = 0 # output white matter mask. crop and move it afterwards wm_out = op.join(fs_dir, 'mri', 'fsmask_1mm.nii.gz') img = nb.Nifti1Image(wmmask, fsmask.affine, fsmask.header) - iflogger.info("Save white matter mask: %s" % wm_out) + iflogger.info('Save white matter mask: %s', wm_out) nb.save(img, wm_out) @@ -450,7 +451,7 @@ def crop_and_move_datasets(subject_id, subjects_dir, fs_dir, parcellation_name, log = cmp_config.get_logger() output_dir = op.abspath(op.curdir) - iflogger.info("Cropping and moving datasets to %s" % output_dir) + iflogger.info('Cropping and moving datasets to %s', output_dir) ds = [ (op.join(fs_dir, 'mri', 'aseg.nii.gz'), op.abspath('aseg.nii.gz')), @@ -469,7 +470,7 @@ def crop_and_move_datasets(subject_id, subjects_dir, fs_dir, parcellation_name, op.abspath('ROIv_HR_th.nii.gz'))) orig = op.join(fs_dir, 'mri', 'orig', '001.mgz') for d in ds: - iflogger.info("Processing %s:" % d[0]) + iflogger.info('Processing %s:', d[0]) if not op.exists(d[0]): raise Exception('File %s does not exist.' % d[0]) # reslice to original volume because the roi creation with freesurfer diff --git a/nipype/interfaces/cmtk/tests/test_nbs.py b/nipype/interfaces/cmtk/tests/test_nbs.py index cc4b064fc1..0516390b02 100644 --- a/nipype/interfaces/cmtk/tests/test_nbs.py +++ b/nipype/interfaces/cmtk/tests/test_nbs.py @@ -18,7 +18,7 @@ def creating_graphs(tmpdir): for idx, name in enumerate(graphnames): graph = np.random.rand(10,10) G = nx.from_numpy_matrix(graph) - out_file = str(tmpdir) + graphnames[idx] + '.pck' + out_file = tmpdir.strpath + graphnames[idx] + '.pck' # Save as pck file nx.write_gpickle(G, out_file) graphlist.append(out_file) @@ -26,7 +26,8 @@ def creating_graphs(tmpdir): @pytest.mark.skipif(have_cv, reason="tests for import error, cviewer available") -def test_importerror(creating_graphs): +def test_importerror(creating_graphs, tmpdir): + tmpdir.chdir() graphlist = creating_graphs group1 = graphlist[:3] group2 = graphlist[3:] diff --git a/nipype/interfaces/dcm2nii.py b/nipype/interfaces/dcm2nii.py index 8379834b81..22e9375609 100644 --- a/nipype/interfaces/dcm2nii.py +++ b/nipype/interfaces/dcm2nii.py @@ -70,13 +70,25 @@ class Dcm2nii(CommandLine): Examples ======== + .. testsetup:: + + >>> tmp = getfixture('tmpdir') + >>> old = tmp.chdir() # changing to a temporary directory + + .. doctest:: + >>> from nipype.interfaces.dcm2nii import Dcm2nii >>> converter = Dcm2nii() - >>> converter.inputs.source_names = ['functional_1.dcm', 'functional_2.dcm'] + >>> converter.inputs.source_names = [os.path.join(datadir, 'functional_1.dcm'), os.path.join(datadir, 'functional_2.dcm')] >>> converter.inputs.gzip_output = True >>> converter.inputs.output_dir = '.' - >>> converter.cmdline # doctest: +ALLOW_UNICODE - 'dcm2nii -a y -c y -b config.ini -v y -d y -e y -g y -i n -n y -o . -p y -x n -f n functional_1.dcm' + >>> converter.cmdline #doctest: +ELLIPSIS + 'dcm2nii -a y -c y -b config.ini -v y -d y -e y -g y -i n -n y -o . -p y -x n -f n ...functional_1.dcm' + + .. testsetup:: + + >>> os.chdir(old.strpath) + """ input_spec = Dcm2niiInputSpec @@ -250,7 +262,7 @@ class Dcm2niix(CommandLine): 'dcm2niix -b y -z i -x n -t n -m n -f %t%p -o . -s y -v n functional_1.dcm' >>> flags = '-'.join([val.strip() + ' ' for val in sorted(' '.join(converter.cmdline.split()[1:-1]).split('-'))]) - >>> flags # doctest: +ALLOW_UNICODE + >>> flags ' -b y -f %t%p -m n -o . -s y -t n -v n -x n -z i ' """ diff --git a/nipype/interfaces/dipy/anisotropic_power.py b/nipype/interfaces/dipy/anisotropic_power.py index f1d41ab118..2a678dfd1f 100644 --- a/nipype/interfaces/dipy/anisotropic_power.py +++ b/nipype/interfaces/dipy/anisotropic_power.py @@ -67,7 +67,7 @@ def _run_interface(self, runtime): apm = shm.anisotropic_power(peaks.shm_coeff) out_file = self._gen_filename('apm') nb.Nifti1Image(apm.astype("float32"), affine).to_filename(out_file) - IFLOGGER.info('APM qball image saved as {i}'.format(i=out_file)) + IFLOGGER.info('APM qball image saved as %s', out_file) return runtime diff --git a/nipype/interfaces/dipy/preprocess.py b/nipype/interfaces/dipy/preprocess.py index 19b76b800b..bfe197cae2 100644 --- a/nipype/interfaces/dipy/preprocess.py +++ b/nipype/interfaces/dipy/preprocess.py @@ -68,7 +68,7 @@ def _run_interface(self, runtime): resample_proxy(self.inputs.in_file, order=order, new_zooms=vox_size, out_file=out_file) - IFLOGGER.info('Resliced image saved as {i}'.format(i=out_file)) + IFLOGGER.info('Resliced image saved as %s', out_file) return runtime def _list_outputs(self): @@ -159,8 +159,8 @@ def _run_interface(self, runtime): smask=signal_mask, nmask=noise_mask, out_file=out_file) - IFLOGGER.info(('Denoised image saved as {i}, estimated ' - 'SNR={s}').format(i=out_file, s=str(s))) + IFLOGGER.info('Denoised image saved as %s, estimated SNR=%s', + out_file, str(s)) return runtime def _list_outputs(self): diff --git a/nipype/interfaces/dipy/reconstruction.py b/nipype/interfaces/dipy/reconstruction.py index ee3fffce9a..d10e51dede 100644 --- a/nipype/interfaces/dipy/reconstruction.py +++ b/nipype/interfaces/dipy/reconstruction.py @@ -123,13 +123,12 @@ def _run_interface(self, runtime): sigma = mean_std * (1 + bias) if sigma == 0: - IFLOGGER.warn( - ('Noise std is 0.0, looks like data was masked and noise' - ' cannot be estimated correctly. Using default tensor ' - 'model instead of RESTORE.')) + IFLOGGER.warn('Noise std is 0.0, looks like data was masked and noise ' + 'cannot be estimated correctly. Using default tensor ' + 'model instead of RESTORE.') dti = TensorModel(gtab) else: - IFLOGGER.info(('Performing RESTORE with noise std=%.4f.') % sigma) + IFLOGGER.info('Performing RESTORE with noise std=%.4f.', sigma) dti = TensorModel(gtab, fit_method='RESTORE', sigma=sigma) try: @@ -252,14 +251,13 @@ def _run_interface(self, runtime): ratio = abs(response[1] / response[0]) if ratio > 0.25: - IFLOGGER.warn(('Estimated response is not prolate enough. ' - 'Ratio=%0.3f.') % ratio) + IFLOGGER.warn('Estimated response is not prolate enough. ' + 'Ratio=%0.3f.', ratio) elif ratio < 1.e-5 or np.any(np.isnan(response)): response = np.array([1.8e-3, 3.6e-4, 3.6e-4, S0]) - IFLOGGER.warn( - ('Estimated response is not valid, using a default one')) + IFLOGGER.warn('Estimated response is not valid, using a default one') else: - IFLOGGER.info(('Estimated response: %s') % str(response[:3])) + IFLOGGER.info('Estimated response: %s', str(response[:3])) np.savetxt(op.abspath(self.inputs.response), response) @@ -343,8 +341,8 @@ def _run_interface(self, runtime): ratio = response[0][1] / response[0][0] if abs(ratio - 0.2) > 0.1: - IFLOGGER.warn(('Estimated response is not prolate enough. ' - 'Ratio=%0.3f.') % ratio) + IFLOGGER.warn('Estimated response is not prolate enough. ' + 'Ratio=%0.3f.', ratio) csd_model = ConstrainedSphericalDeconvModel( gtab, response, sh_order=self.inputs.sh_order) diff --git a/nipype/interfaces/dipy/simulate.py b/nipype/interfaces/dipy/simulate.py index 0331171811..f008948c97 100644 --- a/nipype/interfaces/dipy/simulate.py +++ b/nipype/interfaces/dipy/simulate.py @@ -10,6 +10,7 @@ import os.path as op from builtins import range +import numpy as np import nibabel as nb from ... import logging @@ -227,8 +228,8 @@ def _run_interface(self, runtime): pool = Pool(processes=n_proc) # Simulate sticks using dipy - IFLOGGER.info(('Starting simulation of %d voxels, %d diffusion' - ' directions.') % (len(args), ndirs)) + IFLOGGER.info('Starting simulation of %d voxels, %d diffusion directions.', + len(args), ndirs) result = np.array(pool.map(_compute_voxel, args)) if np.shape(result)[1] != ndirs: raise RuntimeError(('Computed directions do not match number' @@ -288,7 +289,6 @@ def _compute_voxel(args): angles=args['sticks'], fractions=ffs, snr=snr) except Exception as e: pass - # IFLOGGER.warn('Exception simulating dwi signal: %s' % e) return signal.tolist() diff --git a/nipype/interfaces/dipy/tensors.py b/nipype/interfaces/dipy/tensors.py index 7d9ab3867f..e5518f4ea0 100644 --- a/nipype/interfaces/dipy/tensors.py +++ b/nipype/interfaces/dipy/tensors.py @@ -65,14 +65,14 @@ def _run_interface(self, runtime): img = nifti1_symmat(lower_triangular, affine) out_file = self._gen_filename('dti') nb.save(img, out_file) - IFLOGGER.info('DTI parameters image saved as {i}'.format(i=out_file)) + IFLOGGER.info('DTI parameters image saved as %s', out_file) #FA MD RD and AD for metric in ["fa", "md", "rd", "ad"]: data = getattr(ten_fit,metric).astype("float32") out_name = self._gen_filename(metric) nb.Nifti1Image(data, affine).to_filename(out_name) - IFLOGGER.info('DTI {metric} image saved as {i}'.format(i=out_name, metric=metric)) + IFLOGGER.info('DTI %s image saved as %s', metric, out_name) return runtime @@ -147,7 +147,7 @@ def _run_interface(self, runtime): img = nb.Nifti1Image(mode_data, affine) out_file = self._gen_filename('mode') nb.save(img, out_file) - IFLOGGER.info('Tensor mode image saved as {i}'.format(i=out_file)) + IFLOGGER.info('Tensor mode image saved as %s', out_file) return runtime def _list_outputs(self): diff --git a/nipype/interfaces/dipy/tracks.py b/nipype/interfaces/dipy/tracks.py index 4a74b36b53..bd52fe937e 100644 --- a/nipype/interfaces/dipy/tracks.py +++ b/nipype/interfaces/dipy/tracks.py @@ -71,9 +71,8 @@ def _run_interface(self, runtime): data_dims = refnii.shape[:3] kwargs = dict(affine=affine) else: - IFLOGGER.warn( - 'voxel_dims and data_dims are deprecated as of dipy 0.7.1. Please use reference ' - 'input instead') + IFLOGGER.warn('voxel_dims and data_dims are deprecated as of dipy ' + '0.7.1. Please use reference input instead') if not isdefined(self.inputs.data_dims): data_dims = header['dim'] @@ -93,9 +92,8 @@ def _run_interface(self, runtime): out_file = op.abspath(self.inputs.out_filename) nb.save(img, out_file) - IFLOGGER.info( - 'Track density map saved as %s, size=%s, dimensions=%s', - out_file, img.shape, img.header.get_zooms()) + IFLOGGER.info('Track density map saved as %s, size=%s, dimensions=%s', + out_file, img.shape, img.header.get_zooms()) return runtime @@ -238,12 +236,12 @@ def _run_interface(self, runtime): seedps = np.array(np.where(seedmsk == 1), dtype=np.float32).T vseeds = seedps.shape[0] nsperv = (seeds // vseeds) + 1 - IFLOGGER.info(('Seed mask is provided (%d voxels inside ' - 'mask), computing seeds (%d seeds/voxel).') % - (vseeds, nsperv)) + IFLOGGER.info('Seed mask is provided (%d voxels inside ' + 'mask), computing seeds (%d seeds/voxel).', + vseeds, nsperv) if nsperv > 1: - IFLOGGER.info(('Needed %d seeds per selected voxel ' - '(total %d).') % (nsperv, vseeds)) + IFLOGGER.info('Needed %d seeds per selected voxel (total %d).', + nsperv, vseeds) seedps = np.vstack(np.array([seedps] * nsperv)) voxcoord = seedps + np.random.uniform(-1, 1, size=seedps.shape) nseeds = voxcoord.shape[0] diff --git a/nipype/interfaces/elastix/base.py b/nipype/interfaces/elastix/base.py index afdb0a1ff4..746e571f3f 100644 --- a/nipype/interfaces/elastix/base.py +++ b/nipype/interfaces/elastix/base.py @@ -14,7 +14,7 @@ from ... import logging from ..base import CommandLineInputSpec, Directory, traits -logger = logging.getLogger('interface') +iflogger = logging.getLogger('interface') class ElastixBaseInputSpec(CommandLineInputSpec): diff --git a/nipype/interfaces/elastix/registration.py b/nipype/interfaces/elastix/registration.py index 205346ed80..5038447465 100644 --- a/nipype/interfaces/elastix/registration.py +++ b/nipype/interfaces/elastix/registration.py @@ -18,7 +18,7 @@ from .base import ElastixBaseInputSpec from ..base import CommandLine, TraitedSpec, File, traits, InputMultiPath -logger = logging.getLogger('interface') +iflogger = logging.getLogger('interface') class RegistrationInputSpec(ElastixBaseInputSpec): @@ -55,7 +55,7 @@ class Registration(CommandLine): >>> reg.inputs.fixed_image = 'fixed1.nii' >>> reg.inputs.moving_image = 'moving1.nii' >>> reg.inputs.parameters = ['elastix.txt'] - >>> reg.cmdline # doctest: +ALLOW_UNICODE + >>> reg.cmdline 'elastix -f fixed1.nii -m moving1.nii -out ./ -p elastix.txt' @@ -147,7 +147,7 @@ class ApplyWarp(CommandLine): >>> reg = ApplyWarp() >>> reg.inputs.moving_image = 'moving1.nii' >>> reg.inputs.transform_file = 'TransformParameters.0.txt' - >>> reg.cmdline # doctest: +ALLOW_UNICODE + >>> reg.cmdline 'transformix -in moving1.nii -out ./ -tp TransformParameters.0.txt' @@ -187,7 +187,7 @@ class AnalyzeWarp(CommandLine): >>> from nipype.interfaces.elastix import AnalyzeWarp >>> reg = AnalyzeWarp() >>> reg.inputs.transform_file = 'TransformParameters.0.txt' - >>> reg.cmdline # doctest: +ALLOW_UNICODE + >>> reg.cmdline 'transformix -def all -jac all -jacmat all -out ./ -tp TransformParameters.0.txt' @@ -228,7 +228,7 @@ class PointsWarp(CommandLine): >>> reg = PointsWarp() >>> reg.inputs.points_file = 'surf1.vtk' >>> reg.inputs.transform_file = 'TransformParameters.0.txt' - >>> reg.cmdline # doctest: +ALLOW_UNICODE + >>> reg.cmdline 'transformix -out ./ -def surf1.vtk -tp TransformParameters.0.txt' diff --git a/nipype/interfaces/elastix/utils.py b/nipype/interfaces/elastix/utils.py index 42fab68377..718f5310fd 100644 --- a/nipype/interfaces/elastix/utils.py +++ b/nipype/interfaces/elastix/utils.py @@ -16,7 +16,7 @@ from ... import logging from ..base import (BaseInterface, BaseInterfaceInputSpec, isdefined, TraitedSpec, File, traits) -logger = logging.getLogger('interface') +iflogger = logging.getLogger('interface') class EditTransformInputSpec(BaseInterfaceInputSpec): diff --git a/nipype/interfaces/freesurfer/base.py b/nipype/interfaces/freesurfer/base.py index 4d87cdf9e7..56a4d5df77 100644 --- a/nipype/interfaces/freesurfer/base.py +++ b/nipype/interfaces/freesurfer/base.py @@ -23,12 +23,13 @@ from ...utils.filemanip import fname_presuffix from ..base import (CommandLine, Directory, CommandLineInputSpec, isdefined, - traits, TraitedSpec, File) + traits, TraitedSpec, File, + PackageInfo) __docformat__ = 'restructuredtext' -class Info(object): +class Info(PackageInfo): """ Freesurfer subject directory and version information. Examples @@ -39,32 +40,13 @@ class Info(object): >>> Info.subjectsdir() # doctest: +SKIP """ + if os.getenv('FREESURFER_HOME'): + version_file = os.path.join(os.getenv('FREESURFER_HOME'), + 'build-stamp.txt') @staticmethod - def version(): - """Check for freesurfer version on system - - Find which freesurfer is being used....and get version from - /path/to/freesurfer/build-stamp.txt - - Returns - ------- - - version : string - version number as string - or None if freesurfer version not found - - """ - fs_home = os.getenv('FREESURFER_HOME') - if fs_home is None: - return None - versionfile = os.path.join(fs_home, 'build-stamp.txt') - if not os.path.exists(versionfile): - return None - fid = open(versionfile, 'rt') - version = fid.readline() - fid.close() - return version + def parse_version(raw_info): + return raw_info.splitlines()[0] @classmethod def looseversion(cls): diff --git a/nipype/interfaces/freesurfer/longitudinal.py b/nipype/interfaces/freesurfer/longitudinal.py index 1292109060..84559c90d9 100644 --- a/nipype/interfaces/freesurfer/longitudinal.py +++ b/nipype/interfaces/freesurfer/longitudinal.py @@ -98,22 +98,22 @@ class RobustTemplate(FSCommandOpenMP): >>> template.inputs.fixed_timepoint = True >>> template.inputs.no_iteration = True >>> template.inputs.subsample_threshold = 200 - >>> template.cmdline #doctest: +NORMALIZE_WHITESPACE +ALLOW_UNICODE + >>> template.cmdline #doctest: 'mri_robust_template --satit --average 0 --fixtp --mov structural.nii functional.nii --inittp 1 --noit --template mri_robust_template_out.mgz --subsample 200' >>> template.inputs.out_file = 'T1.nii' - >>> template.cmdline #doctest: +NORMALIZE_WHITESPACE +ALLOW_UNICODE + >>> template.cmdline #doctest: 'mri_robust_template --satit --average 0 --fixtp --mov structural.nii functional.nii --inittp 1 --noit --template T1.nii --subsample 200' >>> template.inputs.transform_outputs = ['structural.lta', ... 'functional.lta'] >>> template.inputs.scaled_intensity_outputs = ['structural-iscale.txt', ... 'functional-iscale.txt'] - >>> template.cmdline #doctest: +NORMALIZE_WHITESPACE +ALLOW_UNICODE +ELLIPSIS + >>> template.cmdline #doctest: +ELLIPSIS 'mri_robust_template --satit --average 0 --fixtp --mov structural.nii functional.nii --inittp 1 --noit --template T1.nii --iscaleout .../structural-iscale.txt .../functional-iscale.txt --subsample 200 --lta .../structural.lta .../functional.lta' >>> template.inputs.transform_outputs = True >>> template.inputs.scaled_intensity_outputs = True - >>> template.cmdline #doctest: +NORMALIZE_WHITESPACE +ALLOW_UNICODE +ELLIPSIS + >>> template.cmdline #doctest: +ELLIPSIS 'mri_robust_template --satit --average 0 --fixtp --mov structural.nii functional.nii --inittp 1 --noit --template T1.nii --iscaleout .../is1.txt .../is2.txt --subsample 200 --lta .../tp1.lta .../tp2.lta' >>> template.run() #doctest: +SKIP @@ -199,7 +199,7 @@ class FuseSegmentations(FSCommand): >>> fuse.inputs.in_segmentations = ['aseg.mgz', 'aseg.mgz'] >>> fuse.inputs.in_segmentations_noCC = ['aseg.mgz', 'aseg.mgz'] >>> fuse.inputs.in_norms = ['norm.mgz', 'norm.mgz', 'norm.mgz'] - >>> fuse.cmdline # doctest: +ALLOW_UNICODE + >>> fuse.cmdline 'mri_fuse_segmentations -n norm.mgz -a aseg.mgz -c aseg.mgz tp.long.A.template tp1 tp2' """ diff --git a/nipype/interfaces/freesurfer/model.py b/nipype/interfaces/freesurfer/model.py index 007d30ac3c..e2eba23196 100644 --- a/nipype/interfaces/freesurfer/model.py +++ b/nipype/interfaces/freesurfer/model.py @@ -91,7 +91,7 @@ class MRISPreproc(FSCommand): >>> preproc.inputs.vol_measure_file = [('cont1.nii', 'register.dat'), \ ('cont1a.nii', 'register.dat')] >>> preproc.inputs.out_file = 'concatenated_file.mgz' - >>> preproc.cmdline # doctest: +ALLOW_UNICODE + >>> preproc.cmdline 'mris_preproc --hemi lh --out concatenated_file.mgz --target fsaverage --iv cont1.nii register.dat --iv cont1a.nii register.dat' """ @@ -148,7 +148,7 @@ class MRISPreprocReconAll(MRISPreproc): >>> preproc.inputs.vol_measure_file = [('cont1.nii', 'register.dat'), \ ('cont1a.nii', 'register.dat')] >>> preproc.inputs.out_file = 'concatenated_file.mgz' - >>> preproc.cmdline # doctest: +ALLOW_UNICODE + >>> preproc.cmdline 'mris_preproc --hemi lh --out concatenated_file.mgz --s subject_id --target fsaverage --iv cont1.nii register.dat --iv cont1a.nii register.dat' """ @@ -486,7 +486,7 @@ class Binarize(FSCommand): -------- >>> binvol = Binarize(in_file='structural.nii', min=10, binary_file='foo_out.nii') - >>> binvol.cmdline # doctest: +ALLOW_UNICODE + >>> binvol.cmdline 'mri_binarize --o foo_out.nii --i structural.nii --min 10.000000' """ @@ -595,7 +595,7 @@ class Concatenate(FSCommand): >>> concat = Concatenate() >>> concat.inputs.in_files = ['cont1.nii', 'cont2.nii'] >>> concat.inputs.concatenated_file = 'bar.nii' - >>> concat.cmdline # doctest: +ALLOW_UNICODE + >>> concat.cmdline 'mri_concat --o bar.nii --i cont1.nii --i cont2.nii' """ @@ -719,7 +719,7 @@ class SegStats(FSCommand): >>> ss.inputs.subjects_dir = '.' >>> ss.inputs.avgwf_txt_file = 'avgwf.txt' >>> ss.inputs.summary_file = 'summary.stats' - >>> ss.cmdline # doctest: +ALLOW_UNICODE + >>> ss.cmdline 'mri_segstats --annot PWS04 lh aparc --avgwf ./avgwf.txt --i functional.nii --sum ./summary.stats' """ @@ -841,7 +841,7 @@ class SegStatsReconAll(SegStats): >>> segstatsreconall.inputs.total_gray = True >>> segstatsreconall.inputs.euler = True >>> segstatsreconall.inputs.exclude_id = 0 - >>> segstatsreconall.cmdline # doctest: +ALLOW_UNICODE + >>> segstatsreconall.cmdline 'mri_segstats --annot PWS04 lh aparc --avgwf ./avgwf.txt --brain-vol-from-seg --surf-ctx-vol --empty --etiv --euler --excl-ctxgmwm --excludeid 0 --subcortgray --subject 10335 --supratent --totalgray --surf-wm-vol --sum ./summary.stats' """ input_spec = SegStatsReconAllInputSpec @@ -953,7 +953,7 @@ class Label2Vol(FSCommand): -------- >>> binvol = Label2Vol(label_file='cortex.label', template_file='structural.nii', reg_file='register.dat', fill_thresh=0.5, vol_label_file='foo_out.nii') - >>> binvol.cmdline # doctest: +ALLOW_UNICODE + >>> binvol.cmdline 'mri_label2vol --fillthresh 0 --label cortex.label --reg register.dat --temp structural.nii --o foo_out.nii' """ @@ -1032,7 +1032,7 @@ class MS_LDA(FSCommand): shift=zero_value, vol_synth_file='synth_out.mgz', \ conform=True, use_weights=True, \ images=['FLASH1.mgz', 'FLASH2.mgz', 'FLASH3.mgz']) - >>> optimalWeights.cmdline # doctest: +ALLOW_UNICODE + >>> optimalWeights.cmdline 'mri_ms_LDA -conform -label label.mgz -lda 2 3 -shift 1 -W -synth synth_out.mgz -weight weights.txt FLASH1.mgz FLASH2.mgz FLASH3.mgz' """ @@ -1124,7 +1124,7 @@ class Label2Label(FSCommand): >>> l2l.inputs.source_label = 'lh-pial.stl' >>> l2l.inputs.source_white = 'lh.pial' >>> l2l.inputs.source_sphere_reg = 'lh.pial' - >>> l2l.cmdline # doctest: +ALLOW_UNICODE + >>> l2l.cmdline 'mri_label2label --hemi lh --trglabel lh-pial_converted.stl --regmethod surface --srclabel lh-pial.stl --srcsubject fsaverage --trgsubject 10335' """ @@ -1208,7 +1208,7 @@ class Label2Annot(FSCommand): >>> l2a.inputs.in_labels = ['lh.aparc.label'] >>> l2a.inputs.orig = 'lh.pial' >>> l2a.inputs.out_annot = 'test' - >>> l2a.cmdline # doctest: +ALLOW_UNICODE + >>> l2a.cmdline 'mris_label2annot --hemi lh --l lh.aparc.label --a test --s 10335' """ @@ -1289,7 +1289,7 @@ class SphericalAverage(FSCommand): >>> sphericalavg.inputs.subject_id = '10335' >>> sphericalavg.inputs.erode = 2 >>> sphericalavg.inputs.threshold = 5 - >>> sphericalavg.cmdline # doctest: +ALLOW_UNICODE + >>> sphericalavg.cmdline 'mris_spherical_average -erode 2 -o 10335 -t 5.0 label lh.entorhinal lh pial . test.out' """ diff --git a/nipype/interfaces/freesurfer/preprocess.py b/nipype/interfaces/freesurfer/preprocess.py index 5f39f1cc94..2f8b432bb3 100644 --- a/nipype/interfaces/freesurfer/preprocess.py +++ b/nipype/interfaces/freesurfer/preprocess.py @@ -67,7 +67,7 @@ class ParseDICOMDir(FSCommand): >>> dcminfo.inputs.dicom_dir = '.' >>> dcminfo.inputs.sortbyrun = True >>> dcminfo.inputs.summarize = True - >>> dcminfo.cmdline # doctest: +ALLOW_UNICODE + >>> dcminfo.cmdline 'mri_parse_sdcmdir --d . --o dicominfo.txt --sortbyrun --summarize' """ @@ -131,7 +131,7 @@ class UnpackSDICOMDir(FSCommand): >>> unpack.inputs.output_dir = '.' >>> unpack.inputs.run_info = (5, 'mprage', 'nii', 'struct') >>> unpack.inputs.dir_structure = 'generic' - >>> unpack.cmdline # doctest: +ALLOW_UNICODE + >>> unpack.cmdline 'unpacksdcmdir -generic -targ . -run 5 mprage nii struct -src .' """ _cmd = 'unpacksdcmdir' @@ -353,7 +353,7 @@ class MRIConvert(FSCommand): >>> mc.inputs.in_file = 'structural.nii' >>> mc.inputs.out_file = 'outfile.mgz' >>> mc.inputs.out_type = 'mgz' - >>> mc.cmdline # doctest: +ALLOW_UNICODE + >>> mc.cmdline 'mri_convert --out_type mgz --input_volume structural.nii --output_volume outfile.mgz' """ @@ -579,7 +579,7 @@ class Resample(FSCommand): >>> resampler.inputs.in_file = 'structural.nii' >>> resampler.inputs.resampled_file = 'resampled.nii' >>> resampler.inputs.voxel_size = (2.1, 2.1, 2.1) - >>> resampler.cmdline # doctest: +ALLOW_UNICODE + >>> resampler.cmdline 'mri_convert -vs 2.10 2.10 2.10 -i structural.nii -o resampled.nii' """ @@ -709,27 +709,27 @@ class ReconAll(CommandLine): >>> reconall.inputs.directive = 'all' >>> reconall.inputs.subjects_dir = '.' >>> reconall.inputs.T1_files = 'structural.nii' - >>> reconall.cmdline # doctest: +ALLOW_UNICODE + >>> reconall.cmdline 'recon-all -all -i structural.nii -subjid foo -sd .' >>> reconall.inputs.flags = "-qcache" - >>> reconall.cmdline # doctest: +ALLOW_UNICODE + >>> reconall.cmdline 'recon-all -all -i structural.nii -qcache -subjid foo -sd .' >>> reconall.inputs.flags = ["-cw256", "-qcache"] - >>> reconall.cmdline # doctest: +ALLOW_UNICODE + >>> reconall.cmdline 'recon-all -all -i structural.nii -cw256 -qcache -subjid foo -sd .' Hemisphere may be specified regardless of directive: >>> reconall.inputs.flags = [] >>> reconall.inputs.hemi = 'lh' - >>> reconall.cmdline # doctest: +ALLOW_UNICODE + >>> reconall.cmdline 'recon-all -all -i structural.nii -hemi lh -subjid foo -sd .' ``-autorecon-hemi`` uses the ``-hemi`` input to specify the hemisphere to operate upon: >>> reconall.inputs.directive = 'autorecon-hemi' - >>> reconall.cmdline # doctest: +ALLOW_UNICODE + >>> reconall.cmdline 'recon-all -autorecon-hemi lh -i structural.nii -subjid foo -sd .' Hippocampal subfields can accept T1 and T2 images: @@ -740,14 +740,14 @@ class ReconAll(CommandLine): >>> reconall_subfields.inputs.subjects_dir = '.' >>> reconall_subfields.inputs.T1_files = 'structural.nii' >>> reconall_subfields.inputs.hippocampal_subfields_T1 = True - >>> reconall_subfields.cmdline # doctest: +ALLOW_UNICODE + >>> reconall_subfields.cmdline 'recon-all -all -i structural.nii -hippocampal-subfields-T1 -subjid foo -sd .' >>> reconall_subfields.inputs.hippocampal_subfields_T2 = ( ... 'structural.nii', 'test') - >>> reconall_subfields.cmdline # doctest: +ALLOW_UNICODE + >>> reconall_subfields.cmdline 'recon-all -all -i structural.nii -hippocampal-subfields-T1T2 structural.nii test -subjid foo -sd .' >>> reconall_subfields.inputs.hippocampal_subfields_T1 = False - >>> reconall_subfields.cmdline # doctest: +ALLOW_UNICODE + >>> reconall_subfields.cmdline 'recon-all -all -i structural.nii -hippocampal-subfields-T2 structural.nii test -subjid foo -sd .' """ @@ -1079,7 +1079,7 @@ def cmdline(self): return "echo recon-all: nothing to do" cmd += ' ' + ' '.join(flags) - iflogger.info('resume recon-all : %s' % cmd) + iflogger.info('resume recon-all : %s', cmd) return cmd def _prep_expert_file(self): @@ -1193,7 +1193,7 @@ class BBRegister(FSCommand): >>> from nipype.interfaces.freesurfer import BBRegister >>> bbreg = BBRegister(subject_id='me', source_file='structural.nii', init='header', contrast_type='t2') - >>> bbreg.cmdline # doctest: +ALLOW_UNICODE + >>> bbreg.cmdline 'bbregister --t2 --init-header --reg structural_bbreg_me.dat --mov structural.nii --s me' """ @@ -1351,7 +1351,7 @@ class ApplyVolTransform(FSCommand): >>> applyreg.inputs.reg_file = 'register.dat' >>> applyreg.inputs.transformed_file = 'struct_warped.nii' >>> applyreg.inputs.fs_target = True - >>> applyreg.cmdline # doctest: +ALLOW_UNICODE + >>> applyreg.cmdline 'mri_vol2vol --fstarg --reg register.dat --mov structural.nii --o struct_warped.nii' """ @@ -1431,7 +1431,7 @@ class Smooth(FSCommand): >>> from nipype.interfaces.freesurfer import Smooth >>> smoothvol = Smooth(in_file='functional.nii', smoothed_file = 'foo_out.nii', reg_file='register.dat', surface_fwhm=10, vol_fwhm=6) - >>> smoothvol.cmdline # doctest: +ALLOW_UNICODE + >>> smoothvol.cmdline 'mris_volsmooth --i functional.nii --reg register.dat --o foo_out.nii --fwhm 10.000000 --vol-fwhm 6.000000' """ @@ -1562,7 +1562,7 @@ class RobustRegister(FSCommand): >>> reg.inputs.target_file = 'T1.nii' >>> reg.inputs.auto_sens = True >>> reg.inputs.init_orient = True - >>> reg.cmdline # doctest: +ALLOW_UNICODE +ELLIPSIS + >>> reg.cmdline # doctest: +ELLIPSIS 'mri_robust_register --satit --initorient --lta .../structural_robustreg.lta --mov structural.nii --dst T1.nii' References @@ -1639,7 +1639,7 @@ class FitMSParams(FSCommand): >>> msfit = FitMSParams() >>> msfit.inputs.in_files = ['flash_05.mgz', 'flash_30.mgz'] >>> msfit.inputs.out_dir = 'flash_parameters' - >>> msfit.cmdline # doctest: +ALLOW_UNICODE + >>> msfit.cmdline 'mri_ms_fitparms flash_05.mgz flash_30.mgz flash_parameters' """ @@ -1712,7 +1712,7 @@ class SynthesizeFLASH(FSCommand): >>> syn.inputs.t1_image = 'T1.mgz' >>> syn.inputs.pd_image = 'PD.mgz' >>> syn.inputs.out_file = 'flash_30syn.mgz' - >>> syn.cmdline # doctest: +ALLOW_UNICODE + >>> syn.cmdline 'mri_synthesize 20.00 30.00 3.000 T1.mgz PD.mgz flash_30syn.mgz' """ @@ -1785,7 +1785,7 @@ class MNIBiasCorrection(FSCommand): >>> correct.inputs.iterations = 6 >>> correct.inputs.protocol_iterations = 1000 >>> correct.inputs.distance = 50 - >>> correct.cmdline # doctest: +ALLOW_UNICODE + >>> correct.cmdline 'mri_nu_correct.mni --distance 50 --i norm.mgz --n 6 --o norm_output.mgz --proto-iters 1000' References: @@ -1842,7 +1842,7 @@ class WatershedSkullStrip(FSCommand): >>> skullstrip.inputs.t1 = True >>> skullstrip.inputs.transform = "transforms/talairach_with_skull.lta" >>> skullstrip.inputs.out_file = "brainmask.auto.mgz" - >>> skullstrip.cmdline # doctest: +ALLOW_UNICODE + >>> skullstrip.cmdline 'mri_watershed -T1 transforms/talairach_with_skull.lta T1.mgz brainmask.auto.mgz' """ _cmd = 'mri_watershed' @@ -1890,7 +1890,7 @@ class Normalize(FSCommand): >>> normalize = freesurfer.Normalize() >>> normalize.inputs.in_file = "T1.mgz" >>> normalize.inputs.gradient = 1 - >>> normalize.cmdline # doctest: +ALLOW_UNICODE + >>> normalize.cmdline 'mri_normalize -g 1 T1.mgz T1_norm.mgz' """ _cmd = "mri_normalize" @@ -1942,7 +1942,7 @@ class CANormalize(FSCommand): >>> ca_normalize.inputs.in_file = "T1.mgz" >>> ca_normalize.inputs.atlas = "atlas.nii.gz" # in practice use .gca atlases >>> ca_normalize.inputs.transform = "trans.mat" # in practice use .lta transforms - >>> ca_normalize.cmdline # doctest: +ALLOW_UNICODE + >>> ca_normalize.cmdline 'mri_ca_normalize T1.mgz atlas.nii.gz trans.mat T1_norm.mgz' """ _cmd = "mri_ca_normalize" @@ -2000,7 +2000,7 @@ class CARegister(FSCommandOpenMP): >>> ca_register = freesurfer.CARegister() >>> ca_register.inputs.in_file = "norm.mgz" >>> ca_register.inputs.out_file = "talairach.m3z" - >>> ca_register.cmdline # doctest: +ALLOW_UNICODE + >>> ca_register.cmdline 'mri_ca_register norm.mgz talairach.m3z' """ _cmd = "mri_ca_register" @@ -2071,7 +2071,7 @@ class CALabel(FSCommandOpenMP): >>> ca_label.inputs.out_file = "out.mgz" >>> ca_label.inputs.transform = "trans.mat" >>> ca_label.inputs.template = "Template_6.nii" # in practice use .gcs extension - >>> ca_label.cmdline # doctest: +ALLOW_UNICODE + >>> ca_label.cmdline 'mri_ca_label norm.mgz trans.mat Template_6.nii out.mgz' """ _cmd = "mri_ca_label" @@ -2145,7 +2145,7 @@ class MRIsCALabel(FSCommandOpenMP): >>> ca_label.inputs.sulc = "lh.pial" >>> ca_label.inputs.classifier = "im1.nii" # in pracice, use .gcs extension >>> ca_label.inputs.smoothwm = "lh.pial" - >>> ca_label.cmdline # doctest: +ALLOW_UNICODE + >>> ca_label.cmdline 'mris_ca_label test lh lh.pial im1.nii lh.aparc.annot' """ _cmd = "mris_ca_label" @@ -2231,7 +2231,7 @@ class SegmentCC(FSCommand): >>> SegmentCC_node.inputs.in_norm = "norm.mgz" >>> SegmentCC_node.inputs.out_rotation = "cc.lta" >>> SegmentCC_node.inputs.subject_id = "test" - >>> SegmentCC_node.cmdline # doctest: +ALLOW_UNICODE + >>> SegmentCC_node.cmdline 'mri_cc -aseg aseg.mgz -o aseg.auto.mgz -lta cc.lta test' """ @@ -2322,7 +2322,7 @@ class SegmentWM(FSCommand): >>> SegmentWM_node = freesurfer.SegmentWM() >>> SegmentWM_node.inputs.in_file = "norm.mgz" >>> SegmentWM_node.inputs.out_file = "wm.seg.mgz" - >>> SegmentWM_node.cmdline # doctest: +ALLOW_UNICODE + >>> SegmentWM_node.cmdline 'mri_segment norm.mgz wm.seg.mgz' """ @@ -2366,7 +2366,7 @@ class EditWMwithAseg(FSCommand): >>> editwm.inputs.seg_file = "aseg.mgz" >>> editwm.inputs.out_file = "wm.asegedit.mgz" >>> editwm.inputs.keep_in = True - >>> editwm.cmdline # doctest: +ALLOW_UNICODE + >>> editwm.cmdline 'mri_edit_wm_with_aseg -keep-in T1.mgz norm.mgz aseg.mgz wm.asegedit.mgz' """ _cmd = 'mri_edit_wm_with_aseg' @@ -2433,7 +2433,7 @@ class ConcatenateLTA(FSCommand): >>> conc_lta = ConcatenateLTA() >>> conc_lta.inputs.in_lta1 = 'lta1.lta' >>> conc_lta.inputs.in_lta2 = 'lta2.lta' - >>> conc_lta.cmdline # doctest: +ALLOW_UNICODE + >>> conc_lta.cmdline 'mri_concatenate_lta lta1.lta lta2.lta lta1_concat.lta' You can use 'identity.nofile' as the filename for in_lta2, e.g.: @@ -2441,13 +2441,13 @@ class ConcatenateLTA(FSCommand): >>> conc_lta.inputs.in_lta2 = 'identity.nofile' >>> conc_lta.inputs.invert_1 = True >>> conc_lta.inputs.out_file = 'inv1.lta' - >>> conc_lta.cmdline # doctest: +ALLOW_UNICODE + >>> conc_lta.cmdline 'mri_concatenate_lta -invert1 lta1.lta identity.nofile inv1.lta' To create a RAS2RAS transform: >>> conc_lta.inputs.out_type = 'RAS2RAS' - >>> conc_lta.cmdline # doctest: +ALLOW_UNICODE + >>> conc_lta.cmdline 'mri_concatenate_lta -invert1 -out_type 1 lta1.lta identity.nofile inv1.lta' """ diff --git a/nipype/interfaces/freesurfer/registration.py b/nipype/interfaces/freesurfer/registration.py index 72a3fdb0ee..60a10b4c11 100644 --- a/nipype/interfaces/freesurfer/registration.py +++ b/nipype/interfaces/freesurfer/registration.py @@ -204,7 +204,7 @@ class EMRegister(FSCommandOpenMP): >>> register.inputs.out_file = 'norm_transform.lta' >>> register.inputs.skull = True >>> register.inputs.nbrspacing = 9 - >>> register.cmdline # doctest: +ALLOW_UNICODE + >>> register.cmdline 'mri_em_register -uns 9 -skull norm.mgz aseg.mgz norm_transform.lta' """ _cmd = 'mri_em_register' @@ -254,7 +254,7 @@ class Register(FSCommand): >>> register.inputs.target = 'aseg.mgz' >>> register.inputs.out_file = 'lh.pial.reg' >>> register.inputs.curv = True - >>> register.cmdline # doctest: +ALLOW_UNICODE + >>> register.cmdline 'mris_register -curv lh.pial aseg.mgz lh.pial.reg' """ @@ -320,7 +320,7 @@ class Paint(FSCommand): >>> paint.inputs.template = 'aseg.mgz' >>> paint.inputs.averages = 5 >>> paint.inputs.out_file = 'lh.avg_curv' - >>> paint.cmdline # doctest: +ALLOW_UNICODE + >>> paint.cmdline 'mrisp_paint -a 5 aseg.mgz lh.pial lh.avg_curv' """ @@ -437,7 +437,7 @@ class MRICoreg(FSCommand): >>> coreg.inputs.source_file = 'moving1.nii' >>> coreg.inputs.reference_file = 'fixed1.nii' >>> coreg.inputs.subjects_dir = '.' - >>> coreg.cmdline # doctest: +ALLOW_UNICODE +ELLIPSIS + >>> coreg.cmdline # doctest: +ELLIPSIS 'mri_coreg --lta .../registration.lta --ref fixed1.nii --mov moving1.nii --sd .' If passing a subject ID, the reference mask may be disabled: @@ -447,17 +447,17 @@ class MRICoreg(FSCommand): >>> coreg.inputs.subjects_dir = '.' >>> coreg.inputs.subject_id = 'fsaverage' >>> coreg.inputs.reference_mask = False - >>> coreg.cmdline # doctest: +ALLOW_UNICODE +ELLIPSIS + >>> coreg.cmdline # doctest: +ELLIPSIS 'mri_coreg --s fsaverage --no-ref-mask --lta .../registration.lta --mov moving1.nii --sd .' Spatial scales may be specified as a list of one or two separations: >>> coreg.inputs.sep = [4] - >>> coreg.cmdline # doctest: +ALLOW_UNICODE +ELLIPSIS + >>> coreg.cmdline # doctest: +ELLIPSIS 'mri_coreg --s fsaverage --no-ref-mask --lta .../registration.lta --sep 4 --mov moving1.nii --sd .' >>> coreg.inputs.sep = [4, 5] - >>> coreg.cmdline # doctest: +ALLOW_UNICODE +ELLIPSIS + >>> coreg.cmdline # doctest: +ELLIPSIS 'mri_coreg --s fsaverage --no-ref-mask --lta .../registration.lta --sep 4 --sep 5 --mov moving1.nii --sd .' """ diff --git a/nipype/interfaces/freesurfer/tests/test_model.py b/nipype/interfaces/freesurfer/tests/test_model.py index 28e49401e0..a30a29b0ac 100644 --- a/nipype/interfaces/freesurfer/tests/test_model.py +++ b/nipype/interfaces/freesurfer/tests/test_model.py @@ -15,10 +15,10 @@ @pytest.mark.skipif(no_freesurfer(), reason="freesurfer is not installed") def test_concatenate(tmpdir): - tempdir = str(tmpdir) - os.chdir(tempdir) - in1 = os.path.join(tempdir, 'cont1.nii') - in2 = os.path.join(tempdir, 'cont2.nii') + tmpdir.chdir() + + in1 = tmpdir.join('cont1.nii').strpath + in2 = tmpdir.join('cont2.nii').strpath out = 'bar.nii' data1 = np.zeros((3, 3, 3, 1), dtype=np.float32) @@ -31,24 +31,24 @@ def test_concatenate(tmpdir): # Test default behavior res = model.Concatenate(in_files=[in1, in2]).run() - assert res.outputs.concatenated_file == os.path.join(tempdir, 'concat_output.nii.gz') + assert res.outputs.concatenated_file == tmpdir.join('concat_output.nii.gz').strpath assert np.allclose(nb.load('concat_output.nii.gz').get_data(), out_data) # Test specified concatenated_file res = model.Concatenate(in_files=[in1, in2], concatenated_file=out).run() - assert res.outputs.concatenated_file == os.path.join(tempdir, out) + assert res.outputs.concatenated_file == tmpdir.join(out).strpath assert np.allclose(nb.load(out, mmap=NUMPY_MMAP).get_data(), out_data) # Test in workflow - wf = pe.Workflow('test_concatenate', base_dir=tempdir) + wf = pe.Workflow('test_concatenate', base_dir=tmpdir.strpath) concat = pe.Node(model.Concatenate(in_files=[in1, in2], concatenated_file=out), name='concat') wf.add_nodes([concat]) wf.run() - assert np.allclose(nb.load(os.path.join(tempdir, - 'test_concatenate', - 'concat', out)).get_data(), + assert np.allclose(nb.load(tmpdir.join( + 'test_concatenate', + 'concat', out).strpath).get_data(), out_data) # Test a simple statistic diff --git a/nipype/interfaces/freesurfer/utils.py b/nipype/interfaces/freesurfer/utils.py index e71edb3e5c..a5568ebbcb 100644 --- a/nipype/interfaces/freesurfer/utils.py +++ b/nipype/interfaces/freesurfer/utils.py @@ -196,7 +196,7 @@ class SampleToSurface(FSCommand): >>> sampler.inputs.sampling_method = "average" >>> sampler.inputs.sampling_range = 1 >>> sampler.inputs.sampling_units = "frac" - >>> sampler.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> sampler.cmdline # doctest: +ELLIPSIS 'mri_vol2surf --hemi lh --o ...lh.cope1.mgz --reg register.dat --projfrac-avg 1.000 --mov cope1.nii.gz' >>> res = sampler.run() # doctest: +SKIP @@ -233,8 +233,9 @@ def _format_arg(self, name, spec, value): "Cannot create {} file with extension " "{}".format(value, ext)) else: - logger.warn("Creating {} file with extension {}: " - "{}{}".format(value, ext, base, ext)) + logger.warn('Creating %s file with extension %s: %s%s', + value, ext, base, ext) + if value in implicit_filetypes: return "" return super(SampleToSurface, self)._format_arg(name, spec, value) @@ -326,7 +327,7 @@ class SurfaceSmooth(FSCommand): >>> smoother.inputs.subject_id = "subj_1" >>> smoother.inputs.hemi = "lh" >>> smoother.inputs.fwhm = 5 - >>> smoother.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> smoother.cmdline # doctest: +ELLIPSIS 'mri_surf2surf --cortex --fwhm 5.0000 --hemi lh --sval lh.cope1.mgz --tval ...lh.cope1_smooth5.mgz --s subj_1' >>> smoother.run() # doctest: +SKIP @@ -423,8 +424,8 @@ def _format_arg(self, name, spec, value): "Cannot create {} file with extension " "{}".format(value, ext)) else: - logger.warn("Creating {} file with extension {}: " - "{}{}".format(value, ext, base, ext)) + logger.warn('Creating %s file with extension %s: %s%s', + value, ext, base, ext) if value in implicit_filetypes: return "" return super(SurfaceTransform, self)._format_arg(name, spec, value) @@ -518,7 +519,7 @@ class Surface2VolTransform(FSCommand): >>> xfm2vol.inputs.hemi = 'lh' >>> xfm2vol.inputs.template_file = 'cope1.nii.gz' >>> xfm2vol.inputs.subjects_dir = '.' - >>> xfm2vol.cmdline # doctest: +ALLOW_UNICODE + >>> xfm2vol.cmdline 'mri_surf2vol --hemi lh --volreg register.mat --surfval lh.cope1.mgz --sd . --template cope1.nii.gz --outvol lh.cope1_asVol.nii --vtxvol lh.cope1_asVol_vertex.nii' >>> res = xfm2vol.run()# doctest: +SKIP @@ -995,7 +996,7 @@ class MRIsCombine(FSSurfaceCommand): >>> mris = fs.MRIsCombine() >>> mris.inputs.in_files = ['lh.pial', 'rh.pial'] >>> mris.inputs.out_file = 'bh.pial' - >>> mris.cmdline # doctest: +ALLOW_UNICODE + >>> mris.cmdline 'mris_convert --combinesurfs lh.pial rh.pial bh.pial' >>> mris.run() # doctest: +SKIP """ @@ -1124,7 +1125,7 @@ class MRIPretess(FSCommand): >>> pretess.inputs.in_filled = 'wm.mgz' >>> pretess.inputs.in_norm = 'norm.mgz' >>> pretess.inputs.nocorners = True - >>> pretess.cmdline # doctest: +ALLOW_UNICODE + >>> pretess.cmdline 'mri_pretess -nocorners wm.mgz wm norm.mgz wm_pretesswm.mgz' >>> pretess.run() # doctest: +SKIP @@ -1294,7 +1295,7 @@ class MakeAverageSubject(FSCommand): >>> from nipype.interfaces.freesurfer import MakeAverageSubject >>> avg = MakeAverageSubject(subjects_ids=['s1', 's2']) - >>> avg.cmdline # doctest: +ALLOW_UNICODE + >>> avg.cmdline 'make_average_subject --out average --subjects s1 s2' """ @@ -1329,7 +1330,7 @@ class ExtractMainComponent(CommandLine): >>> from nipype.interfaces.freesurfer import ExtractMainComponent >>> mcmp = ExtractMainComponent(in_file='lh.pial') - >>> mcmp.cmdline # doctest: +ALLOW_UNICODE + >>> mcmp.cmdline 'mris_extract_main_component lh.pial lh.maincmp' """ @@ -1404,7 +1405,7 @@ class Tkregister2(FSCommand): >>> tk2.inputs.moving_image = 'T1.mgz' >>> tk2.inputs.target_image = 'structural.nii' >>> tk2.inputs.reg_header = True - >>> tk2.cmdline # doctest: +ALLOW_UNICODE + >>> tk2.cmdline 'tkregister2 --mov T1.mgz --noedit --reg T1_to_native.dat --regheader \ --targ structural.nii' >>> tk2.run() # doctest: +SKIP @@ -1417,7 +1418,7 @@ class Tkregister2(FSCommand): >>> tk2 = Tkregister2() >>> tk2.inputs.moving_image = 'epi.nii' >>> tk2.inputs.fsl_in_matrix = 'flirt.mat' - >>> tk2.cmdline # doctest: +ALLOW_UNICODE + >>> tk2.cmdline 'tkregister2 --fsl flirt.mat --mov epi.nii --noedit --reg register.dat' >>> tk2.run() # doctest: +SKIP """ @@ -1494,11 +1495,11 @@ class AddXFormToHeader(FSCommand): >>> adder = AddXFormToHeader() >>> adder.inputs.in_file = 'norm.mgz' >>> adder.inputs.transform = 'trans.mat' - >>> adder.cmdline # doctest: +ALLOW_UNICODE + >>> adder.cmdline 'mri_add_xform_to_header trans.mat norm.mgz output.mgz' >>> adder.inputs.copy_name = True - >>> adder.cmdline # doctest: +ALLOW_UNICODE + >>> adder.cmdline 'mri_add_xform_to_header -c trans.mat norm.mgz output.mgz' >>> adder.run() # doctest: +SKIP @@ -1552,7 +1553,7 @@ class CheckTalairachAlignment(FSCommand): >>> checker.inputs.in_file = 'trans.mat' >>> checker.inputs.threshold = 0.005 - >>> checker.cmdline # doctest: +ALLOW_UNICODE + >>> checker.cmdline 'talairach_afd -T 0.005 -xfm trans.mat' >>> checker.run() # doctest: +SKIP @@ -1601,7 +1602,7 @@ class TalairachAVI(FSCommand): >>> example = TalairachAVI() >>> example.inputs.in_file = 'norm.mgz' >>> example.inputs.out_file = 'trans.mat' - >>> example.cmdline # doctest: +ALLOW_UNICODE + >>> example.cmdline 'talairach_avi --i norm.mgz --xfm trans.mat' >>> example.run() # doctest: +SKIP @@ -1632,7 +1633,7 @@ class TalairachQC(FSScriptCommand): >>> from nipype.interfaces.freesurfer import TalairachQC >>> qc = TalairachQC() >>> qc.inputs.log_file = 'dirs.txt' - >>> qc.cmdline # doctest: +ALLOW_UNICODE + >>> qc.cmdline 'tal_QC_AZS dirs.txt' """ _cmd = "tal_QC_AZS" @@ -1671,7 +1672,7 @@ class RemoveNeck(FSCommand): >>> remove_neck.inputs.in_file = 'norm.mgz' >>> remove_neck.inputs.transform = 'trans.mat' >>> remove_neck.inputs.template = 'trans.mat' - >>> remove_neck.cmdline # doctest: +ALLOW_UNICODE + >>> remove_neck.cmdline 'mri_remove_neck norm.mgz trans.mat trans.mat norm_noneck.mgz' """ _cmd = "mri_remove_neck" @@ -1811,7 +1812,7 @@ class Sphere(FSCommandOpenMP): >>> from nipype.interfaces.freesurfer import Sphere >>> sphere = Sphere() >>> sphere.inputs.in_file = 'lh.pial' - >>> sphere.cmdline # doctest: +ALLOW_UNICODE + >>> sphere.cmdline 'mris_sphere lh.pial lh.sphere' """ _cmd = 'mris_sphere' @@ -1935,7 +1936,7 @@ class EulerNumber(FSCommand): >>> from nipype.interfaces.freesurfer import EulerNumber >>> ft = EulerNumber() >>> ft.inputs.in_file = 'lh.pial' - >>> ft.cmdline # doctest: +ALLOW_UNICODE + >>> ft.cmdline 'mris_euler_number lh.pial' """ _cmd = 'mris_euler_number' @@ -1971,7 +1972,7 @@ class RemoveIntersection(FSCommand): >>> from nipype.interfaces.freesurfer import RemoveIntersection >>> ri = RemoveIntersection() >>> ri.inputs.in_file = 'lh.pial' - >>> ri.cmdline # doctest: +ALLOW_UNICODE + >>> ri.cmdline 'mris_remove_intersection lh.pial lh.pial' """ @@ -2067,7 +2068,7 @@ class MakeSurfaces(FSCommand): >>> makesurfaces.inputs.in_label = 'aparc+aseg.nii' >>> makesurfaces.inputs.in_T1 = 'T1.mgz' >>> makesurfaces.inputs.orig_pial = 'lh.pial' - >>> makesurfaces.cmdline # doctest: +ALLOW_UNICODE + >>> makesurfaces.cmdline 'mris_make_surfaces -T1 T1.mgz -orig pial -orig_pial pial 10335 lh' """ @@ -2200,7 +2201,7 @@ class Curvature(FSCommand): >>> curv = Curvature() >>> curv.inputs.in_file = 'lh.pial' >>> curv.inputs.save = True - >>> curv.cmdline # doctest: +ALLOW_UNICODE + >>> curv.cmdline 'mris_curvature -w lh.pial' """ @@ -2294,7 +2295,7 @@ class CurvatureStats(FSCommand): >>> curvstats.inputs.values = True >>> curvstats.inputs.min_max = True >>> curvstats.inputs.write = True - >>> curvstats.cmdline # doctest: +ALLOW_UNICODE + >>> curvstats.cmdline 'mris_curvature_stats -m -o lh.curv.stats -F pial -G --writeCurvatureFiles subject_id lh pial pial' """ @@ -2351,7 +2352,7 @@ class Jacobian(FSCommand): >>> jacobian = Jacobian() >>> jacobian.inputs.in_origsurf = 'lh.pial' >>> jacobian.inputs.in_mappedsurf = 'lh.pial' - >>> jacobian.cmdline # doctest: +ALLOW_UNICODE + >>> jacobian.cmdline 'mris_jacobian lh.pial lh.pial lh.jacobian' """ @@ -2488,7 +2489,7 @@ class VolumeMask(FSCommand): >>> volmask.inputs.rh_white = 'lh.pial' >>> volmask.inputs.subject_id = '10335' >>> volmask.inputs.save_ribbon = True - >>> volmask.cmdline # doctest: +ALLOW_UNICODE + >>> volmask.cmdline 'mris_volmask --label_left_ribbon 3 --label_left_white 2 --label_right_ribbon 42 --label_right_white 41 --save_ribbon 10335' """ @@ -2828,7 +2829,7 @@ class RelabelHypointensities(FSCommand): >>> relabelhypos.inputs.rh_white = 'lh.pial' >>> relabelhypos.inputs.surf_directory = '.' >>> relabelhypos.inputs.aseg = 'aseg.mgz' - >>> relabelhypos.cmdline # doctest: +ALLOW_UNICODE + >>> relabelhypos.cmdline 'mri_relabel_hypointensities aseg.mgz . aseg.hypos.mgz' """ @@ -2999,7 +3000,7 @@ class Apas2Aseg(FSCommand): >>> apas2aseg = Apas2Aseg() >>> apas2aseg.inputs.in_file = 'aseg.mgz' >>> apas2aseg.inputs.out_file = 'output.mgz' - >>> apas2aseg.cmdline # doctest: +ALLOW_UNICODE + >>> apas2aseg.cmdline 'apas2aseg --i aseg.mgz --o output.mgz' """ @@ -3081,10 +3082,10 @@ class MRIsExpand(FSSurfaceCommand): >>> from nipype.interfaces.freesurfer import MRIsExpand >>> mris_expand = MRIsExpand(thickness=True, distance=0.5) >>> mris_expand.inputs.in_file = 'lh.white' - >>> mris_expand.cmdline # doctest: +ALLOW_UNICODE + >>> mris_expand.cmdline 'mris_expand -thickness lh.white 0.5 expanded' >>> mris_expand.inputs.out_name = 'graymid' - >>> mris_expand.cmdline # doctest: +ALLOW_UNICODE + >>> mris_expand.cmdline 'mris_expand -thickness lh.white 0.5 graymid' """ _cmd = 'mris_expand' diff --git a/nipype/interfaces/fsl/aroma.py b/nipype/interfaces/fsl/aroma.py index 02df37d9a2..fb8dc82bd8 100644 --- a/nipype/interfaces/fsl/aroma.py +++ b/nipype/interfaces/fsl/aroma.py @@ -95,7 +95,7 @@ class ICA_AROMA(CommandLine): >>> AROMA_obj.inputs.mask = 'mask.nii.gz' >>> AROMA_obj.inputs.denoise_type = 'both' >>> AROMA_obj.inputs.out_dir = 'ICA_testout' - >>> AROMA_obj.cmdline # doctest: +ALLOW_UNICODE + >>> AROMA_obj.cmdline 'ICA_AROMA.py -den both -warp warpfield.nii -i functional.nii -m mask.nii.gz -affmat func_to_struct.mat -mc fsl_mcflirt_movpar.txt -o ICA_testout' """ _cmd = 'ICA_AROMA.py' diff --git a/nipype/interfaces/fsl/base.py b/nipype/interfaces/fsl/base.py index f5353f2b06..6d16817e09 100644 --- a/nipype/interfaces/fsl/base.py +++ b/nipype/interfaces/fsl/base.py @@ -36,7 +36,7 @@ from ..base import traits, isdefined, CommandLine, CommandLineInputSpec from ...external.due import BibTeX -LOGGER = logging.getLogger('interface') +IFLOGGER = logging.getLogger('interface') class Info(object): @@ -113,8 +113,8 @@ def output_type(cls): try: return os.environ['FSLOUTPUTTYPE'] except KeyError: - LOGGER.warn('FSLOUTPUTTYPE environment variable is not set. ' - 'Setting FSLOUTPUTTYPE=NIFTI') + IFLOGGER.warn('FSLOUTPUTTYPE environment variable is not set. ' + 'Setting FSLOUTPUTTYPE=NIFTI') return 'NIFTI' @staticmethod diff --git a/nipype/interfaces/fsl/dti.py b/nipype/interfaces/fsl/dti.py index 9d74a3fafe..812515fcda 100644 --- a/nipype/interfaces/fsl/dti.py +++ b/nipype/interfaces/fsl/dti.py @@ -85,7 +85,7 @@ class DTIFit(FSLCommand): >>> dti.inputs.bvals = 'bvals' >>> dti.inputs.base_name = 'TP' >>> dti.inputs.mask = 'mask.nii' - >>> dti.cmdline # doctest: +ALLOW_UNICODE + >>> dti.cmdline 'dtifit -k diffusion.nii -o TP -m mask.nii -r bvecs -b bvals' """ @@ -327,7 +327,7 @@ class BEDPOSTX5(FSLXCommand): >>> from nipype.interfaces import fsl >>> bedp = fsl.BEDPOSTX5(bvecs='bvecs', bvals='bvals', dwi='diffusion.nii', ... mask='mask.nii', n_fibres=1) - >>> bedp.cmdline # doctest: +ALLOW_UNICODE + >>> bedp.cmdline 'bedpostx bedpostx --forcedir -n 1' """ @@ -583,7 +583,7 @@ class ProbTrackX(FSLCommand): target_masks = ['targets_MASK1.nii', 'targets_MASK2.nii'], \ thsamples='merged_thsamples.nii', fsamples='merged_fsamples.nii', phsamples='merged_phsamples.nii', \ out_dir='.') - >>> pbx.cmdline # doctest: +ALLOW_UNICODE + >>> pbx.cmdline 'probtrackx --forcedir -m mask.nii --mode=seedmask --nsamples=3 --nsteps=10 --opd --os2t --dir=. --samples=merged --seed=MASK_average_thal_right.nii --targetmasks=targets.txt --xfm=trans.mat' """ @@ -780,7 +780,7 @@ class ProbTrackX2(ProbTrackX): >>> pbx2.inputs.out_dir = '.' >>> pbx2.inputs.n_samples = 3 >>> pbx2.inputs.n_steps = 10 - >>> pbx2.cmdline # doctest: +ALLOW_UNICODE + >>> pbx2.cmdline 'probtrackx2 --forcedir -m nodif_brain_mask.nii.gz --nsamples=3 --nsteps=10 --opd --dir=. --samples=merged --seed=seed_source.nii.gz' """ _cmd = 'probtrackx2' @@ -871,7 +871,7 @@ class VecReg(FSLCommand): affine_mat='trans.mat', \ ref_vol='mni.nii', \ out_file='diffusion_vreg.nii') - >>> vreg.cmdline # doctest: +ALLOW_UNICODE + >>> vreg.cmdline 'vecreg -t trans.mat -i diffusion.nii -o diffusion_vreg.nii -r mni.nii' """ @@ -932,7 +932,7 @@ class ProjThresh(FSLCommand): >>> from nipype.interfaces import fsl >>> ldir = ['seeds_to_M1.nii', 'seeds_to_M2.nii'] >>> pThresh = fsl.ProjThresh(in_files=ldir, threshold=3) - >>> pThresh.cmdline # doctest: +ALLOW_UNICODE + >>> pThresh.cmdline 'proj_thresh seeds_to_M1.nii seeds_to_M2.nii 3' """ @@ -980,7 +980,7 @@ class FindTheBiggest(FSLCommand): >>> from nipype.interfaces import fsl >>> ldir = ['seeds_to_M1.nii', 'seeds_to_M2.nii'] >>> fBig = fsl.FindTheBiggest(in_files=ldir, out_file='biggestSegmentation') - >>> fBig.cmdline # doctest: +ALLOW_UNICODE + >>> fBig.cmdline 'find_the_biggest seeds_to_M1.nii seeds_to_M2.nii biggestSegmentation' """ diff --git a/nipype/interfaces/fsl/epi.py b/nipype/interfaces/fsl/epi.py index 5978ee492d..0beb60b3c0 100644 --- a/nipype/interfaces/fsl/epi.py +++ b/nipype/interfaces/fsl/epi.py @@ -71,7 +71,7 @@ class PrepareFieldmap(FSLCommand): >>> prepare.inputs.in_phase = "phase.nii" >>> prepare.inputs.in_magnitude = "magnitude.nii" >>> prepare.inputs.output_type = "NIFTI_GZ" - >>> prepare.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> prepare.cmdline # doctest: +ELLIPSIS 'fsl_prepare_fieldmap SIEMENS phase.nii magnitude.nii \ .../phase_fslprepared.nii.gz 2.460000' >>> res = prepare.run() # doctest: +SKIP @@ -247,7 +247,7 @@ class TOPUP(FSLCommand): >>> topup.inputs.in_file = "b0_b0rev.nii" >>> topup.inputs.encoding_file = "topup_encoding.txt" >>> topup.inputs.output_type = "NIFTI_GZ" - >>> topup.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> topup.cmdline # doctest: +ELLIPSIS 'topup --config=b02b0.cnf --datain=topup_encoding.txt \ --imain=b0_b0rev.nii --out=b0_b0rev_base --iout=b0_b0rev_corrected.nii.gz \ --fout=b0_b0rev_field.nii.gz --jacout=jac --logout=b0_b0rev_topup.log \ @@ -389,7 +389,7 @@ class ApplyTOPUP(FSLCommand): >>> applytopup.inputs.in_topup_fieldcoef = "topup_fieldcoef.nii.gz" >>> applytopup.inputs.in_topup_movpar = "topup_movpar.txt" >>> applytopup.inputs.output_type = "NIFTI_GZ" - >>> applytopup.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> applytopup.cmdline # doctest: +ELLIPSIS 'applytopup --datain=topup_encoding.txt --imain=epi.nii,epi_rev.nii \ --inindex=1,2 --topup=topup --out=epi_corrected.nii.gz' >>> res = applytopup.run() # doctest: +SKIP @@ -545,12 +545,12 @@ class Eddy(FSLCommand): >>> eddy.inputs.in_bvec = 'bvecs.scheme' >>> eddy.inputs.in_bval = 'bvals.scheme' >>> eddy.inputs.use_cuda = True - >>> eddy.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> eddy.cmdline # doctest: +ELLIPSIS 'eddy_cuda --acqp=epi_acqp.txt --bvals=bvals.scheme --bvecs=bvecs.scheme \ --imain=epi.nii --index=epi_index.txt --mask=epi_mask.nii \ --out=.../eddy_corrected' >>> eddy.inputs.use_cuda = False - >>> eddy.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> eddy.cmdline # doctest: +ELLIPSIS 'eddy_openmp --acqp=epi_acqp.txt --bvals=bvals.scheme \ --bvecs=bvecs.scheme --imain=epi.nii --index=epi_index.txt \ --mask=epi_mask.nii --out=.../eddy_corrected' @@ -679,7 +679,7 @@ class SigLoss(FSLCommand): >>> sigloss.inputs.in_file = "phase.nii" >>> sigloss.inputs.echo_time = 0.03 >>> sigloss.inputs.output_type = "NIFTI_GZ" - >>> sigloss.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> sigloss.cmdline # doctest: +ELLIPSIS 'sigloss --te=0.030000 -i phase.nii -s .../phase_sigloss.nii.gz' >>> res = sigloss.run() # doctest: +SKIP @@ -784,7 +784,7 @@ class EpiReg(FSLCommand): >>> epireg.inputs.fmapmagbrain='fieldmap_mag_brain.nii' >>> epireg.inputs.echospacing=0.00067 >>> epireg.inputs.pedir='y' - >>> epireg.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> epireg.cmdline # doctest: +ELLIPSIS 'epi_reg --echospacing=0.000670 --fmap=fieldmap_phase_fslprepared.nii \ --fmapmag=fieldmap_mag.nii --fmapmagbrain=fieldmap_mag_brain.nii --noclean \ --pedir=y --epi=epi.nii --t1=T1.nii --t1brain=T1_brain.nii --out=epi2struct' @@ -895,7 +895,7 @@ class EPIDeWarp(FSLCommand): >>> dewarp.inputs.mag_file = "magnitude.nii" >>> dewarp.inputs.dph_file = "phase.nii" >>> dewarp.inputs.output_type = "NIFTI_GZ" - >>> dewarp.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> dewarp.cmdline # doctest: +ELLIPSIS 'epidewarp.fsl --mag magnitude.nii --dph phase.nii --epi functional.nii \ --esp 0.58 --exfdw .../exfdw.nii.gz --nocleanup --sigma 2 --tediff 2.46 \ --tmpdir .../temp --vsm .../vsm.nii.gz' @@ -988,7 +988,7 @@ class EddyCorrect(FSLCommand): >>> from nipype.interfaces.fsl import EddyCorrect >>> eddyc = EddyCorrect(in_file='diffusion.nii', ... out_file="diffusion_edc.nii", ref_num=0) - >>> eddyc.cmdline # doctest: +ALLOW_UNICODE + >>> eddyc.cmdline 'eddy_correct diffusion.nii diffusion_edc.nii 0' """ diff --git a/nipype/interfaces/fsl/maths.py b/nipype/interfaces/fsl/maths.py index 588f7caf95..f403c5c402 100644 --- a/nipype/interfaces/fsl/maths.py +++ b/nipype/interfaces/fsl/maths.py @@ -439,7 +439,7 @@ class MultiImageMaths(MathsCommand): >>> maths.inputs.op_string = "-add %s -mul -1 -div %s" >>> maths.inputs.operand_files = ["functional2.nii", "functional3.nii"] >>> maths.inputs.out_file = "functional4.nii" - >>> maths.cmdline # doctest: +ALLOW_UNICODE + >>> maths.cmdline 'fslmaths functional.nii -add functional2.nii -mul -1 -div functional3.nii functional4.nii' """ diff --git a/nipype/interfaces/fsl/model.py b/nipype/interfaces/fsl/model.py index b4d3fb56f8..701ee757db 100644 --- a/nipype/interfaces/fsl/model.py +++ b/nipype/interfaces/fsl/model.py @@ -934,7 +934,7 @@ class FLAMEO(FSLCommand): >>> flameo.inputs.t_con_file = 'design.con' >>> flameo.inputs.mask_file = 'mask.nii' >>> flameo.inputs.run_mode = 'fe' - >>> flameo.cmdline # doctest: +ALLOW_UNICODE + >>> flameo.cmdline 'flameo --copefile=cope.nii.gz --covsplitfile=cov_split.mat --designfile=design.mat --ld=stats --maskfile=mask.nii --runmode=fe --tcontrastsfile=design.con --varcopefile=varcope.nii.gz' """ @@ -1601,7 +1601,7 @@ class MELODIC(FSLCommand): >>> melodic_setup.inputs.s_des = 'subjectDesign.mat' >>> melodic_setup.inputs.s_con = 'subjectDesign.con' >>> melodic_setup.inputs.out_dir = 'groupICA.out' - >>> melodic_setup.cmdline # doctest: +ALLOW_UNICODE + >>> melodic_setup.cmdline 'melodic -i functional.nii,functional2.nii,functional3.nii -a tica --bgthreshold=10.000000 --mmthresh=0.500000 --nobet -o groupICA.out --Ostats --Scon=subjectDesign.con --Sdes=subjectDesign.mat --Tcon=timeDesign.con --Tdes=timeDesign.mat --tr=1.500000' >>> melodic_setup.run() # doctest: +SKIP @@ -1657,7 +1657,7 @@ class SmoothEstimate(FSLCommand): >>> est = SmoothEstimate() >>> est.inputs.zstat_file = 'zstat1.nii.gz' >>> est.inputs.mask_file = 'mask.nii' - >>> est.cmdline # doctest: +ALLOW_UNICODE + >>> est.cmdline 'smoothest --mask=mask.nii --zstat=zstat1.nii.gz' """ @@ -1773,7 +1773,7 @@ class Cluster(FSLCommand): >>> cl.inputs.in_file = 'zstat1.nii.gz' >>> cl.inputs.out_localmax_txt_file = 'stats.txt' >>> cl.inputs.use_mm = True - >>> cl.cmdline # doctest: +ALLOW_UNICODE + >>> cl.cmdline 'cluster --in=zstat1.nii.gz --olmax=stats.txt --thresh=2.3000000000 --mm' """ @@ -1859,7 +1859,7 @@ class DualRegression(FSLCommand): >>> dual_regression.inputs.one_sample_group_mean = True >>> dual_regression.inputs.n_perm = 10 >>> dual_regression.inputs.out_dir = "my_output_directory" - >>> dual_regression.cmdline # doctest: +ALLOW_UNICODE + >>> dual_regression.cmdline u'dual_regression allFA.nii 0 -1 10 my_output_directory functional.nii functional2.nii functional3.nii' >>> dual_regression.run() # doctest: +SKIP @@ -1977,7 +1977,7 @@ class Randomise(FSLCommand): ------- >>> import nipype.interfaces.fsl as fsl >>> rand = fsl.Randomise(in_file='allFA.nii', mask = 'mask.nii', tcon='design.con', design_mat='design.mat') - >>> rand.cmdline # doctest: +ALLOW_UNICODE + >>> rand.cmdline 'randomise -i allFA.nii -o "tbss_" -d design.mat -t design.con -m mask.nii' """ @@ -2122,7 +2122,7 @@ class GLM(FSLCommand): ------- >>> import nipype.interfaces.fsl as fsl >>> glm = fsl.GLM(in_file='functional.nii', design='maps.nii', output_type='NIFTI') - >>> glm.cmdline # doctest: +ALLOW_UNICODE + >>> glm.cmdline 'fsl_glm -i functional.nii -d maps.nii -o functional_glm.nii' """ diff --git a/nipype/interfaces/fsl/possum.py b/nipype/interfaces/fsl/possum.py index 20efefbf2c..1c2b10e1d2 100644 --- a/nipype/interfaces/fsl/possum.py +++ b/nipype/interfaces/fsl/possum.py @@ -80,7 +80,7 @@ class B0Calc(FSLCommand): >>> b0calc.inputs.in_file = 'tissue+air_map.nii' >>> b0calc.inputs.z_b0 = 3.0 >>> b0calc.inputs.output_type = "NIFTI_GZ" - >>> b0calc.cmdline # doctest: +ALLOW_UNICODE + >>> b0calc.cmdline 'b0calc -i tissue+air_map.nii -o tissue+air_map_b0field.nii.gz --b0=3.00' """ diff --git a/nipype/interfaces/fsl/preprocess.py b/nipype/interfaces/fsl/preprocess.py index b96c0b6acd..4ffeead842 100644 --- a/nipype/interfaces/fsl/preprocess.py +++ b/nipype/interfaces/fsl/preprocess.py @@ -127,7 +127,7 @@ class BET(FSLCommand): >>> btr.inputs.in_file = 'structural.nii' >>> btr.inputs.frac = 0.7 >>> btr.inputs.out_file = 'brain_anat.nii' - >>> btr.cmdline # doctest: +ALLOW_UNICODE + >>> btr.cmdline 'bet structural.nii brain_anat.nii -f 0.70' >>> res = btr.run() # doctest: +SKIP @@ -298,7 +298,7 @@ class FAST(FSLCommand): >>> fastr = fsl.FAST() >>> fastr.inputs.in_files = 'structural.nii' >>> fastr.inputs.out_basename = 'fast_' - >>> fastr.cmdline # doctest: +ALLOW_UNICODE + >>> fastr.cmdline 'fast -o fast_ -S 1 structural.nii' >>> out = fastr.run() # doctest: +SKIP @@ -541,7 +541,7 @@ class FLIRT(FSLCommand): >>> flt.inputs.in_file = 'structural.nii' >>> flt.inputs.reference = 'mni.nii' >>> flt.inputs.output_type = "NIFTI_GZ" - >>> flt.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> flt.cmdline # doctest: +ELLIPSIS 'flirt -in structural.nii -ref mni.nii -out structural_flirt.nii.gz -omat structural_flirt.mat -bins 640 -searchcost mutualinfo' >>> res = flt.run() #doctest: +SKIP @@ -674,7 +674,7 @@ class MCFLIRT(FSLCommand): >>> mcflt.inputs.in_file = 'functional.nii' >>> mcflt.inputs.cost = 'mutualinfo' >>> mcflt.inputs.out_file = 'moco.nii' - >>> mcflt.cmdline # doctest: +ALLOW_UNICODE + >>> mcflt.cmdline 'mcflirt -in functional.nii -cost mutualinfo -out moco.nii' >>> res = mcflt.run() # doctest: +SKIP @@ -1397,7 +1397,7 @@ class FUGUE(FSLCommand): >>> fugue.inputs.shift_in_file = 'vsm.nii' # Previously computed with fugue as well >>> fugue.inputs.unwarp_direction = 'y' >>> fugue.inputs.output_type = "NIFTI_GZ" - >>> fugue.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> fugue.cmdline # doctest: +ELLIPSIS 'fugue --in=epi.nii --mask=epi_mask.nii --loadshift=vsm.nii --unwarpdir=y --unwarp=epi_unwarped.nii.gz' >>> fugue.run() #doctest: +SKIP @@ -1412,7 +1412,7 @@ class FUGUE(FSLCommand): >>> fugue.inputs.shift_in_file = 'vsm.nii' # Previously computed with fugue as well >>> fugue.inputs.unwarp_direction = 'y' >>> fugue.inputs.output_type = "NIFTI_GZ" - >>> fugue.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> fugue.cmdline # doctest: +ELLIPSIS 'fugue --in=epi.nii --mask=epi_mask.nii --loadshift=vsm.nii --unwarpdir=y --warp=epi_warped.nii.gz' >>> fugue.run() #doctest: +SKIP @@ -1427,7 +1427,7 @@ class FUGUE(FSLCommand): >>> fugue.inputs.unwarp_direction = 'y' >>> fugue.inputs.save_shift = True >>> fugue.inputs.output_type = "NIFTI_GZ" - >>> fugue.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> fugue.cmdline # doctest: +ELLIPSIS 'fugue --dwelltoasym=0.9390243902 --mask=epi_mask.nii --phasemap=epi_phasediff.nii --saveshift=epi_phasediff_vsm.nii.gz --unwarpdir=y' >>> fugue.run() #doctest: +SKIP diff --git a/nipype/interfaces/fsl/tests/test_Level1Design_functions.py b/nipype/interfaces/fsl/tests/test_Level1Design_functions.py index 56fdecd0b4..b7573f7454 100644 --- a/nipype/interfaces/fsl/tests/test_Level1Design_functions.py +++ b/nipype/interfaces/fsl/tests/test_Level1Design_functions.py @@ -4,7 +4,8 @@ from ..model import Level1Design -def test_level1design(): +def test_level1design(tmpdir): + old = tmpdir.chdir() l = Level1Design() runinfo = dict(cond=[{'name': 'test_condition', 'onset': [0, 10], 'duration':[10, 10]}],regress=[]) diff --git a/nipype/interfaces/fsl/tests/test_model.py b/nipype/interfaces/fsl/tests/test_model.py index 667e9033c9..b2e3f8571c 100644 --- a/nipype/interfaces/fsl/tests/test_model.py +++ b/nipype/interfaces/fsl/tests/test_model.py @@ -13,7 +13,7 @@ @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") def test_MultipleRegressDesign(tmpdir): - os.chdir(str(tmpdir)) + tmpdir.chdir() foo = fsl.MultipleRegressDesign() foo.inputs.regressors = dict(voice_stenght=[1, 1, 1], age=[0.2, 0.4, 0.5], BMI=[1, -1, 2]) con1 = ['voice_and_age', 'T', ['age', 'voice_stenght'], [0.5, 0.5]] @@ -22,7 +22,7 @@ def test_MultipleRegressDesign(tmpdir): res = foo.run() for ii in ["mat", "con", "fts", "grp"]: - assert getattr(res.outputs, "design_"+ii) == os.path.join(os.getcwd(), 'design.'+ii) + assert getattr(res.outputs, "design_"+ii) == tmpdir.join('design.'+ii).strpath design_mat_expected_content = """/NumWaves 3 /NumPoints 3 @@ -62,6 +62,6 @@ def test_MultipleRegressDesign(tmpdir): 1 """ for ii in ["mat", "con", "fts", "grp"]: - assert open(os.path.join(os.getcwd(), 'design.'+ii), 'r').read() == eval("design_"+ii+"_expected_content") + assert tmpdir.join('design.'+ii).read() == eval("design_"+ii+"_expected_content") diff --git a/nipype/interfaces/fsl/tests/test_preprocess.py b/nipype/interfaces/fsl/tests/test_preprocess.py index 32f0266ddb..3d75d514a6 100644 --- a/nipype/interfaces/fsl/tests/test_preprocess.py +++ b/nipype/interfaces/fsl/tests/test_preprocess.py @@ -6,10 +6,9 @@ from builtins import open, open import os -import tempfile from copy import deepcopy -import pytest +import pytest, pdb from nipype.utils.filemanip import split_filename, filename_to_list from .. import preprocess as fsl from nipype.interfaces.fsl import Info @@ -27,11 +26,9 @@ def fsl_name(obj, fname): @pytest.fixture() def setup_infile(tmpdir): ext = Info.output_type_to_ext(Info.output_type()) - tmp_dir = str(tmpdir) - tmp_infile = os.path.join(tmp_dir, 'foo' + ext) - open(tmp_infile, 'w') - - return (tmp_infile, tmp_dir) + tmp_infile = tmpdir.join('foo' + ext) + tmp_infile.open("w") + return (tmp_infile.strpath, tmpdir.strpath) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -153,7 +150,7 @@ def test_fast(setup_infile): @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") -def test_fast_list_outputs(setup_infile): +def test_fast_list_outputs(setup_infile, tmpdir): ''' By default (no -o), FSL's fast command outputs files into the same directory as the input files. If the flag -o is set, it outputs files into the cwd ''' @@ -166,9 +163,9 @@ def _run_and_test(opts, output_base): # set up tmp_infile, indir = setup_infile - cwd = tempfile.mkdtemp() - os.chdir(cwd) - assert indir != cwd + cwd = tmpdir.mkdir("new") + cwd.chdir() + assert indir != cwd.strpath out_basename = 'a_basename' # run and test @@ -177,17 +174,17 @@ def _run_and_test(opts, output_base): _run_and_test(opts, os.path.join(input_path, input_filename)) opts['out_basename'] = out_basename - _run_and_test(opts, os.path.join(cwd, out_basename)) + _run_and_test(opts, os.path.join(cwd.strpath, out_basename)) @pytest.fixture() def setup_flirt(tmpdir): ext = Info.output_type_to_ext(Info.output_type()) - tmp_dir = str(tmpdir) - _, infile = tempfile.mkstemp(suffix=ext, dir=tmp_dir) - _, reffile = tempfile.mkstemp(suffix=ext, dir=tmp_dir) - - return (tmp_dir, infile, reffile) + infile = tmpdir.join("infile"+ext) + infile.open("w") + reffile = tmpdir.join("reffile"+ext) + reffile.open("w") + return (tmpdir, infile.strpath, reffile.strpath) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -205,6 +202,7 @@ def test_flirt(setup_flirt): out_file='outfile', out_matrix_file='outmat.mat', bins=256, cost='mutualinfo') + flirt_est = fsl.FLIRT(in_file=infile, reference=reffile, out_matrix_file='outmat.mat', bins=256, @@ -249,8 +247,8 @@ def test_flirt(setup_flirt): axfm2.inputs.in_matrix_file = reffile assert axfm2.cmdline == (realcmd + ' -applyxfm -init %s' % reffile) - - _, tmpfile = tempfile.mkstemp(suffix='.nii', dir=tmpdir) + tmpfile = tmpdir.join("file4test.nii") + tmpfile.open("w") # Loop over all inputs, set a reasonable value and make sure the # cmdline is updated correctly. for key, trait_spec in sorted(fsl.FLIRT.input_spec().traits().items()): @@ -267,7 +265,7 @@ def test_flirt(setup_flirt): param = '-v' value = '-v' elif isinstance(trait_spec.trait_type, File): - value = tmpfile + value = tmpfile.strpath param = trait_spec.argstr % value elif trait_spec.default is False: param = trait_spec.argstr @@ -383,7 +381,7 @@ def test_mcflirt_noinput(): def test_fnirt(setup_flirt): tmpdir, infile, reffile = setup_flirt - os.chdir(tmpdir) + tmpdir.chdir() fnirt = fsl.FNIRT() assert fnirt.cmd == 'fnirt' @@ -549,11 +547,10 @@ def setup_fugue(tmpdir): import os.path as op d = np.ones((80, 80, 80)) - tmp_dir = str(tmpdir) - infile = op.join(tmp_dir, 'dumbfile.nii.gz') + infile = tmpdir.join('dumbfile.nii.gz').strpath nb.Nifti1Image(d, None, None).to_filename(infile) - return (tmp_dir, infile) + return (tmpdir, infile) @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") diff --git a/nipype/interfaces/fsl/tests/test_utils.py b/nipype/interfaces/fsl/tests/test_utils.py index 9196d6d8d9..66b91cf96f 100644 --- a/nipype/interfaces/fsl/tests/test_utils.py +++ b/nipype/interfaces/fsl/tests/test_utils.py @@ -3,8 +3,6 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: import os -from tempfile import mkdtemp -from shutil import rmtree import numpy as np diff --git a/nipype/interfaces/fsl/utils.py b/nipype/interfaces/fsl/utils.py index 072895a719..b28a4df425 100644 --- a/nipype/interfaces/fsl/utils.py +++ b/nipype/interfaces/fsl/utils.py @@ -191,7 +191,7 @@ class Smooth(FSLCommand): >>> sm.inputs.output_type = 'NIFTI_GZ' >>> sm.inputs.in_file = 'functional2.nii' >>> sm.inputs.sigma = 8.0 - >>> sm.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> sm.cmdline # doctest: +ELLIPSIS 'fslmaths functional2.nii -kernel gauss 8.000 -fmean functional2_smooth.nii.gz' Setting the kernel width using fwhm: @@ -200,7 +200,7 @@ class Smooth(FSLCommand): >>> sm.inputs.output_type = 'NIFTI_GZ' >>> sm.inputs.in_file = 'functional2.nii' >>> sm.inputs.fwhm = 8.0 - >>> sm.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> sm.cmdline # doctest: +ELLIPSIS 'fslmaths functional2.nii -kernel gauss 3.397 -fmean functional2_smooth.nii.gz' One of sigma or fwhm must be set: @@ -263,10 +263,10 @@ class Merge(FSLCommand): >>> merger.inputs.in_files = ['functional2.nii', 'functional3.nii'] >>> merger.inputs.dimension = 't' >>> merger.inputs.output_type = 'NIFTI_GZ' - >>> merger.cmdline # doctest: +ALLOW_UNICODE + >>> merger.cmdline 'fslmerge -t functional2_merged.nii.gz functional2.nii functional3.nii' >>> merger.inputs.tr = 2.25 - >>> merger.cmdline # doctest: +ALLOW_UNICODE + >>> merger.cmdline 'fslmerge -tr functional2_merged.nii.gz functional2.nii functional3.nii 2.25' @@ -1187,7 +1187,7 @@ class ConvertXFM(FSLCommand): >>> invt.inputs.in_file = "flirt.mat" >>> invt.inputs.invert_xfm = True >>> invt.inputs.out_file = 'flirt_inv.mat' - >>> invt.cmdline # doctest: +ALLOW_UNICODE + >>> invt.cmdline 'convert_xfm -omat flirt_inv.mat -inverse flirt.mat' @@ -1492,7 +1492,7 @@ class InvWarp(FSLCommand): >>> invwarp.inputs.warp = "struct2mni.nii" >>> invwarp.inputs.reference = "anatomical.nii" >>> invwarp.inputs.output_type = "NIFTI_GZ" - >>> invwarp.cmdline # doctest: +ALLOW_UNICODE + >>> invwarp.cmdline 'invwarp --out=struct2mni_inverse.nii.gz --ref=anatomical.nii --warp=struct2mni.nii' >>> res = invwarp.run() # doctest: +SKIP @@ -1728,7 +1728,7 @@ class WarpUtils(FSLCommand): >>> warputils.inputs.out_format = 'spline' >>> warputils.inputs.warp_resolution = (10,10,10) >>> warputils.inputs.output_type = "NIFTI_GZ" - >>> warputils.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> warputils.cmdline # doctest: +ELLIPSIS 'fnirtfileutils --in=warpfield.nii --outformat=spline --ref=T1.nii --warpres=10.0000,10.0000,10.0000 --out=warpfield_coeffs.nii.gz' >>> res = invwarp.run() # doctest: +SKIP @@ -1880,7 +1880,7 @@ class ConvertWarp(FSLCommand): >>> warputils.inputs.reference = "T1.nii" >>> warputils.inputs.relwarp = True >>> warputils.inputs.output_type = "NIFTI_GZ" - >>> warputils.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> warputils.cmdline # doctest: +ELLIPSIS 'convertwarp --ref=T1.nii --rel --warp1=warpfield.nii --out=T1_concatwarp.nii.gz' >>> res = warputils.run() # doctest: +SKIP @@ -1940,7 +1940,7 @@ class WarpPoints(CommandLine): >>> warppoints.inputs.dest_file = 'T1.nii' >>> warppoints.inputs.warp_file = 'warpfield.nii' >>> warppoints.inputs.coord_mm = True - >>> warppoints.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> warppoints.cmdline # doctest: +ELLIPSIS 'img2imgcoord -mm -dest T1.nii -src epi.nii -warp warpfield.nii surf.txt' >>> res = warppoints.run() # doctest: +SKIP @@ -2100,7 +2100,7 @@ class WarpPointsToStd(WarpPoints): >>> warppoints.inputs.std_file = 'mni.nii' >>> warppoints.inputs.warp_file = 'warpfield.nii' >>> warppoints.inputs.coord_mm = True - >>> warppoints.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> warppoints.cmdline # doctest: +ELLIPSIS 'img2stdcoord -mm -img T1.nii -std mni.nii -warp warpfield.nii surf.txt' >>> res = warppoints.run() # doctest: +SKIP @@ -2148,7 +2148,7 @@ class WarpPointsFromStd(CommandLine): >>> warppoints.inputs.std_file = 'mni.nii' >>> warppoints.inputs.warp_file = 'warpfield.nii' >>> warppoints.inputs.coord_mm = True - >>> warppoints.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> warppoints.cmdline # doctest: +ELLIPSIS 'std2imgcoord -mm -img T1.nii -std mni.nii -warp warpfield.nii surf.txt' >>> res = warppoints.run() # doctest: +SKIP @@ -2217,7 +2217,7 @@ class MotionOutliers(FSLCommand): >>> from nipype.interfaces.fsl import MotionOutliers >>> mo = MotionOutliers() >>> mo.inputs.in_file = "epi.nii" - >>> mo.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> mo.cmdline # doctest: +ELLIPSIS 'fsl_motion_outliers -i epi.nii -o epi_outliers.txt -p epi_metrics.png -s epi_metrics.txt' >>> res = mo.run() # doctest: +SKIP """ diff --git a/nipype/interfaces/io.py b/nipype/interfaces/io.py index 4d3220b044..0793b955bd 100644 --- a/nipype/interfaces/io.py +++ b/nipype/interfaces/io.py @@ -351,17 +351,17 @@ def _substitute(self, pathstr): oldpathstr = pathstr pathstr = pathstr.replace(key, val) if pathstr != oldpathstr: - iflogger.debug('sub.str: %s -> %s using %r -> %r' - % (oldpathstr, pathstr, key, val)) + iflogger.debug('sub.str: %s -> %s using %r -> %r', + oldpathstr, pathstr, key, val) if isdefined(self.inputs.regexp_substitutions): for key, val in self.inputs.regexp_substitutions: oldpathstr = pathstr pathstr, _ = re.subn(key, val, pathstr) if pathstr != oldpathstr: - iflogger.debug('sub.regexp: %s -> %s using %r -> %r' - % (oldpathstr, pathstr, key, val)) + iflogger.debug('sub.regexp: %s -> %s using %r -> %r', + oldpathstr, pathstr, key, val) if pathstr_ != pathstr: - iflogger.info('sub: %s -> %s' % (pathstr_, pathstr)) + iflogger.info('sub: %s -> %s', pathstr_, pathstr) return pathstr # Check for s3 in base directory @@ -514,8 +514,8 @@ def _fetch_bucket(self, bucket_name): # Try and get AWS credentials if a creds_path is specified if aws_access_key_id and aws_secret_access_key: # Init connection - iflogger.info('Connecting to S3 bucket: %s with credentials...'\ - % bucket_name) + iflogger.info('Connecting to S3 bucket: %s with credentials...', + bucket_name) # Use individual session for each instance of DataSink # Better when datasinks are being used in multi-threading, see: # http://boto3.readthedocs.org/en/latest/guide/resources.html#multithreading @@ -525,8 +525,7 @@ def _fetch_bucket(self, bucket_name): # Otherwise, connect anonymously else: - iflogger.info('Connecting to AWS: %s anonymously...'\ - % bucket_name) + iflogger.info('Connecting to AWS: %s anonymously...', bucket_name) session = boto3.session.Session() s3_resource = session.resource('s3', use_ssl=True) s3_resource.meta.client.meta.events.register('choose-signer.s3.*', @@ -611,7 +610,7 @@ def _upload_to_s3(self, bucket, src, dst): src_md5 = hashlib.md5(src_read).hexdigest() # Move to next loop iteration if dst_md5 == src_md5: - iflogger.info('File %s already exists on S3, skipping...' % dst_f) + iflogger.info('File %s already exists on S3, skipping...', dst_f) continue else: iflogger.info('Overwriting previous S3 file...') @@ -620,8 +619,8 @@ def _upload_to_s3(self, bucket, src, dst): iflogger.info('New file to S3') # Copy file up to S3 (either encrypted or not) - iflogger.info('Uploading %s to S3 bucket, %s, as %s...'\ - % (src_f, bucket.name, dst_f)) + iflogger.info('Uploading %s to S3 bucket, %s, as %s...', src_f, + bucket.name, dst_f) if self.inputs.encrypt_bucket_keys: extra_args = {'ServerSideEncryption' : 'AES256'} else: @@ -671,7 +670,7 @@ def _list_outputs(self): outdir = local_out_exception # Log local copying directory iflogger.info('Access to S3 failed! Storing outputs locally at: '\ - '%s\nError: %s' %(outdir, exc)) + '%s\nError: %s', outdir, exc) else: s3dir = '' @@ -697,7 +696,7 @@ def _list_outputs(self): for key, files in list(self.inputs._outputs.items()): if not isdefined(files): continue - iflogger.debug("key: %s files: %s" % (key, str(files))) + iflogger.debug("key: %s files: %s", key, str(files)) files = filename_to_list(files) tempoutdir = outdir if s3_flag: @@ -745,16 +744,16 @@ def _list_outputs(self): raise(inst) # If src is a file, copy it to dst if os.path.isfile(src): - iflogger.debug('copyfile: %s %s' % (src, dst)) + iflogger.debug('copyfile: %s %s', src, dst) copyfile(src, dst, copy=True, hashmethod='content', use_hardlink=use_hardlink) out_files.append(dst) # If src is a directory, copy entire contents to dst dir elif os.path.isdir(src): if os.path.exists(dst) and self.inputs.remove_dest_dir: - iflogger.debug('removing: %s' % dst) + iflogger.debug('removing: %s', dst) shutil.rmtree(dst) - iflogger.debug('copydir: %s %s' % (src, dst)) + iflogger.debug('copydir: %s %s', src, dst) copytree(src, dst) out_files.append(dst) @@ -1222,7 +1221,7 @@ class SelectFiles(IOBase): ... "epi": "{subject_id}/func/f[0, 1].nii"} >>> dg = Node(SelectFiles(templates), "selectfiles") >>> dg.inputs.subject_id = "subj1" - >>> pprint.pprint(dg.outputs.get()) # doctest: +NORMALIZE_WHITESPACE +ALLOW_UNICODE + >>> pprint.pprint(dg.outputs.get()) # doctest: {'T1': , 'epi': } The same thing with dynamic grabbing of specific files: @@ -2430,7 +2429,7 @@ def _list_outputs(self): try: sftp.get(os.path.join(filledtemplate_dir, f), f) except IOError: - iflogger.info('remote file %s not found' % f) + iflogger.info('remote file %s not found', f) if any([val is None for val in outputs[key]]): outputs[key] = [] if len(outputs[key]) == 0: @@ -2477,18 +2476,28 @@ class JSONFileGrabber(IOBase): Example ------- + .. testsetup:: + + >>> tmp = getfixture('tmpdir') + >>> old = tmp.chdir() # changing to a temporary directory + + .. doctest:: + >>> import pprint >>> from nipype.interfaces.io import JSONFileGrabber >>> jsonSource = JSONFileGrabber() >>> jsonSource.inputs.defaults = {'param1': 'overrideMe', 'param3': 1.0} >>> res = jsonSource.run() - >>> pprint.pprint(res.outputs.get()) # doctest: +ALLOW_UNICODE + >>> pprint.pprint(res.outputs.get()) {'param1': 'overrideMe', 'param3': 1.0} - >>> jsonSource.inputs.in_file = 'jsongrabber.txt' + >>> jsonSource.inputs.in_file = os.path.join(datadir, 'jsongrabber.txt') >>> res = jsonSource.run() - >>> pprint.pprint(res.outputs.get()) # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS +ALLOW_UNICODE + >>> pprint.pprint(res.outputs.get()) # doctest:, +ELLIPSIS {'param1': 'exampleStr', 'param2': 4, 'param3': 1.0} + .. testsetup:: + + >>> os.chdir(old.strpath) """ input_spec = JSONFileGrabberInputSpec diff --git a/nipype/interfaces/meshfix.py b/nipype/interfaces/meshfix.py index 6ae1859459..466190468a 100644 --- a/nipype/interfaces/meshfix.py +++ b/nipype/interfaces/meshfix.py @@ -105,7 +105,7 @@ class MeshFix(CommandLine): >>> fix.inputs.in_file1 = 'lh-pial.stl' >>> fix.inputs.in_file2 = 'rh-pial.stl' >>> fix.run() # doctest: +SKIP - >>> fix.cmdline # doctest: +ALLOW_UNICODE + >>> fix.cmdline 'meshfix lh-pial.stl rh-pial.stl -o lh-pial_fixed.off' """ _cmd = 'meshfix' diff --git a/nipype/interfaces/minc/base.py b/nipype/interfaces/minc/base.py index 6348e4ee0f..e4b8592adf 100644 --- a/nipype/interfaces/minc/base.py +++ b/nipype/interfaces/minc/base.py @@ -109,11 +109,11 @@ def aggregate_filename(files, new_suffix): >>> from nipype.interfaces.minc.base import aggregate_filename >>> f = aggregate_filename(['/tmp/foo1.mnc', '/tmp/foo2.mnc', '/tmp/foo3.mnc'], 'averaged') - >>> os.path.split(f)[1] # This has a full path, so just check the filename. # doctest: +ALLOW_UNICODE + >>> os.path.split(f)[1] # This has a full path, so just check the filename. 'foo_averaged.mnc' >>> f = aggregate_filename(['/tmp/foo1.mnc', '/tmp/blah1.mnc'], 'averaged') - >>> os.path.split(f)[1] # This has a full path, so just check the filename. # doctest: +ALLOW_UNICODE + >>> os.path.split(f)[1] # This has a full path, so just check the filename. 'foo1_averaged.mnc' """ diff --git a/nipype/interfaces/mne/base.py b/nipype/interfaces/mne/base.py index f2f3a70641..5196ddf5be 100644 --- a/nipype/interfaces/mne/base.py +++ b/nipype/interfaces/mne/base.py @@ -55,7 +55,7 @@ class WatershedBEM(FSCommand): >>> bem = WatershedBEM() >>> bem.inputs.subject_id = 'subj1' >>> bem.inputs.subjects_dir = '.' - >>> bem.cmdline # doctest: +ALLOW_UNICODE + >>> bem.cmdline 'mne_watershed_bem --overwrite --subject subj1 --volume T1' >>> bem.run() # doctest: +SKIP diff --git a/nipype/interfaces/mrtrix/convert.py b/nipype/interfaces/mrtrix/convert.py index 00e87ec0dd..eb34de974e 100644 --- a/nipype/interfaces/mrtrix/convert.py +++ b/nipype/interfaces/mrtrix/convert.py @@ -68,7 +68,7 @@ def read_mrtrix_header(in_file): key = line.split(': ')[0] value = line.split(': ')[1] header[key] = value - iflogger.info('...adding "{v}" to header for key "{k}"'.format(v=value, k=key)) + iflogger.info('...adding "%s" to header for key "%s"', value, key) fileobj.close() header['count'] = int(header['count'].replace('\n', '')) header['offset'] = int(header['file'].replace('.', '')) @@ -118,8 +118,8 @@ def track_gen(track_points): raise HeaderError( 'Expecting %s points, found only %s' % ( stream_count, n_streams)) - iflogger.error('Expecting %s points, found only %s' % ( - stream_count, n_streams)) + iflogger.error('Expecting %s points, found only %s', + stream_count, n_streams) break pts = np.ndarray( shape=(n_pts, pt_cols), @@ -136,16 +136,15 @@ def track_gen(track_points): yield xyz n_streams += 1 if n_streams == stream_count: - iflogger.info('100% : {n} tracks read'.format(n=n_streams)) + iflogger.info('100%% : %i tracks read', n_streams) raise StopIteration try: if n_streams % int(stream_count / 100) == 0: percent = int(float(n_streams) / float(stream_count) * 100) - iflogger.info('{p}% : {n} tracks read'.format(p=percent, - n=n_streams)) + iflogger.info('%i%% : %i tracks read', percent, n_streams) except ZeroDivisionError: - iflogger.info('{} stream read out of {}'.format(n_streams, - stream_count)) + iflogger.info('%i stream read out of %i', n_streams, + stream_count) track_points, nonfinite_list = points_per_track(offset) fileobj.seek(offset) streamlines = track_gen(track_points) @@ -200,14 +199,16 @@ def _run_interface(self, runtime): trk_header['n_count'] = header['count'] if isdefined(self.inputs.matrix_file) and isdefined(self.inputs.registration_image_file): - iflogger.info('Applying transformation from matrix file {m}'.format(m=self.inputs.matrix_file)) + iflogger.info('Applying transformation from matrix file %s', + self.inputs.matrix_file) xfm = np.genfromtxt(self.inputs.matrix_file) iflogger.info(xfm) registration_image_file = nb.load(self.inputs.registration_image_file) reg_affine = registration_image_file.affine r_dx, r_dy, r_dz = get_data_dims(self.inputs.registration_image_file) r_vx, r_vy, r_vz = get_vox_dims(self.inputs.registration_image_file) - iflogger.info('Using affine from registration image file {r}'.format(r=self.inputs.registration_image_file)) + iflogger.info('Using affine from registration image file %s', + self.inputs.registration_image_file) iflogger.info(reg_affine) trk_header['vox_to_ras'] = reg_affine trk_header['dim'] = [r_dx, r_dy, r_dz] @@ -225,18 +226,19 @@ def _run_interface(self, runtime): final_streamlines = move_streamlines(transformed_streamlines, aff) trk_tracks = ((ii, None, None) for ii in final_streamlines) trk.write(out_filename, trk_tracks, trk_header) - iflogger.info('Saving transformed Trackvis file as {out}'.format(out=out_filename)) + iflogger.info('Saving transformed Trackvis file as %s', out_filename) iflogger.info('New TrackVis Header:') iflogger.info(trk_header) else: - iflogger.info('Applying transformation from scanner coordinates to {img}'.format(img=self.inputs.image_file)) + iflogger.info('Applying transformation from scanner coordinates to %s', + self.inputs.image_file) axcode = aff2axcodes(affine) trk_header['voxel_order'] = axcode[0] + axcode[1] + axcode[2] trk_header['vox_to_ras'] = affine transformed_streamlines = transform_to_affine(streamlines, trk_header, affine) trk_tracks = ((ii, None, None) for ii in transformed_streamlines) trk.write(out_filename, trk_tracks, trk_header) - iflogger.info('Saving Trackvis file as {out}'.format(out=out_filename)) + iflogger.info('Saving Trackvis file as %s', out_filename) iflogger.info('TrackVis Header:') iflogger.info(trk_header) return runtime diff --git a/nipype/interfaces/mrtrix/preprocess.py b/nipype/interfaces/mrtrix/preprocess.py index 7ca6abd1fb..becee5088f 100644 --- a/nipype/interfaces/mrtrix/preprocess.py +++ b/nipype/interfaces/mrtrix/preprocess.py @@ -144,7 +144,7 @@ class DWI2Tensor(CommandLine): >>> dwi2tensor = mrt.DWI2Tensor() >>> dwi2tensor.inputs.in_file = 'dwi.mif' >>> dwi2tensor.inputs.encoding_file = 'encoding.txt' - >>> dwi2tensor.cmdline # doctest: +ALLOW_UNICODE + >>> dwi2tensor.cmdline 'dwi2tensor -grad encoding.txt dwi.mif dwi_tensor.mif' >>> dwi2tensor.run() # doctest: +SKIP """ diff --git a/nipype/interfaces/mrtrix/tracking.py b/nipype/interfaces/mrtrix/tracking.py index 5fa39d38d3..5570a9b8d1 100644 --- a/nipype/interfaces/mrtrix/tracking.py +++ b/nipype/interfaces/mrtrix/tracking.py @@ -210,7 +210,7 @@ class StreamlineTrack(CommandLine): >>> strack.inputs.in_file = 'data.Bfloat' >>> strack.inputs.seed_file = 'seed_mask.nii' >>> strack.inputs.mask_file = 'mask.nii' - >>> strack.cmdline # doctest: +ALLOW_UNICODE + >>> strack.cmdline 'streamtrack -mask mask.nii -seed seed_mask.nii SD_PROB data.Bfloat data_tracked.tck' >>> strack.run() # doctest: +SKIP """ diff --git a/nipype/interfaces/mrtrix3/base.py b/nipype/interfaces/mrtrix3/base.py index ab982b816a..a9890d9653 100644 --- a/nipype/interfaces/mrtrix3/base.py +++ b/nipype/interfaces/mrtrix3/base.py @@ -16,7 +16,7 @@ from ... import logging from ..traits_extension import isdefined from ..base import (CommandLineInputSpec, CommandLine, traits, File) -logger = logging.getLogger('interface') +iflogger = logging.getLogger('interface') class MRTrix3BaseInputSpec(CommandLineInputSpec): @@ -52,7 +52,7 @@ def _format_arg(self, name, trait_spec, value): from multiprocessing import cpu_count value = cpu_count() except: - logger.warn('Number of threads could not be computed') + iflogger.warn('Number of threads could not be computed') pass return trait_spec.argstr % value diff --git a/nipype/interfaces/mrtrix3/connectivity.py b/nipype/interfaces/mrtrix3/connectivity.py index a2e7db355d..caa510e6e1 100644 --- a/nipype/interfaces/mrtrix3/connectivity.py +++ b/nipype/interfaces/mrtrix3/connectivity.py @@ -96,7 +96,7 @@ class BuildConnectome(MRTrix3Base): >>> mat = mrt.BuildConnectome() >>> mat.inputs.in_file = 'tracks.tck' >>> mat.inputs.in_parc = 'aparc+aseg.nii' - >>> mat.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> mat.cmdline # doctest: +ELLIPSIS 'tck2connectome tracks.tck aparc+aseg.nii connectome.csv' >>> mat.run() # doctest: +SKIP """ @@ -155,7 +155,7 @@ class LabelConfig(MRTrix3Base): >>> labels = mrt.LabelConfig() >>> labels.inputs.in_file = 'aparc+aseg.nii' >>> labels.inputs.in_config = 'mrtrix3_labelconfig.txt' - >>> labels.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> labels.cmdline # doctest: +ELLIPSIS 'labelconfig aparc+aseg.nii mrtrix3_labelconfig.txt parcellation.mif' >>> labels.run() # doctest: +SKIP """ diff --git a/nipype/interfaces/mrtrix3/preprocess.py b/nipype/interfaces/mrtrix3/preprocess.py index 91ec44d1f0..141325e25b 100644 --- a/nipype/interfaces/mrtrix3/preprocess.py +++ b/nipype/interfaces/mrtrix3/preprocess.py @@ -96,7 +96,7 @@ class ResponseSD(MRTrix3Base): >>> resp.inputs.in_file = 'dwi.mif' >>> resp.inputs.in_mask = 'mask.nii.gz' >>> resp.inputs.grad_fsl = ('bvecs', 'bvals') - >>> resp.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> resp.cmdline # doctest: +ELLIPSIS 'dwi2response -fslgrad bvecs bvals -mask mask.nii.gz dwi.mif response.txt' >>> resp.run() # doctest: +SKIP """ @@ -139,7 +139,7 @@ class ACTPrepareFSL(CommandLine): >>> import nipype.interfaces.mrtrix3 as mrt >>> prep = mrt.ACTPrepareFSL() >>> prep.inputs.in_file = 'T1.nii.gz' - >>> prep.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> prep.cmdline # doctest: +ELLIPSIS 'act_anat_prepare_fsl T1.nii.gz act_5tt.mif' >>> prep.run() # doctest: +SKIP """ @@ -185,7 +185,7 @@ class ReplaceFSwithFIRST(CommandLine): >>> prep.inputs.in_file = 'aparc+aseg.nii' >>> prep.inputs.in_t1w = 'T1.nii.gz' >>> prep.inputs.in_config = 'mrtrix3_labelconfig.txt' - >>> prep.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> prep.cmdline # doctest: +ELLIPSIS 'fs_parc_replace_sgm_first aparc+aseg.nii T1.nii.gz \ mrtrix3_labelconfig.txt aparc+first.mif' >>> prep.run() # doctest: +SKIP diff --git a/nipype/interfaces/mrtrix3/reconst.py b/nipype/interfaces/mrtrix3/reconst.py index b1f71dd572..b608c5514c 100644 --- a/nipype/interfaces/mrtrix3/reconst.py +++ b/nipype/interfaces/mrtrix3/reconst.py @@ -58,7 +58,7 @@ class FitTensor(MRTrix3Base): >>> tsr.inputs.in_file = 'dwi.mif' >>> tsr.inputs.in_mask = 'mask.nii.gz' >>> tsr.inputs.grad_fsl = ('bvecs', 'bvals') - >>> tsr.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> tsr.cmdline # doctest: +ELLIPSIS 'dwi2tensor -fslgrad bvecs bvals -mask mask.nii.gz dwi.mif dti.mif' >>> tsr.run() # doctest: +SKIP """ @@ -173,7 +173,7 @@ class EstimateFOD(MRTrix3Base): >>> fod.inputs.response = 'response.txt' >>> fod.inputs.in_mask = 'mask.nii.gz' >>> fod.inputs.grad_fsl = ('bvecs', 'bvals') - >>> fod.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> fod.cmdline # doctest: +ELLIPSIS 'dwi2fod -fslgrad bvecs bvals -mask mask.nii.gz dwi.mif response.txt\ fods.mif' >>> fod.run() # doctest: +SKIP diff --git a/nipype/interfaces/mrtrix3/tracking.py b/nipype/interfaces/mrtrix3/tracking.py index 82c7294cfc..f2cc9c7c75 100644 --- a/nipype/interfaces/mrtrix3/tracking.py +++ b/nipype/interfaces/mrtrix3/tracking.py @@ -227,7 +227,7 @@ class Tractography(MRTrix3Base): >>> tk.inputs.in_file = 'fods.mif' >>> tk.inputs.roi_mask = 'mask.nii.gz' >>> tk.inputs.seed_sphere = (80, 100, 70, 10) - >>> tk.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> tk.cmdline # doctest: +ELLIPSIS 'tckgen -algorithm iFOD2 -mask mask.nii.gz -seed_sphere \ 80.000000,100.000000,70.000000,10.000000 fods.mif tracked.tck' >>> tk.run() # doctest: +SKIP diff --git a/nipype/interfaces/mrtrix3/utils.py b/nipype/interfaces/mrtrix3/utils.py index 99f308bd18..42f3d0c6fd 100644 --- a/nipype/interfaces/mrtrix3/utils.py +++ b/nipype/interfaces/mrtrix3/utils.py @@ -46,7 +46,7 @@ class BrainMask(CommandLine): >>> import nipype.interfaces.mrtrix3 as mrt >>> bmsk = mrt.BrainMask() >>> bmsk.inputs.in_file = 'dwi.mif' - >>> bmsk.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> bmsk.cmdline # doctest: +ELLIPSIS 'dwi2mask dwi.mif brainmask.mif' >>> bmsk.run() # doctest: +SKIP """ @@ -93,7 +93,7 @@ class Mesh2PVE(CommandLine): >>> m2p.inputs.in_file = 'surf1.vtk' >>> m2p.inputs.reference = 'dwi.mif' >>> m2p.inputs.in_first = 'T1.nii.gz' - >>> m2p.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> m2p.cmdline # doctest: +ELLIPSIS 'mesh2pve -first T1.nii.gz surf1.vtk dwi.mif mesh2volume.nii.gz' >>> m2p.run() # doctest: +SKIP """ @@ -139,7 +139,7 @@ class Generate5tt(CommandLine): >>> seg.inputs.in_fast = ['tpm_00.nii.gz', ... 'tpm_01.nii.gz', 'tpm_02.nii.gz'] >>> seg.inputs.in_first = 'first_merged.nii.gz' - >>> seg.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> seg.cmdline # doctest: +ELLIPSIS '5ttgen tpm_00.nii.gz tpm_01.nii.gz tpm_02.nii.gz first_merged.nii.gz\ act-5tt.mif' >>> seg.run() # doctest: +SKIP @@ -197,7 +197,7 @@ class TensorMetrics(CommandLine): >>> comp = mrt.TensorMetrics() >>> comp.inputs.in_file = 'dti.mif' >>> comp.inputs.out_fa = 'fa.mif' - >>> comp.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> comp.cmdline # doctest: +ELLIPSIS 'tensor2metric -fa fa.mif dti.mif' >>> comp.run() # doctest: +SKIP """ @@ -337,7 +337,7 @@ class ComputeTDI(MRTrix3Base): >>> import nipype.interfaces.mrtrix3 as mrt >>> tdi = mrt.ComputeTDI() >>> tdi.inputs.in_file = 'dti.mif' - >>> tdi.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> tdi.cmdline # doctest: +ELLIPSIS 'tckmap dti.mif tdi.mif' >>> tdi.run() # doctest: +SKIP """ @@ -388,7 +388,7 @@ class TCK2VTK(MRTrix3Base): >>> vtk = mrt.TCK2VTK() >>> vtk.inputs.in_file = 'tracks.tck' >>> vtk.inputs.reference = 'b0.nii' - >>> vtk.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> vtk.cmdline # doctest: +ELLIPSIS 'tck2vtk -image b0.nii tracks.tck tracks.vtk' >>> vtk.run() # doctest: +SKIP """ diff --git a/nipype/interfaces/niftyfit/asl.py b/nipype/interfaces/niftyfit/asl.py index f0cc8bc19b..366f9a6eca 100644 --- a/nipype/interfaces/niftyfit/asl.py +++ b/nipype/interfaces/niftyfit/asl.py @@ -147,7 +147,7 @@ class FitAsl(NiftyFitCommand): >>> from nipype.interfaces import niftyfit >>> node = niftyfit.FitAsl() >>> node.inputs.source_file = 'asl.nii.gz' - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'fit_asl -source asl.nii.gz -cbf asl_cbf.nii.gz -error asl_error.nii.gz \ -syn asl_syn.nii.gz' diff --git a/nipype/interfaces/niftyfit/dwi.py b/nipype/interfaces/niftyfit/dwi.py index e368726656..67c5444bbe 100644 --- a/nipype/interfaces/niftyfit/dwi.py +++ b/nipype/interfaces/niftyfit/dwi.py @@ -248,7 +248,7 @@ class FitDwi(NiftyFitCommand): >>> fit_dwi.inputs.bvec_file = 'bvecs' >>> fit_dwi.inputs.bval_file = 'bvals' >>> fit_dwi.inputs.rgbmap_file = 'rgb.nii.gz' - >>> fit_dwi.cmdline # doctest: +ALLOW_UNICODE + >>> fit_dwi.cmdline 'fit_dwi -source dwi.nii.gz -bval bvals -bvec bvecs -dti \ -error dwi_error.nii.gz -famap dwi_famap.nii.gz -mcmap dwi_mcmap.nii.gz \ -mcout dwi_mcout.txt -mdmap dwi_mdmap.nii.gz -nodiff dwi_no_diff.nii.gz \ @@ -427,7 +427,7 @@ class DwiTool(NiftyFitCommand): >>> dwi_tool.inputs.mask_file = 'mask.nii.gz' >>> dwi_tool.inputs.b0_file = 'b0.nii.gz' >>> dwi_tool.inputs.rgbmap_file = 'rgb_map.nii.gz' - >>> dwi_tool.cmdline # doctest: +ALLOW_UNICODE + >>> dwi_tool.cmdline 'dwi_tool -source dwi.nii.gz -bval bvals -bvec bvecs -b0 b0.nii.gz \ -mask mask.nii.gz -dti -famap dwi_famap.nii.gz -logdti2 dwi_logdti2.nii.gz \ -mcmap dwi_mcmap.nii.gz -mdmap dwi_mdmap.nii.gz -rgbmap rgb_map.nii.gz \ diff --git a/nipype/interfaces/niftyfit/qt1.py b/nipype/interfaces/niftyfit/qt1.py index 6cb0cf7da1..b5ccfed88b 100644 --- a/nipype/interfaces/niftyfit/qt1.py +++ b/nipype/interfaces/niftyfit/qt1.py @@ -165,7 +165,7 @@ class FitQt1(NiftyFitCommand): >>> from nipype.interfaces.niftyfit import FitQt1 >>> fit_qt1 = FitQt1() >>> fit_qt1.inputs.source_file = 'TI4D.nii.gz' - >>> fit_qt1.cmdline # doctest: +ALLOW_UNICODE + >>> fit_qt1.cmdline 'fit_qt1 -source TI4D.nii.gz -comp TI4D_comp.nii.gz \ -error TI4D_error.nii.gz -m0map TI4D_m0map.nii.gz -mcmap TI4D_mcmap.nii.gz \ -res TI4D_res.nii.gz -syn TI4D_syn.nii.gz -t1map TI4D_t1map.nii.gz' diff --git a/nipype/interfaces/niftyreg/reg.py b/nipype/interfaces/niftyreg/reg.py index e8ad87e3ee..fa4a1701ee 100644 --- a/nipype/interfaces/niftyreg/reg.py +++ b/nipype/interfaces/niftyreg/reg.py @@ -156,7 +156,7 @@ class RegAladin(NiftyRegCommand): >>> node.inputs.flo_file = 'im2.nii' >>> node.inputs.rmask_file = 'mask.nii' >>> node.inputs.omp_core_val = 4 - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'reg_aladin -aff im2_aff.txt -flo im2.nii -omp 4 -ref im1.nii \ -res im2_res.nii.gz -rmask mask.nii' @@ -367,7 +367,7 @@ class RegF3D(NiftyRegCommand): >>> node.inputs.flo_file = 'im2.nii' >>> node.inputs.rmask_file = 'mask.nii' >>> node.inputs.omp_core_val = 4 - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'reg_f3d -cpp im2_cpp.nii.gz -flo im2.nii -omp 4 -ref im1.nii \ -res im2_res.nii.gz -rmask mask.nii' diff --git a/nipype/interfaces/niftyreg/regutils.py b/nipype/interfaces/niftyreg/regutils.py index 9c2ddc055d..214ccc9a45 100644 --- a/nipype/interfaces/niftyreg/regutils.py +++ b/nipype/interfaces/niftyreg/regutils.py @@ -106,7 +106,7 @@ class RegResample(NiftyRegCommand): >>> node.inputs.trans_file = 'warpfield.nii' >>> node.inputs.inter_val = 'LIN' >>> node.inputs.omp_core_val = 4 - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'reg_resample -flo im2.nii -inter 1 -omp 4 -ref im1.nii -trans \ warpfield.nii -res im2_res.nii.gz' @@ -173,7 +173,7 @@ class RegJacobian(NiftyRegCommand): >>> node.inputs.ref_file = 'im1.nii' >>> node.inputs.trans_file = 'warpfield.nii' >>> node.inputs.omp_core_val = 4 - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'reg_jacobian -omp 4 -ref im1.nii -trans warpfield.nii -jac \ warpfield_jac.nii.gz' @@ -289,7 +289,7 @@ class RegTools(NiftyRegCommand): >>> node.inputs.in_file = 'im1.nii' >>> node.inputs.mul_val = 4 >>> node.inputs.omp_core_val = 4 - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'reg_tools -in im1.nii -mul 4.0 -omp 4 -out im1_tools.nii.gz' """ @@ -391,15 +391,27 @@ class RegAverage(NiftyRegCommand): Examples -------- + + .. testsetup:: + + >>> tmp = getfixture('tmpdir') + >>> old = tmp.chdir() # changing to temporary file + + .. doctest:: + >>> from nipype.interfaces import niftyreg >>> node = niftyreg.RegAverage() >>> one_file = 'im1.nii' >>> two_file = 'im2.nii' >>> three_file = 'im3.nii' >>> node.inputs.avg_files = [one_file, two_file, three_file] - >>> node.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> node.cmdline # doctest: +ELLIPSIS 'reg_average --cmd_file .../reg_average_cmd' + .. testsetup:: + + >>> os.chdir(old.strpath) + """ _cmd = get_custom_path('reg_average') input_spec = RegAverageInputSpec @@ -602,7 +614,7 @@ class RegTransform(NiftyRegCommand): >>> node = niftyreg.RegTransform() >>> node.inputs.def_input = 'warpfield.nii' >>> node.inputs.omp_core_val = 4 - >>> node.cmdline # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> node.cmdline # doctest: +ELLIPSIS 'reg_transform -omp 4 -def warpfield.nii .../warpfield_trans.nii.gz' """ @@ -714,7 +726,7 @@ class RegMeasure(NiftyRegCommand): >>> node.inputs.flo_file = 'im2.nii' >>> node.inputs.measure_type = 'lncc' >>> node.inputs.omp_core_val = 4 - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'reg_measure -flo im2.nii -lncc -omp 4 -out im2_lncc.txt -ref im1.nii' """ diff --git a/nipype/interfaces/niftyseg/em.py b/nipype/interfaces/niftyseg/em.py index be39f7775b..f2e7359677 100644 --- a/nipype/interfaces/niftyseg/em.py +++ b/nipype/interfaces/niftyseg/em.py @@ -127,7 +127,7 @@ class EM(NiftySegCommand): >>> node = niftyseg.EM() >>> node.inputs.in_file = 'im1.nii' >>> node.inputs.no_prior = 4 - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'seg_EM -in im1.nii -nopriors 4 -bc_out im1_bc_em.nii.gz -out im1_em.nii.gz -out_outlier im1_outlier_em.nii.gz' """ diff --git a/nipype/interfaces/niftyseg/label_fusion.py b/nipype/interfaces/niftyseg/label_fusion.py index 82b19d1f3b..c1637cb258 100644 --- a/nipype/interfaces/niftyseg/label_fusion.py +++ b/nipype/interfaces/niftyseg/label_fusion.py @@ -147,7 +147,7 @@ class LabelFusion(NiftySegCommand): >>> node.inputs.template_file = 'im3.nii' >>> node.inputs.template_num = 2 >>> node.inputs.classifier_type = 'STEPS' - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'seg_LabFusion -in im1.nii -STEPS 2.000000 2 im2.nii im3.nii -out im1_steps.nii' """ @@ -298,7 +298,7 @@ class CalcTopNCC(NiftySegCommand): >>> node.inputs.num_templates = 2 >>> node.inputs.in_templates = ['im2.nii', 'im3.nii'] >>> node.inputs.top_templates = 1 - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'seg_CalcTopNCC -target im1.nii -templates 2 im2.nii im3.nii -n 1' """ diff --git a/nipype/interfaces/niftyseg/lesions.py b/nipype/interfaces/niftyseg/lesions.py index d531b5c464..489837e6dd 100644 --- a/nipype/interfaces/niftyseg/lesions.py +++ b/nipype/interfaces/niftyseg/lesions.py @@ -109,7 +109,7 @@ class FillLesions(NiftySegCommand): >>> node = niftyseg.FillLesions() >>> node.inputs.in_file = 'im1.nii' >>> node.inputs.lesion_mask = 'im2.nii' - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'seg_FillLesions -i im1.nii -l im2.nii -o im1_lesions_filled.nii.gz' """ diff --git a/nipype/interfaces/niftyseg/maths.py b/nipype/interfaces/niftyseg/maths.py index bd05ab5df3..b8a5c0a1b8 100644 --- a/nipype/interfaces/niftyseg/maths.py +++ b/nipype/interfaces/niftyseg/maths.py @@ -169,31 +169,31 @@ class UnaryMaths(MathsCommand): >>> # Test sqrt operation >>> unary_sqrt = copy.deepcopy(unary) >>> unary_sqrt.inputs.operation = 'sqrt' - >>> unary_sqrt.cmdline # doctest: +ALLOW_UNICODE + >>> unary_sqrt.cmdline 'seg_maths im1.nii -sqrt -odt float im1_sqrt.nii' >>> unary_sqrt.run() # doctest: +SKIP >>> # Test sqrt operation >>> unary_abs = copy.deepcopy(unary) >>> unary_abs.inputs.operation = 'abs' - >>> unary_abs.cmdline # doctest: +ALLOW_UNICODE + >>> unary_abs.cmdline 'seg_maths im1.nii -abs -odt float im1_abs.nii' >>> unary_abs.run() # doctest: +SKIP >>> # Test bin operation >>> unary_bin = copy.deepcopy(unary) >>> unary_bin.inputs.operation = 'bin' - >>> unary_bin.cmdline # doctest: +ALLOW_UNICODE + >>> unary_bin.cmdline 'seg_maths im1.nii -bin -odt float im1_bin.nii' >>> unary_bin.run() # doctest: +SKIP >>> # Test otsu operation >>> unary_otsu = copy.deepcopy(unary) >>> unary_otsu.inputs.operation = 'otsu' - >>> unary_otsu.cmdline # doctest: +ALLOW_UNICODE + >>> unary_otsu.cmdline 'seg_maths im1.nii -otsu -odt float im1_otsu.nii' >>> unary_otsu.run() # doctest: +SKIP >>> # Test isnan operation >>> unary_isnan = copy.deepcopy(unary) >>> unary_isnan.inputs.operation = 'isnan' - >>> unary_isnan.cmdline # doctest: +ALLOW_UNICODE + >>> unary_isnan.cmdline 'seg_maths im1.nii -isnan -odt float im1_isnan.nii' >>> unary_isnan.run() # doctest: +SKIP @@ -302,28 +302,28 @@ class BinaryMaths(MathsCommand): >>> binary_sub = copy.deepcopy(binary) >>> binary_sub.inputs.operation = 'sub' >>> binary_sub.inputs.operand_file = 'im2.nii' - >>> binary_sub.cmdline # doctest: +ALLOW_UNICODE + >>> binary_sub.cmdline 'seg_maths im1.nii -sub im2.nii -odt float im1_sub.nii' >>> binary_sub.run() # doctest: +SKIP >>> # Test mul operation >>> binary_mul = copy.deepcopy(binary) >>> binary_mul.inputs.operation = 'mul' >>> binary_mul.inputs.operand_value = 2.0 - >>> binary_mul.cmdline # doctest: +ALLOW_UNICODE + >>> binary_mul.cmdline 'seg_maths im1.nii -mul 2.00000000 -odt float im1_mul.nii' >>> binary_mul.run() # doctest: +SKIP >>> # Test llsnorm operation >>> binary_llsnorm = copy.deepcopy(binary) >>> binary_llsnorm.inputs.operation = 'llsnorm' >>> binary_llsnorm.inputs.operand_file = 'im2.nii' - >>> binary_llsnorm.cmdline # doctest: +ALLOW_UNICODE + >>> binary_llsnorm.cmdline 'seg_maths im1.nii -llsnorm im2.nii -odt float im1_llsnorm.nii' >>> binary_llsnorm.run() # doctest: +SKIP >>> # Test splitinter operation >>> binary_splitinter = copy.deepcopy(binary) >>> binary_splitinter.inputs.operation = 'splitinter' >>> binary_splitinter.inputs.operand_str = 'z' - >>> binary_splitinter.cmdline # doctest: +ALLOW_UNICODE + >>> binary_splitinter.cmdline 'seg_maths im1.nii -splitinter z -odt float im1_splitinter.nii' >>> binary_splitinter.run() # doctest: +SKIP @@ -419,21 +419,21 @@ class BinaryMathsInteger(MathsCommand): >>> binaryi_dil = copy.deepcopy(binaryi) >>> binaryi_dil.inputs.operation = 'dil' >>> binaryi_dil.inputs.operand_value = 2 - >>> binaryi_dil.cmdline # doctest: +ALLOW_UNICODE + >>> binaryi_dil.cmdline 'seg_maths im1.nii -dil 2 -odt float im1_dil.nii' >>> binaryi_dil.run() # doctest: +SKIP >>> # Test dil operation >>> binaryi_ero = copy.deepcopy(binaryi) >>> binaryi_ero.inputs.operation = 'ero' >>> binaryi_ero.inputs.operand_value = 1 - >>> binaryi_ero.cmdline # doctest: +ALLOW_UNICODE + >>> binaryi_ero.cmdline 'seg_maths im1.nii -ero 1 -odt float im1_ero.nii' >>> binaryi_ero.run() # doctest: +SKIP >>> # Test pad operation >>> binaryi_pad = copy.deepcopy(binaryi) >>> binaryi_pad.inputs.operation = 'pad' >>> binaryi_pad.inputs.operand_value = 4 - >>> binaryi_pad.cmdline # doctest: +ALLOW_UNICODE + >>> binaryi_pad.cmdline 'seg_maths im1.nii -pad 4 -odt float im1_pad.nii' >>> binaryi_pad.run() # doctest: +SKIP @@ -512,7 +512,7 @@ class TupleMaths(MathsCommand): >>> tuple_lncc.inputs.operation = 'lncc' >>> tuple_lncc.inputs.operand_file1 = 'im2.nii' >>> tuple_lncc.inputs.operand_value2 = 2.0 - >>> tuple_lncc.cmdline # doctest: +ALLOW_UNICODE + >>> tuple_lncc.cmdline 'seg_maths im1.nii -lncc im2.nii 2.00000000 -odt float im1_lncc.nii' >>> tuple_lncc.run() # doctest: +SKIP @@ -521,7 +521,7 @@ class TupleMaths(MathsCommand): >>> tuple_lssd.inputs.operation = 'lssd' >>> tuple_lssd.inputs.operand_file1 = 'im2.nii' >>> tuple_lssd.inputs.operand_value2 = 1.0 - >>> tuple_lssd.cmdline # doctest: +ALLOW_UNICODE + >>> tuple_lssd.cmdline 'seg_maths im1.nii -lssd im2.nii 1.00000000 -odt float im1_lssd.nii' >>> tuple_lssd.run() # doctest: +SKIP @@ -530,7 +530,7 @@ class TupleMaths(MathsCommand): >>> tuple_lltsnorm.inputs.operation = 'lltsnorm' >>> tuple_lltsnorm.inputs.operand_file1 = 'im2.nii' >>> tuple_lltsnorm.inputs.operand_value2 = 0.01 - >>> tuple_lltsnorm.cmdline # doctest: +ALLOW_UNICODE + >>> tuple_lltsnorm.cmdline 'seg_maths im1.nii -lltsnorm im2.nii 0.01000000 -odt float \ im1_lltsnorm.nii' >>> tuple_lltsnorm.run() # doctest: +SKIP @@ -575,7 +575,7 @@ class Merge(MathsCommand): >>> node.inputs.merge_files = files >>> node.inputs.dimension = 2 >>> node.inputs.output_datatype = 'float' - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'seg_maths im1.nii -merge 2 2 im2.nii im3.nii -odt float im1_merged.nii' """ diff --git a/nipype/interfaces/niftyseg/patchmatch.py b/nipype/interfaces/niftyseg/patchmatch.py index d598a08928..207764f086 100644 --- a/nipype/interfaces/niftyseg/patchmatch.py +++ b/nipype/interfaces/niftyseg/patchmatch.py @@ -102,7 +102,7 @@ class PatchMatch(NiftySegCommand): >>> node.inputs.in_file = 'im1.nii' >>> node.inputs.mask_file = 'im2.nii' >>> node.inputs.database_file = 'db.xml' - >>> node.cmdline # doctest: +ALLOW_UNICODE + >>> node.cmdline 'seg_PatchMatch -i im1.nii -m im2.nii -db db.xml -o im1_pm.nii.gz' """ diff --git a/nipype/interfaces/niftyseg/stats.py b/nipype/interfaces/niftyseg/stats.py index e2e7781aa6..cef03b6177 100644 --- a/nipype/interfaces/niftyseg/stats.py +++ b/nipype/interfaces/niftyseg/stats.py @@ -154,19 +154,19 @@ class UnaryStats(StatsCommand): >>> # Test v operation >>> unary_v = copy.deepcopy(unary) >>> unary_v.inputs.operation = 'v' - >>> unary_v.cmdline # doctest: +ALLOW_UNICODE + >>> unary_v.cmdline 'seg_stats im1.nii -v' >>> unary_v.run() # doctest: +SKIP >>> # Test vl operation >>> unary_vl = copy.deepcopy(unary) >>> unary_vl.inputs.operation = 'vl' - >>> unary_vl.cmdline # doctest: +ALLOW_UNICODE + >>> unary_vl.cmdline 'seg_stats im1.nii -vl' >>> unary_vl.run() # doctest: +SKIP >>> # Test x operation >>> unary_x = copy.deepcopy(unary) >>> unary_x.inputs.operation = 'x' - >>> unary_x.cmdline # doctest: +ALLOW_UNICODE + >>> unary_x.cmdline 'seg_stats im1.nii -x' >>> unary_x.run() # doctest: +SKIP @@ -243,21 +243,21 @@ class BinaryStats(StatsCommand): >>> binary_sa = copy.deepcopy(binary) >>> binary_sa.inputs.operation = 'sa' >>> binary_sa.inputs.operand_value = 2.0 - >>> binary_sa.cmdline # doctest: +ALLOW_UNICODE + >>> binary_sa.cmdline 'seg_stats im1.nii -sa 2.00000000' >>> binary_sa.run() # doctest: +SKIP >>> # Test ncc operation >>> binary_ncc = copy.deepcopy(binary) >>> binary_ncc.inputs.operation = 'ncc' >>> binary_ncc.inputs.operand_file = 'im2.nii' - >>> binary_ncc.cmdline # doctest: +ALLOW_UNICODE + >>> binary_ncc.cmdline 'seg_stats im1.nii -ncc im2.nii' >>> binary_ncc.run() # doctest: +SKIP >>> # Test Nl operation >>> binary_nl = copy.deepcopy(binary) >>> binary_nl.inputs.operation = 'Nl' >>> binary_nl.inputs.operand_file = 'output.csv' - >>> binary_nl.cmdline # doctest: +ALLOW_UNICODE + >>> binary_nl.cmdline 'seg_stats im1.nii -Nl output.csv' >>> binary_nl.run() # doctest: +SKIP diff --git a/nipype/interfaces/nilearn.py b/nipype/interfaces/nilearn.py index e7984c654a..db47b57e8b 100644 --- a/nipype/interfaces/nilearn.py +++ b/nipype/interfaces/nilearn.py @@ -21,7 +21,7 @@ from .. import logging from ..interfaces.base import (traits, TraitedSpec, BaseInterface, BaseInterfaceInputSpec, File, InputMultiPath) -IFLOG = logging.getLogger('interface') +IFLOGGER = logging.getLogger('interface') class SignalExtractionInputSpec(BaseInterfaceInputSpec): in_file = File(exists=True, mandatory=True, desc='4-D fMRI nii file') diff --git a/nipype/interfaces/nitime/tests/test_nitime.py b/nipype/interfaces/nitime/tests/test_nitime.py index fa6ace4014..d37fea4f4f 100644 --- a/nipype/interfaces/nitime/tests/test_nitime.py +++ b/nipype/interfaces/nitime/tests/test_nitime.py @@ -30,11 +30,12 @@ def test_read_csv(): @pytest.mark.skipif(no_nitime, reason="nitime is not installed") -def test_coherence_analysis(): +def test_coherence_analysis(tmpdir): """Test that the coherence analyzer works """ import nitime.analysis as nta import nitime.timeseries as ts + tmpdir.chdir() # This is the nipype interface analysis: CA = nitime.CoherenceAnalyzer() CA.inputs.TR = 1.89 diff --git a/nipype/interfaces/quickshear.py b/nipype/interfaces/quickshear.py index d1782d5755..a0e9c79a1c 100644 --- a/nipype/interfaces/quickshear.py +++ b/nipype/interfaces/quickshear.py @@ -40,7 +40,7 @@ class Quickshear(CommandLine): >>> from nipype.interfaces.quickshear import Quickshear >>> qs = Quickshear(in_file='T1.nii', mask_file='brain_mask.nii') - >>> qs.cmdline # doctest: +ALLOW_UNICODE + >>> qs.cmdline 'quickshear T1.nii brain_mask.nii T1_defaced.nii' In the absence of a precomputed mask, a simple pipeline can be generated diff --git a/nipype/interfaces/slicer/generate_classes.py b/nipype/interfaces/slicer/generate_classes.py index 77a633f5f8..f0bc8274bb 100644 --- a/nipype/interfaces/slicer/generate_classes.py +++ b/nipype/interfaces/slicer/generate_classes.py @@ -18,9 +18,9 @@ def force_to_valid_python_variable_name(old_name): """ Valid c++ names are not always valid in python, so provide alternate naming - >>> force_to_valid_python_variable_name('lambda') # doctest: +ALLOW_UNICODE + >>> force_to_valid_python_variable_name('lambda') 'opt_lambda' - >>> force_to_valid_python_variable_name('inputVolume') # doctest: +ALLOW_UNICODE + >>> force_to_valid_python_variable_name('inputVolume') 'inputVolume' """ new_name = old_name diff --git a/nipype/interfaces/spm/model.py b/nipype/interfaces/spm/model.py index ddf35ef449..8ddc06a9b0 100644 --- a/nipype/interfaces/spm/model.py +++ b/nipype/interfaces/spm/model.py @@ -32,7 +32,7 @@ scans_for_fnames, ImageFileSPM) __docformat__ = 'restructuredtext' -logger = logging.getLogger('interface') +iflogger = logging.getLogger('interface') class Level1DesignInputSpec(SPMCommandInputSpec): diff --git a/nipype/interfaces/tests/test_base.py b/nipype/interfaces/tests/test_base.py index 995ee2e45b..48a44ad6a4 100644 --- a/nipype/interfaces/tests/test_base.py +++ b/nipype/interfaces/tests/test_base.py @@ -70,14 +70,14 @@ def test_bunch_hash(): @pytest.fixture(scope="module") def setup_file(request, tmpdir_factory): - tmp_dir = str(tmpdir_factory.mktemp('files')) - tmp_infile = os.path.join(tmp_dir, 'foo.txt') - with open(tmp_infile, 'w') as fp: + tmp_dir = tmpdir_factory.mktemp('files') + tmp_infile = tmp_dir.join('foo.txt') + with tmp_infile.open('w') as fp: fp.writelines([u'123456789']) - os.chdir(tmp_dir) + tmp_dir.chdir() - return tmp_infile + return tmp_infile.strpath def test_TraitedSpec(): @@ -412,7 +412,7 @@ def _run_interface(self, runtime): def test_BaseInterface_load_save_inputs(tmpdir): - tmp_json = os.path.join(str(tmpdir), 'settings.json') + tmp_json = tmpdir.join('settings.json').strpath class InputSpec(nib.TraitedSpec): input1 = nib.traits.Int() diff --git a/nipype/interfaces/tests/test_io.py b/nipype/interfaces/tests/test_io.py index 4fade26800..ff56c9ec9d 100644 --- a/nipype/interfaces/tests/test_io.py +++ b/nipype/interfaces/tests/test_io.py @@ -43,7 +43,6 @@ except CalledProcessError: fakes3 = False -from tempfile import mkstemp, mkdtemp def test_datagrabber(): dg = nio.DataGrabber() @@ -117,7 +116,7 @@ def test_s3datagrabber_communication(tmpdir): dg.inputs.anon = True dg.inputs.bucket = 'openfmri' dg.inputs.bucket_path = 'ds001/' - dg.inputs.local_directory = str(tmpdir) + dg.inputs.local_directory = tmpdir.strpath dg.inputs.sort_filelist = True dg.inputs.template = '*' dg.inputs.field_template = dict(func='%s/BOLD/task001_%s/bold.nii.gz', @@ -147,7 +146,7 @@ def test_datagrabber_order(tmpdir): tmpdir.join(file_name).open('a').close() dg = nio.DataGrabber(infields=['sid']) - dg.inputs.base_directory = str(tmpdir) + dg.inputs.base_directory = tmpdir.strpath dg.inputs.template = '%s_L%d_R*.q*' dg.inputs.template_args = {'outfiles': [['sid', 1], ['sid', 2], ['sid', 3]]} @@ -185,6 +184,7 @@ def dummy_input(request, tmpdir_factory): Function to create a dummy file ''' # Init variables + input_path = tmpdir_factory.mktemp('input_data').join('datasink_test_s3.txt') # Create input file @@ -208,7 +208,7 @@ def test_datasink_to_s3(dummy_input, tmpdir): attr_folder = 'text_file' output_dir = 's3://' + bucket_name # Local temporary filepaths for testing - fakes3_dir = str(tmpdir) + fakes3_dir = tmpdir.strpath input_path = dummy_input # Start up fake-S3 server @@ -280,7 +280,7 @@ def test_datasink_localcopy(dummy_input, tmpdir): ''' # Init variables - local_dir = str(tmpdir) + local_dir = tmpdir.strpath container = 'outputs' attr_folder = 'text_file' @@ -335,42 +335,41 @@ def test_datasink_substitutions(tmpdir): x in glob.glob(os.path.join(str(outdir), '*'))]) \ == ['!-yz-b.n', 'ABABAB.n'] # so we got re used 2nd and both patterns - -def _temp_analyze_files(): +@pytest.fixture() +def _temp_analyze_files(tmpdir): """Generate temporary analyze file pair.""" - fd, orig_img = mkstemp(suffix='.img', dir=mkdtemp()) - orig_hdr = orig_img[:-4] + '.hdr' - fp = open(orig_hdr, 'w+') - fp.close() - return orig_img, orig_hdr + img_dir = tmpdir.mkdir("img") + orig_img = img_dir.join("orig.img") + orig_hdr = img_dir.join("orig.hdr") + orig_img.open('w') + orig_hdr.open('w') + return orig_img.strpath, orig_hdr.strpath -def test_datasink_copydir(): - orig_img, orig_hdr = _temp_analyze_files() - outdir = mkdtemp() +def test_datasink_copydir_1(_temp_analyze_files, tmpdir): + orig_img, orig_hdr = _temp_analyze_files + outdir = tmpdir pth, fname = os.path.split(orig_img) - ds = nio.DataSink(base_directory=outdir, parameterization=False) + ds = nio.DataSink(base_directory=outdir.mkdir("basedir").strpath, parameterization=False) setattr(ds.inputs, '@outdir', pth) ds.run() sep = os.path.sep - file_exists = lambda: os.path.exists(os.path.join(outdir, - pth.split(sep)[-1], - fname)) - assert file_exists() - shutil.rmtree(pth) + assert tmpdir.join('basedir', pth.split(sep)[-1], fname).check() - orig_img, orig_hdr = _temp_analyze_files() +def test_datasink_copydir_2(_temp_analyze_files, tmpdir): + orig_img, orig_hdr = _temp_analyze_files pth, fname = os.path.split(orig_img) + ds = nio.DataSink(base_directory=tmpdir.mkdir("basedir").strpath, parameterization=False) ds.inputs.remove_dest_dir = True setattr(ds.inputs, 'outdir', pth) ds.run() - assert not file_exists() - shutil.rmtree(outdir) - shutil.rmtree(pth) + sep = os.path.sep + assert not tmpdir.join('basedir', pth.split(sep)[-1], fname).check() + assert tmpdir.join('basedir', 'outdir', pth.split(sep)[-1], fname).check() def test_datafinder_depth(tmpdir): - outdir = str(tmpdir) + outdir = tmpdir.strpath os.makedirs(os.path.join(outdir, '0', '1', '2', '3')) df = nio.DataFinder() @@ -387,7 +386,7 @@ def test_datafinder_depth(tmpdir): def test_datafinder_unpack(tmpdir): - outdir = str(tmpdir) + outdir = tmpdir.strpath single_res = os.path.join(outdir, "findme.txt") open(single_res, 'a').close() open(os.path.join(outdir, "dontfindme"), 'a').close() @@ -408,7 +407,7 @@ def test_freesurfersource(): assert fss.inputs.subjects_dir == Undefined -def test_jsonsink_input(tmpdir): +def test_jsonsink_input(): ds = nio.JSONFileSink() assert ds.inputs._outputs == {} @@ -425,7 +424,7 @@ def test_jsonsink_input(tmpdir): {'new_entry' : 'someValue', 'test' : 'testInfields'} ]) def test_jsonsink(tmpdir, inputs_attributes): - os.chdir(str(tmpdir)) + tmpdir.chdir() js = nio.JSONFileSink(infields=['test'], in_dict={'foo': 'var'}) setattr(js.inputs, 'contrasts.alt', 'someNestedValue') expected_data = {"contrasts": {"alt": "someNestedValue"}, "foo": "var"} diff --git a/nipype/interfaces/tests/test_matlab.py b/nipype/interfaces/tests/test_matlab.py index 33f80c0fa1..25b5ac964f 100644 --- a/nipype/interfaces/tests/test_matlab.py +++ b/nipype/interfaces/tests/test_matlab.py @@ -2,8 +2,6 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os -from tempfile import mkdtemp -from shutil import rmtree import pytest import nipype.interfaces.matlab as mlab @@ -70,7 +68,7 @@ def test_mlab_init(): @pytest.mark.skipif(no_matlab, reason="matlab is not available") -def test_run_interface(): +def test_run_interface(tmpdir): default_script_file = clean_workspace_and_get_default_script_file() mc = mlab.MatlabCommand(matlab_cmd='foo_m') @@ -89,12 +87,10 @@ def test_run_interface(): if os.path.exists(default_script_file): # cleanup os.remove(default_script_file) - cwd = os.getcwd() - basedir = mkdtemp() - os.chdir(basedir) + cwd = tmpdir.chdir() # bypasses ubuntu dash issue - mc = mlab.MatlabCommand(script='foo;', paths=[basedir], mfile=True) + mc = mlab.MatlabCommand(script='foo;', paths=[tmpdir.strpath], mfile=True) assert not os.path.exists(default_script_file), 'scriptfile should not exist 4.' with pytest.raises(RuntimeError): mc.run() @@ -103,11 +99,10 @@ def test_run_interface(): os.remove(default_script_file) # bypasses ubuntu dash issue - res = mlab.MatlabCommand(script='a=1;', paths=[basedir], mfile=True).run() + res = mlab.MatlabCommand(script='a=1;', paths=[tmpdir.strpath], mfile=True).run() assert res.runtime.returncode == 0 assert os.path.exists(default_script_file), 'scriptfile should exist 5.' - os.chdir(cwd) - rmtree(basedir) + cwd.chdir() @pytest.mark.skipif(no_matlab, reason="matlab is not available") diff --git a/nipype/interfaces/tests/test_nilearn.py b/nipype/interfaces/tests/test_nilearn.py index 4e8299aa74..ce3846a6d3 100644 --- a/nipype/interfaces/tests/test_nilearn.py +++ b/nipype/interfaces/tests/test_nilearn.py @@ -1,8 +1,6 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os -import tempfile -import shutil import numpy as np @@ -33,13 +31,14 @@ class TestSignalExtraction(): labels = ['CSF', 'GrayMatter', 'WhiteMatter'] global_labels = ['GlobalSignal'] + labels - def setup_class(self): - self.orig_dir = os.getcwd() - self.temp_dir = tempfile.mkdtemp() - os.chdir(self.temp_dir) + @pytest.fixture(autouse=True, scope='class') + def setup_class(self, tmpdir_factory): + tempdir = tmpdir_factory.mktemp("test") + self.orig_dir = tempdir.chdir() utils.save_toy_nii(self.fake_fmri_data, self.filenames['in_file']) utils.save_toy_nii(self.fake_label_data, self.filenames['label_files']) + def test_signal_extract_no_shared(self): # run iface.SignalExtraction(in_file=self.filenames['in_file'], @@ -151,10 +150,9 @@ def assert_expected_output(self, labels, wanted): for j, segment in enumerate(time): npt.assert_almost_equal(segment, wanted[i][j], decimal=1) - - def teardown_class(self): - os.chdir(self.orig_dir) - shutil.rmtree(self.temp_dir) +#dj: self doesnt have orig_dir at this point, not sure how to change it. should work without it +# def teardown_class(self): +# self.orig_dir.chdir() fake_fmri_data = np.array([[[[2, -1, 4, -2, 3], diff --git a/nipype/interfaces/utility/base.py b/nipype/interfaces/utility/base.py index 60e4c4aa3f..ec744d9fce 100644 --- a/nipype/interfaces/utility/base.py +++ b/nipype/interfaces/utility/base.py @@ -2,15 +2,9 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ -Various utilities - - Change directory to provide relative paths for doctests - >>> import os - >>> filepath = os.path.dirname(os.path.realpath(__file__)) - >>> datadir = os.path.realpath(os.path.join(filepath, - ... '../../testing/data')) - >>> os.chdir(datadir) - + # changing to temporary directories + >>> tmp = getfixture('tmpdir') + >>> old = tmp.chdir() """ from __future__ import print_function, division, unicode_literals, absolute_import from builtins import range @@ -47,7 +41,7 @@ class IdentityInterface(IOBase): >>> out = ii.run() - >>> out.outputs.a # doctest: +ALLOW_UNICODE + >>> out.outputs.a 'foo' >>> ii2 = IdentityInterface(fields=['a', 'b'], mandatory_inputs=True) @@ -231,14 +225,14 @@ class Rename(IOBase): >>> from nipype.interfaces.utility import Rename >>> rename1 = Rename() - >>> rename1.inputs.in_file = "zstat1.nii.gz" + >>> rename1.inputs.in_file = os.path.join(datadir, "zstat1.nii.gz") # datadir is a directory with exemplary files, defined in conftest.py >>> rename1.inputs.format_string = "Faces-Scenes.nii.gz" >>> res = rename1.run() # doctest: +SKIP >>> res.outputs.out_file # doctest: +SKIP 'Faces-Scenes.nii.gz" # doctest: +SKIP >>> rename2 = Rename(format_string="%(subject_id)s_func_run%(run)02d") - >>> rename2.inputs.in_file = "functional.nii" + >>> rename2.inputs.in_file = os.path.join(datadir, "functional.nii") >>> rename2.inputs.keep_ext = True >>> rename2.inputs.subject_id = "subj_201" >>> rename2.inputs.run = 2 @@ -247,7 +241,7 @@ class Rename(IOBase): 'subj_201_func_run02.nii' # doctest: +SKIP >>> rename3 = Rename(format_string="%(subject_id)s_%(seq)s_run%(run)02d.nii") - >>> rename3.inputs.in_file = "func_epi_1_1.nii" + >>> rename3.inputs.in_file = os.path.join(datadir, "func_epi_1_1.nii") >>> rename3.inputs.parse_string = "func_(?P\w*)_.*" >>> rename3.inputs.subject_id = "subj_201" >>> rename3.inputs.run = 2 diff --git a/nipype/interfaces/utility/tests/test_base.py b/nipype/interfaces/utility/tests/test_base.py index 3d2fbd2b5f..3e66f827d2 100644 --- a/nipype/interfaces/utility/tests/test_base.py +++ b/nipype/interfaces/utility/tests/test_base.py @@ -11,13 +11,13 @@ def test_rename(tmpdir): - os.chdir(str(tmpdir)) + tmpdir.chdir() # Test very simple rename _ = open("file.txt", "w").close() rn = utility.Rename(in_file="file.txt", format_string="test_file1.txt") res = rn.run() - outfile = str(tmpdir.join("test_file1.txt")) + outfile = tmpdir.join("test_file1.txt").strpath assert res.outputs.out_file == outfile assert os.path.exists(outfile) @@ -31,7 +31,7 @@ def test_rename(tmpdir): rn.inputs.field1 = "test" rn.inputs.field2 = 2 res = rn.run() - outfile = str(tmpdir.join("test_file2.txt")) + outfile = tmpdir.join("test_file2.txt").strpath assert res.outputs.out_file == outfile assert os.path.exists(outfile) @@ -41,7 +41,7 @@ def test_rename(tmpdir): ({"squeeze" : True}, (0 , [1,2,3])) ]) def test_split(tmpdir, args, expected): - os.chdir(str(tmpdir)) + tmpdir.chdir() node = pe.Node(utility.Split(inlist=list(range(4)), splits=[1, 3], @@ -64,7 +64,7 @@ def test_split(tmpdir, args, expected): [[0, 2, 4], [1, 3, 5]]), ]) def test_merge(tmpdir, args, kwargs, in_lists, expected): - os.chdir(str(tmpdir)) + tmpdir.chdir() node = pe.Node(utility.Merge(*args, **kwargs), name='merge') diff --git a/nipype/interfaces/utility/tests/test_csv.py b/nipype/interfaces/utility/tests/test_csv.py index 86ac95a371..f0101b4da7 100644 --- a/nipype/interfaces/utility/tests/test_csv.py +++ b/nipype/interfaces/utility/tests/test_csv.py @@ -12,7 +12,7 @@ def test_csvReader(tmpdir): "bar,world,5\n", "baz,goodbye,0.3\n"] for x in range(2): - name = str(tmpdir.join("testfile.csv")) + name = tmpdir.join("testfile.csv").strpath with open(name, 'w') as fid: reader = utility.CSVReader() if x % 2 == 0: diff --git a/nipype/interfaces/utility/tests/test_wrappers.py b/nipype/interfaces/utility/tests/test_wrappers.py index 3384a5865c..b995dc27ad 100644 --- a/nipype/interfaces/utility/tests/test_wrappers.py +++ b/nipype/interfaces/utility/tests/test_wrappers.py @@ -16,7 +16,7 @@ def concat_sort(in_arrays): """ def test_function(tmpdir): - os.chdir(str(tmpdir)) + tmpdir.chdir() def gen_random_array(size): import numpy as np @@ -46,8 +46,8 @@ def make_random_array(size): return np.random.randn(size, size) -def should_fail(tmpdir): - os.chdir(tmpdir) +def should_fail(tmp): + tmp.chdir() node = pe.Node(utility.Function(input_names=["size"], output_names=["random_array"], @@ -59,11 +59,11 @@ def should_fail(tmpdir): def test_should_fail(tmpdir): with pytest.raises(NameError): - should_fail(str(tmpdir)) + should_fail(tmpdir) def test_function_with_imports(tmpdir): - os.chdir(str(tmpdir)) + tmpdir.chdir() node = pe.Node(utility.Function(input_names=["size"], output_names=["random_array"], @@ -79,7 +79,7 @@ def test_aux_connect_function(tmpdir): """ This tests excution nodes with multiple inputs and auxiliary function inside the Workflow connect function. """ - os.chdir(str(tmpdir)) + tmpdir.chdir() wf = pe.Workflow(name="test_workflow") diff --git a/nipype/interfaces/utility/wrappers.py b/nipype/interfaces/utility/wrappers.py index 2a5e163e7d..9999c4af6a 100644 --- a/nipype/interfaces/utility/wrappers.py +++ b/nipype/interfaces/utility/wrappers.py @@ -1,17 +1,12 @@ # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Various utilities - - Change directory to provide relative paths for doctests - >>> import os - >>> filepath = os.path.dirname(os.path.realpath(__file__)) - >>> datadir = os.path.realpath(os.path.join(filepath, - ... '../../testing/data')) - >>> os.chdir(datadir) - - """ +# changing to temporary directories + >>> tmp = getfixture('tmpdir') + >>> old = tmp.chdir() +""" + from __future__ import print_function, division, unicode_literals, absolute_import from future import standard_library @@ -26,7 +21,7 @@ from ...utils.filemanip import filename_to_list from ...utils.functions import getsource, create_function_from_source -logger = logging.getLogger('interface') +iflogger = logging.getLogger('interface') class FunctionInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): function_str = traits.Str(mandatory=True, desc='code for function') diff --git a/nipype/interfaces/vista/vista.py b/nipype/interfaces/vista/vista.py index e898956d65..e8928ae24a 100644 --- a/nipype/interfaces/vista/vista.py +++ b/nipype/interfaces/vista/vista.py @@ -34,7 +34,7 @@ class Vnifti2Image(CommandLine): >>> vimage = Vnifti2Image() >>> vimage.inputs.in_file = 'image.nii' - >>> vimage.cmdline # doctest: +ALLOW_UNICODE + >>> vimage.cmdline 'vnifti2image -in image.nii -out image.v' >>> vimage.run() # doctest: +SKIP """ @@ -63,7 +63,7 @@ class VtoMat(CommandLine): >>> vimage = VtoMat() >>> vimage.inputs.in_file = 'image.v' - >>> vimage.cmdline # doctest: +ALLOW_UNICODE + >>> vimage.cmdline 'vtomat -in image.v -out image.mat' >>> vimage.run() # doctest: +SKIP """ diff --git a/nipype/pipeline/engine/nodes.py b/nipype/pipeline/engine/nodes.py index f7f83f578a..36d3ba1b40 100644 --- a/nipype/pipeline/engine/nodes.py +++ b/nipype/pipeline/engine/nodes.py @@ -887,7 +887,7 @@ def _add_join_item_fields(self): ... name='inputspec'), >>> join = JoinNode(IdentityInterface(fields=['images', 'mask']), ... joinsource='inputspec', joinfield='images', name='join') - >>> join._add_join_item_fields() # doctest: +ALLOW_UNICODE + >>> join._add_join_item_fields() {'images': 'imagesJ1'} Return the {base field: slot field} dictionary diff --git a/nipype/pipeline/engine/tests/test_engine.py b/nipype/pipeline/engine/tests/test_engine.py index 6bfffdfbeb..8b4d559ec0 100644 --- a/nipype/pipeline/engine/tests/test_engine.py +++ b/nipype/pipeline/engine/tests/test_engine.py @@ -661,7 +661,7 @@ def test_parameterize_dirs_false(tmpdir): n2 = pe.Node(IdentityInterface(fields='in1'), name='Node2') wf = pe.Workflow(name='Test') - wf.base_dir = str(tmpdir) + wf.base_dir = tmpdir.strpath wf.config['execution']['parameterize_dirs'] = False wf.connect([(n1, n2, [('output1', 'in1')])]) diff --git a/nipype/pipeline/engine/tests/test_join.py b/nipype/pipeline/engine/tests/test_join.py index 87dafeee0f..a77745eb03 100644 --- a/nipype/pipeline/engine/tests/test_join.py +++ b/nipype/pipeline/engine/tests/test_join.py @@ -149,7 +149,7 @@ def _list_outputs(self): def test_join_expansion(tmpdir): - os.chdir(str(tmpdir)) + tmpdir.chdir() # Make the workflow. wf = pe.Workflow(name='test') @@ -196,7 +196,7 @@ def test_join_expansion(tmpdir): def test_node_joinsource(tmpdir): """Test setting the joinsource to a Node.""" - os.chdir(str(tmpdir)) + tmpdir.chdir() # Make the workflow. wf = pe.Workflow(name='test') @@ -214,7 +214,7 @@ def test_node_joinsource(tmpdir): def test_set_join_node(tmpdir): """Test collecting join inputs to a set.""" - os.chdir(str(tmpdir)) + tmpdir.chdir() # Make the workflow. wf = pe.Workflow(name='test') @@ -240,7 +240,7 @@ def test_unique_join_node(tmpdir): """Test join with the ``unique`` flag set to True.""" global _sum_operands _sum_operands = [] - os.chdir(str(tmpdir)) + tmpdir.chdir() # Make the workflow. wf = pe.Workflow(name='test') @@ -265,7 +265,7 @@ def test_multiple_join_nodes(tmpdir): """Test two join nodes, one downstream of the other.""" global _products _products = [] - os.chdir(str(tmpdir)) + tmpdir.chdir() # Make the workflow. wf = pe.Workflow(name='test') @@ -318,7 +318,7 @@ def test_identity_join_node(tmpdir): """Test an IdentityInterface join.""" global _sum_operands _sum_operands = [] - os.chdir(str(tmpdir)) + tmpdir.chdir() # Make the workflow. wf = pe.Workflow(name='test') @@ -353,7 +353,7 @@ def test_multifield_join_node(tmpdir): """Test join on several fields.""" global _products _products = [] - os.chdir(str(tmpdir)) + tmpdir.chdir() # Make the workflow. wf = pe.Workflow(name='test') @@ -393,7 +393,7 @@ def test_synchronize_join_node(tmpdir): """Test join on an input node which has the ``synchronize`` flag set to True.""" global _products _products = [] - os.chdir(str(tmpdir)) + tmpdir.chdir() # Make the workflow. wf = pe.Workflow(name='test') @@ -430,7 +430,7 @@ def test_synchronize_join_node(tmpdir): def test_itersource_join_source_node(tmpdir): """Test join on an input node which has an ``itersource``.""" - os.chdir(str(tmpdir)) + tmpdir.chdir() # Make the workflow. wf = pe.Workflow(name='test') @@ -484,7 +484,7 @@ def test_itersource_join_source_node(tmpdir): def test_itersource_two_join_nodes(tmpdir): """Test join with a midstream ``itersource`` and an upstream iterable.""" - os.chdir(str(tmpdir)) + tmpdir.chdir() # Make the workflow. wf = pe.Workflow(name='test') @@ -524,8 +524,7 @@ def test_itersource_two_join_nodes(tmpdir): def test_set_join_node_file_input(tmpdir): """Test collecting join inputs to a set.""" - wd = str(tmpdir) - os.chdir(wd) + tmpdir.chdir() open('test.nii', 'w+').close() open('test2.nii', 'w+').close() @@ -533,7 +532,7 @@ def test_set_join_node_file_input(tmpdir): wf = pe.Workflow(name='test') # the iterated input node inputspec = pe.Node(IdentityInterface(fields=['n']), name='inputspec') - inputspec.iterables = [('n', [os.path.join(wd, 'test.nii'), os.path.join(wd, 'test2.nii')])] + inputspec.iterables = [('n', [tmpdir.join('test.nii').strpath, tmpdir.join('test2.nii').strpath])] # a pre-join node in the iterated path pre_join1 = pe.Node(IdentityInterface(fields=['n']), name='pre_join1') wf.connect(inputspec, 'n', pre_join1, 'n') @@ -547,8 +546,7 @@ def test_set_join_node_file_input(tmpdir): def test_nested_workflow_join(tmpdir): """Test collecting join inputs within a nested workflow""" - wd = str(tmpdir) - os.chdir(wd) + tmpdir.chdir() # Make the nested workflow def nested_wf(i, name='smallwf'): diff --git a/nipype/pipeline/engine/tests/test_utils.py b/nipype/pipeline/engine/tests/test_utils.py index 7aa20b9302..34ec45cfa8 100644 --- a/nipype/pipeline/engine/tests/test_utils.py +++ b/nipype/pipeline/engine/tests/test_utils.py @@ -18,27 +18,28 @@ from ..utils import merge_dict, clean_working_directory, write_workflow_prov -def test_identitynode_removal(): +def test_identitynode_removal(tmpdir): def test_function(arg1, arg2, arg3): import numpy as np return (np.array(arg1) + arg2 + arg3).tolist() + - wf = pe.Workflow(name="testidentity") + wf = pe.Workflow(name="testidentity", base_dir=tmpdir.strpath) - n1 = pe.Node(niu.IdentityInterface(fields=['a', 'b']), name='src') + n1 = pe.Node(niu.IdentityInterface(fields=['a', 'b']), name='src', base_dir=tmpdir.strpath) n1.iterables = ('b', [0, 1, 2, 3]) n1.inputs.a = [0, 1, 2, 3] - n2 = pe.Node(niu.Select(), name='selector') + n2 = pe.Node(niu.Select(), name='selector', base_dir=tmpdir.strpath) wf.connect(n1, ('a', test_function, 1, -1), n2, 'inlist') wf.connect(n1, 'b', n2, 'index') - n3 = pe.Node(niu.IdentityInterface(fields=['c', 'd']), name='passer') + n3 = pe.Node(niu.IdentityInterface(fields=['c', 'd']), name='passer', base_dir=tmpdir.strpath) n3.inputs.c = [1, 2, 3, 4] wf.connect(n2, 'out', n3, 'd') - n4 = pe.Node(niu.Select(), name='selector2') + n4 = pe.Node(niu.Select(), name='selector2', base_dir=tmpdir.strpath) wf.connect(n3, ('c', test_function, 1, -1), n4, 'inlist') wf.connect(n3, 'd', n4, 'index') @@ -58,15 +59,13 @@ class InputSpec(nib.TraitedSpec): outputs = OutputSpec() inputs = InputSpec() - wd = str(tmpdir) filenames = ['file.hdr', 'file.img', 'file.BRIK', 'file.HEAD', '_0x1234.json', 'foo.txt'] outfiles = [] for filename in filenames: - outfile = os.path.join(wd, filename) - with open(outfile, 'wt') as fp: - fp.writelines('dummy') - outfiles.append(outfile) + outfile = tmpdir.join(filename) + outfile.write('dummy') + outfiles.append(outfile.strpath) outputs.files = outfiles[:4:2] outputs.others = outfiles[5] inputs.infile = outfiles[-1] @@ -75,12 +74,12 @@ class InputSpec(nib.TraitedSpec): assert os.path.exists(outfiles[5]) config.set_default_config() config.set('execution', 'remove_unnecessary_outputs', False) - out = clean_working_directory(outputs, wd, inputs, needed_outputs, + out = clean_working_directory(outputs, tmpdir.strpath, inputs, needed_outputs, deepcopy(config._sections)) assert os.path.exists(outfiles[5]) assert out.others == outfiles[5] config.set('execution', 'remove_unnecessary_outputs', True) - out = clean_working_directory(outputs, wd, inputs, needed_outputs, + out = clean_working_directory(outputs, tmpdir.strpath, inputs, needed_outputs, deepcopy(config._sections)) assert os.path.exists(outfiles[1]) assert os.path.exists(outfiles[3]) @@ -105,30 +104,21 @@ def test_function(arg1): fp.close() return file1, file2 - out_dir = str(tmpdir) n1 = pe.Node(niu.Function(input_names=['arg1'], output_names=['file1', 'file2'], function=test_function), - base_dir=out_dir, + base_dir=tmpdir.strpath, name='testoutputs') n1.inputs.arg1 = 1 n1.config = {'execution': {'remove_unnecessary_outputs': True}} n1.config = merge_dict(deepcopy(config._sections), n1.config) n1.run() - assert os.path.exists(os.path.join(out_dir, - n1.name, - 'file1.txt')) - assert os.path.exists(os.path.join(out_dir, - n1.name, - 'file2.txt')) + assert tmpdir.join(n1.name,'file1.txt').check() + assert tmpdir.join(n1.name,'file1.txt').check() n1.needed_outputs = ['file2'] n1.run() - assert not os.path.exists(os.path.join(out_dir, - n1.name, - 'file1.txt')) - assert os.path.exists(os.path.join(out_dir, - n1.name, - 'file2.txt')) + assert not tmpdir.join(n1.name,'file1.txt').check() + assert tmpdir.join(n1.name,'file2.txt').check() class InputSpec(nib.TraitedSpec): @@ -154,29 +144,22 @@ def _list_outputs(self): def test_inputs_removal(tmpdir): - out_dir = str(tmpdir) - file1 = os.path.join(out_dir, 'file1.txt') - fp = open(file1, 'wt') - fp.write('dummy_file') - fp.close() + file1 = tmpdir.join('file1.txt') + file1.write('dummy_file') n1 = pe.Node(UtilsTestInterface(), - base_dir=out_dir, + base_dir=tmpdir.strpath, name='testinputs') - n1.inputs.in_file = file1 + n1.inputs.in_file = file1.strpath n1.config = {'execution': {'keep_inputs': True}} n1.config = merge_dict(deepcopy(config._sections), n1.config) n1.run() - assert os.path.exists(os.path.join(out_dir, - n1.name, - 'file1.txt')) - n1.inputs.in_file = file1 + assert tmpdir.join(n1.name,'file1.txt').check() + n1.inputs.in_file = file1.strpath n1.config = {'execution': {'keep_inputs': False}} n1.config = merge_dict(deepcopy(config._sections), n1.config) n1.overwrite = True n1.run() - assert not os.path.exists(os.path.join(out_dir, - n1.name, - 'file1.txt')) + assert not tmpdir.join(n1.name,'file1.txt').check() def test_outputs_removal_wf(tmpdir): @@ -210,27 +193,26 @@ def test_function3(arg): import os return arg - out_dir = str(tmpdir) for plugin in ('Linear',): # , 'MultiProc'): n1 = pe.Node(niu.Function(input_names=['arg1'], output_names=['out_file1', 'out_file2', 'dir'], function=test_function), - name='n1') + name='n1', base_dir=tmpdir.strpath) n1.inputs.arg1 = 1 n2 = pe.Node(niu.Function(input_names=['in_file', 'arg'], output_names=['out_file1', 'out_file2', 'n'], function=test_function2), - name='n2') + name='n2', base_dir=tmpdir.strpath) n2.inputs.arg = 2 n3 = pe.Node(niu.Function(input_names=['arg'], output_names=['n'], function=test_function3), - name='n3') + name='n3', base_dir=tmpdir.strpath) - wf = pe.Workflow(name="node_rem_test" + plugin, base_dir=out_dir) + wf = pe.Workflow(name="node_rem_test" + plugin, base_dir=tmpdir.strpath) wf.connect(n1, "out_file1", n2, "in_file") wf.run(plugin='Linear') @@ -271,7 +253,7 @@ def test_function3(arg): n2.name, 'file3.txt')) != remove_unnecessary_outputs - n4 = pe.Node(UtilsTestInterface(), name='n4') + n4 = pe.Node(UtilsTestInterface(), name='n4', base_dir=tmpdir.strpath) wf.connect(n2, "out_file1", n4, "in_file") def pick_first(l): @@ -320,20 +302,18 @@ def create_wf(name): def test_multi_disconnected_iterable(tmpdir): metawf = pe.Workflow(name='meta') - metawf.base_dir = str(tmpdir) + metawf.base_dir = tmpdir.strpath metawf.add_nodes([create_wf('wf%d' % i) for i in range(30)]) eg = metawf.run(plugin='Linear') assert len(eg.nodes()) == 60 def test_provenance(tmpdir): - out_dir = str(tmpdir) metawf = pe.Workflow(name='meta') - metawf.base_dir = out_dir + metawf.base_dir = tmpdir.strpath metawf.add_nodes([create_wf('wf%d' % i) for i in range(1)]) eg = metawf.run(plugin='Linear') - prov_base = os.path.join(out_dir, - 'workflow_provenance_test') + prov_base = tmpdir.join('workflow_provenance_test').strpath psg = write_workflow_prov(eg, prov_base, format='all') assert len(psg.bundles) == 2 assert len(psg.get_records()) == 7 @@ -356,7 +336,7 @@ def test_mapnode_crash(tmpdir): node.inputs.WRONG = ['string{}'.format(i) for i in range(3)] node.config = deepcopy(config._sections) node.config['execution']['stop_on_first_crash'] = True - node.base_dir = str(tmpdir) + node.base_dir = tmpdir.strpath with pytest.raises(TypeError): node.run() os.chdir(cwd) @@ -373,7 +353,7 @@ def test_mapnode_crash2(tmpdir): iterfield=['WRONG'], name='myfunc') node.inputs.WRONG = ['string{}'.format(i) for i in range(3)] - node.base_dir = str(tmpdir) + node.base_dir = tmpdir.strpath with pytest.raises(Exception): node.run() @@ -384,6 +364,7 @@ def test_mapnode_crash2(tmpdir): reason="the famous segfault #1788") def test_mapnode_crash3(tmpdir): """Test mapnode crash when mapnode is embedded in a workflow""" + tmpdir.chdir() node = pe.MapNode(niu.Function(input_names=['WRONG'], output_names=['newstring'], function=dummy_func), @@ -392,6 +373,8 @@ def test_mapnode_crash3(tmpdir): node.inputs.WRONG = ['string{}'.format(i) for i in range(3)] wf = pe.Workflow('testmapnodecrash') wf.add_nodes([node]) - wf.base_dir = str(tmpdir) + wf.base_dir = tmpdir.strpath + #changing crashdump dir to cwl (to avoid problems with read-only systems) + wf.config["execution"]["crashdump_dir"] = os.getcwd() with pytest.raises(RuntimeError): wf.run(plugin='Linear') diff --git a/nipype/pipeline/plugins/sge.py b/nipype/pipeline/plugins/sge.py index 6d448df3df..42aa4bc915 100644 --- a/nipype/pipeline/plugins/sge.py +++ b/nipype/pipeline/plugins/sge.py @@ -313,9 +313,9 @@ def qsub_sanitize_job_name(testjobname): Numbers and punctuation are not allowed. - >>> qsub_sanitize_job_name('01') # doctest: +ALLOW_UNICODE + >>> qsub_sanitize_job_name('01') 'J01' - >>> qsub_sanitize_job_name('a01') # doctest: +ALLOW_UNICODE + >>> qsub_sanitize_job_name('a01') 'a01' """ if testjobname[0].isalpha(): diff --git a/nipype/pipeline/plugins/tests/test_callback.py b/nipype/pipeline/plugins/tests/test_callback.py index bfe03463d1..46f3608746 100644 --- a/nipype/pipeline/plugins/tests/test_callback.py +++ b/nipype/pipeline/plugins/tests/test_callback.py @@ -32,7 +32,7 @@ def callback(self, node, status, result=None): def test_callback_normal(tmpdir): so = Status() - wf = pe.Workflow(name='test', base_dir=str(tmpdir)) + wf = pe.Workflow(name='test', base_dir=tmpdir.strpath) f_node = pe.Node(niu.Function(function=func, input_names=[], output_names=[]), name='f_node') @@ -48,7 +48,7 @@ def test_callback_normal(tmpdir): def test_callback_exception(tmpdir): so = Status() - wf = pe.Workflow(name='test', base_dir=str(tmpdir)) + wf = pe.Workflow(name='test', base_dir=tmpdir.strpath) f_node = pe.Node(niu.Function(function=bad_func, input_names=[], output_names=[]), name='f_node') @@ -66,7 +66,7 @@ def test_callback_exception(tmpdir): def test_callback_multiproc_normal(tmpdir): so = Status() - wf = pe.Workflow(name='test', base_dir=str(tmpdir)) + wf = pe.Workflow(name='test', base_dir=tmpdir.strpath) f_node = pe.Node(niu.Function(function=func, input_names=[], output_names=[]), name='f_node') diff --git a/nipype/pipeline/plugins/tests/test_debug.py b/nipype/pipeline/plugins/tests/test_debug.py index 3e03abcf90..e7997ba7f0 100644 --- a/nipype/pipeline/plugins/tests/test_debug.py +++ b/nipype/pipeline/plugins/tests/test_debug.py @@ -34,7 +34,7 @@ def callme(node, graph): def test_debug(tmpdir): - os.chdir(str(tmpdir)) + tmpdir.chdir() pipe = pe.Workflow(name='pipe') mod1 = pe.Node(DebugTestInterface(), name='mod1') diff --git a/nipype/pipeline/plugins/tests/test_linear.py b/nipype/pipeline/plugins/tests/test_linear.py index 2e2fead4eb..afb916f6eb 100644 --- a/nipype/pipeline/plugins/tests/test_linear.py +++ b/nipype/pipeline/plugins/tests/test_linear.py @@ -29,7 +29,7 @@ def _list_outputs(self): def test_run_in_series(tmpdir): - os.chdir(str(tmpdir)) + tmpdir.chdir() pipe = pe.Workflow(name='pipe') mod1 = pe.Node(interface=LinearTestInterface(), name='mod1') diff --git a/nipype/pipeline/plugins/tests/test_somaflow.py b/nipype/pipeline/plugins/tests/test_somaflow.py index f2d5c945fb..7449d0d3ae 100644 --- a/nipype/pipeline/plugins/tests/test_somaflow.py +++ b/nipype/pipeline/plugins/tests/test_somaflow.py @@ -34,7 +34,7 @@ def _list_outputs(self): @pytest.mark.skipif(soma_not_loaded, reason="soma not loaded") def test_run_somaflow(tmpdir): - os.chdir(str(tmpdir)) + tmpdir.chdir() pipe = pe.Workflow(name='pipe') mod1 = pe.Node(interface=SomaTestInterface(), name='mod1') diff --git a/nipype/testing/fixtures.py b/nipype/testing/fixtures.py index 2a405742f7..550346d1db 100644 --- a/nipype/testing/fixtures.py +++ b/nipype/testing/fixtures.py @@ -39,66 +39,57 @@ def nifti_image_files(outdir, filelist, shape): @pytest.fixture() def create_files_in_directory(request, tmpdir): - outdir = str(tmpdir) - cwd = os.getcwd() - os.chdir(outdir) + cwd = tmpdir.chdir() filelist = ['a.nii', 'b.nii'] - nifti_image_files(outdir, filelist, shape=(3,3,3,4)) + nifti_image_files(tmpdir.strpath, filelist, shape=(3,3,3,4)) def change_directory(): - os.chdir(cwd) + cwd.chdir() request.addfinalizer(change_directory) - return (filelist, outdir) + return (filelist, tmpdir.strpath) @pytest.fixture() def create_analyze_pair_file_in_directory(request, tmpdir): - outdir = str(tmpdir) - cwd = os.getcwd() - os.chdir(outdir) + cwd = tmpdir.chdir() filelist = ['a.hdr'] - analyze_pair_image_files(outdir, filelist, shape=(3, 3, 3, 4)) + analyze_pair_image_files(tmpdir.strpath, filelist, shape=(3, 3, 3, 4)) def change_directory(): - os.chdir(cwd) + cwd.chdir() request.addfinalizer(change_directory) - return (filelist, outdir) + return (filelist, tmpdir.strpath) @pytest.fixture() def create_files_in_directory_plus_dummy_file(request, tmpdir): - outdir = str(tmpdir) - cwd = os.getcwd() - os.chdir(outdir) + cwd = tmpdir.chdir() filelist = ['a.nii', 'b.nii'] - nifti_image_files(outdir, filelist, shape=(3,3,3,4)) + nifti_image_files(tmpdir.strpath, filelist, shape=(3,3,3,4)) - with open(os.path.join(outdir, 'reg.dat'), 'wt') as fp: - fp.write('dummy file') + tmpdir.join('reg.dat').write('dummy file') filelist.append('reg.dat') def change_directory(): - os.chdir(cwd) + cwd.chdir() request.addfinalizer(change_directory) - return (filelist, outdir) + return (filelist, tmpdir.strpath) @pytest.fixture() def create_surf_file_in_directory(request, tmpdir): - outdir = str(tmpdir) - cwd = os.getcwd() - os.chdir(outdir) + cwd = tmpdir.chdir() surf = 'lh.a.nii' - nifti_image_files(outdir, filelist=surf, shape=(1, 100, 1)) + nifti_image_files(tmpdir.strpath, filelist=surf, shape=(1, 100, 1)) def change_directory(): - os.chdir(cwd) + cwd.chdir() request.addfinalizer(change_directory) - return (surf, outdir) + return (surf, tmpdir.strpath) def set_output_type(fsl_output_type): @@ -115,18 +106,15 @@ def set_output_type(fsl_output_type): @pytest.fixture(params=[None]+list(Info.ftypes)) def create_files_in_directory_plus_output_type(request, tmpdir): func_prev_type = set_output_type(request.param) - - testdir = str(tmpdir) - origdir = os.getcwd() - os.chdir(testdir) + origdir = tmpdir.chdir() filelist = ['a.nii', 'b.nii'] - nifti_image_files(testdir, filelist, shape=(3,3,3,4)) + nifti_image_files(tmpdir.strpath, filelist, shape=(3,3,3,4)) out_ext = Info.output_type_to_ext(Info.output_type()) def fin(): set_output_type(func_prev_type) - os.chdir(origdir) + origdir.chdir() request.addfinalizer(fin) - return (filelist, testdir, out_ext) + return (filelist, tmpdir.strpath, out_ext) diff --git a/nipype/testing/tests/test_utils.py b/nipype/testing/tests/test_utils.py index e2ca3a32de..838c3d167a 100644 --- a/nipype/testing/tests/test_utils.py +++ b/nipype/testing/tests/test_utils.py @@ -17,8 +17,8 @@ def test_tempfatfs(): except (IOError, OSError): warnings.warn("Cannot mount FAT filesystems with FUSE") else: - with fatfs as tmpdir: - assert os.path.exists(tmpdir) + with fatfs as tmp_dir: + assert os.path.exists(tmp_dir) @patch('subprocess.check_call', MagicMock( side_effect=subprocess.CalledProcessError('',''))) diff --git a/nipype/utils/filemanip.py b/nipype/utils/filemanip.py index e8a9ea22b8..16eabbb69c 100644 --- a/nipype/utils/filemanip.py +++ b/nipype/utils/filemanip.py @@ -64,13 +64,13 @@ def split_filename(fname): -------- >>> from nipype.utils.filemanip import split_filename >>> pth, fname, ext = split_filename('/home/data/subject.nii.gz') - >>> pth # doctest: +ALLOW_UNICODE + >>> pth '/home/data' - >>> fname # doctest: +ALLOW_UNICODE + >>> fname 'subject' - >>> ext # doctest: +ALLOW_UNICODE + >>> ext '.nii.gz' """ @@ -171,7 +171,7 @@ def fname_presuffix(fname, prefix='', suffix='', newpath=None, use_ext=True): >>> from nipype.utils.filemanip import fname_presuffix >>> fname = 'foo.nii.gz' - >>> fname_presuffix(fname,'pre','post','/tmp') # doctest: +ALLOW_UNICODE + >>> fname_presuffix(fname,'pre','post','/tmp') '/tmp/prefoopost.nii.gz' """ @@ -368,13 +368,13 @@ def copyfile(originalfile, newfile, copy=False, create_new=False, elif hashmethod == 'content': hashfn = hash_infile newhash = hashfn(newfile) - fmlogger.debug("File: %s already exists,%s, copy:%d" % - (newfile, newhash, copy)) + fmlogger.debug('File: %s already exists,%s, copy:%d', newfile, + newhash, copy) orighash = hashfn(originalfile) keep = newhash == orighash if keep: - fmlogger.debug("File: %s already exists, not overwriting, copy:%d" - % (newfile, copy)) + fmlogger.debug('File: %s already exists, not overwriting, copy:%d', + newfile, copy) else: os.unlink(newfile) @@ -385,7 +385,7 @@ def copyfile(originalfile, newfile, copy=False, create_new=False, # ~hardlink & ~symlink => copy if not keep and use_hardlink: try: - fmlogger.debug("Linking File: %s->%s" % (newfile, originalfile)) + fmlogger.debug('Linking File: %s->%s', newfile, originalfile) # Use realpath to avoid hardlinking symlinks os.link(os.path.realpath(originalfile), newfile) except OSError: @@ -395,7 +395,7 @@ def copyfile(originalfile, newfile, copy=False, create_new=False, if not keep and not copy and os.name == 'posix': try: - fmlogger.debug("Symlinking File: %s->%s" % (newfile, originalfile)) + fmlogger.debug('Symlinking File: %s->%s', newfile, originalfile) os.symlink(originalfile, newfile) except OSError: copy = True # Disable symlink for associated files @@ -404,7 +404,7 @@ def copyfile(originalfile, newfile, copy=False, create_new=False, if not keep: try: - fmlogger.debug("Copying File: %s->%s" % (newfile, originalfile)) + fmlogger.debug('Copying File: %s->%s', newfile, originalfile) shutil.copyfile(originalfile, newfile) except shutil.Error as e: fmlogger.warn(e.message) @@ -603,7 +603,7 @@ def read_stream(stream, logger=None, encoding=None): Robustly reads a stream, sending a warning to a logger if some decoding error was raised. - >>> read_stream(bytearray([65, 0xc7, 65, 10, 66])) # doctest: +ELLIPSIS +ALLOW_UNICODE + >>> read_stream(bytearray([65, 0xc7, 65, 10, 66])) # doctest: +ELLIPSIS ['A...A', 'B'] diff --git a/nipype/utils/tests/test_filemanip.py b/nipype/utils/tests/test_filemanip.py index 9e0f3abb78..d50bef355a 100644 --- a/nipype/utils/tests/test_filemanip.py +++ b/nipype/utils/tests/test_filemanip.py @@ -6,8 +6,6 @@ import os import time -from tempfile import mkstemp, mkdtemp -import shutil import warnings import pytest @@ -93,7 +91,7 @@ def _temp_analyze_files_prime(tmpdir): orig_hdr = tmpdir.join("orig_prime.hdr") orig_img.open('w+').close() orig_hdr.open('w+').close() - return str(orig_img), str(orig_hdr) + return orig_img.strpath, orig_hdr.strpath def test_copyfile(_temp_analyze_files): @@ -275,15 +273,14 @@ def test_list_to_filename(list, expected): assert x == expected -def test_check_depends(): +def test_check_depends(tmpdir): def touch(fname): with open(fname, 'a'): os.utime(fname, None) - tmpdir = mkdtemp() - dependencies = [os.path.join(tmpdir, str(i)) for i in range(3)] - targets = [os.path.join(tmpdir, str(i)) for i in range(3, 6)] + dependencies = [tmpdir.join(str(i)).strpath for i in range(3)] + targets = [tmpdir.join(str(i)).strpath for i in range(3, 6)] # Targets newer than dependencies for dep in dependencies: @@ -307,13 +304,11 @@ def touch(fname): else: assert False, "Should raise OSError on missing dependency" - shutil.rmtree(tmpdir) - -def test_json(): +def test_json(tmpdir): # Simple roundtrip test of json files, just a sanity check. adict = dict(a='one', c='three', b='two') - fd, name = mkstemp(suffix='.json') + name = tmpdir.join('test.json').strpath save_json(name, adict) # save_json closes the file new_dict = load_json(name) os.unlink(name) diff --git a/nipype/utils/tests/test_provenance.py b/nipype/utils/tests/test_provenance.py index 270774dcf5..ce35a95aac 100644 --- a/nipype/utils/tests/test_provenance.py +++ b/nipype/utils/tests/test_provenance.py @@ -21,8 +21,7 @@ def test_provenance(): assert 'echo hello' in provn def test_provenance_exists(tmpdir): - tempdir = str(tmpdir) - os.chdir(tempdir) + tmpdir.chdir() from nipype import config from nipype.interfaces.base import CommandLine provenance_state = config.get('execution', 'write_provenance') @@ -31,8 +30,7 @@ def test_provenance_exists(tmpdir): CommandLine('echo hello').run() config.set('execution', 'write_provenance', provenance_state) config.set('execution', 'hash_method', hash_state) - provenance_exists = os.path.exists(os.path.join(tempdir, 'provenance.provn')) - assert provenance_exists + assert tmpdir.join('provenance.provn').check() def test_safe_encode(): a = '\xc3\xa9lg' diff --git a/nipype/workflows/dmri/fsl/tests/test_dti.py b/nipype/workflows/dmri/fsl/tests/test_dti.py index 9a8ed4ca13..7c5a7a4426 100644 --- a/nipype/workflows/dmri/fsl/tests/test_dti.py +++ b/nipype/workflows/dmri/fsl/tests/test_dti.py @@ -9,15 +9,13 @@ import nipype.pipeline.engine as pe import warnings -import tempfile -import shutil from nipype.workflows.dmri.fsl.dti import create_bedpostx_pipeline from nipype.utils.filemanip import list_to_filename @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @pytest.mark.skipif(no_fsl_course_data(), reason="fsl data not available") -def test_create_bedpostx_pipeline(): +def test_create_bedpostx_pipeline(tmpdir): fsl_course_dir = os.path.abspath(os.environ['FSL_COURSE_DATA']) mask_file = os.path.join(fsl_course_dir, "fdt2/subj1.bedpostX/nodif_brain_mask.nii.gz") @@ -72,7 +70,7 @@ def test_create_bedpostx_pipeline(): test_f1 = pe.Node(util.AssertEqual(), name="mean_f1_test") pipeline = pe.Workflow(name="test_bedpostx") - pipeline.base_dir = tempfile.mkdtemp(prefix="nipype_test_bedpostx_") + pipeline.base_dir = tmpdir.mkdir("nipype_test_bedpostx_").strpath pipeline.connect([(slice_mask, original_bedpostx, [("roi_file", "mask")]), (slice_mask, nipype_bedpostx, [("roi_file", "inputnode.mask")]), @@ -85,4 +83,3 @@ def test_create_bedpostx_pipeline(): ]) pipeline.run(plugin='Linear') - shutil.rmtree(pipeline.base_dir) diff --git a/nipype/workflows/dmri/fsl/tests/test_epi.py b/nipype/workflows/dmri/fsl/tests/test_epi.py index f7b349b442..eeb36ee409 100644 --- a/nipype/workflows/dmri/fsl/tests/test_epi.py +++ b/nipype/workflows/dmri/fsl/tests/test_epi.py @@ -9,14 +9,12 @@ import nipype.pipeline.engine as pe import warnings -import tempfile -import shutil from nipype.workflows.dmri.fsl.epi import create_eddy_correct_pipeline @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @pytest.mark.skipif(no_fsl_course_data(), reason="fsl data not available") -def test_create_eddy_correct_pipeline(): +def test_create_eddy_correct_pipeline(tmpdir): fsl_course_dir = os.path.abspath(os.environ['FSL_COURSE_DATA']) dwi_file = os.path.join(fsl_course_dir, "fdt1/subj1/data.nii.gz") @@ -36,7 +34,7 @@ def test_create_eddy_correct_pipeline(): test = pe.Node(util.AssertEqual(), name="eddy_corrected_dwi_test") pipeline = pe.Workflow(name="test_eddycorrect") - pipeline.base_dir = tempfile.mkdtemp(prefix="nipype_test_eddycorrect_") + pipeline.base_dir = tmpdir.mkdir("nipype_test_eddycorrect_").strpath pipeline.connect([(trim_dwi, original_eddycorrect, [("roi_file", "in_file")]), (trim_dwi, nipype_eddycorrect, [("roi_file", "inputnode.in_file")]), @@ -45,4 +43,3 @@ def test_create_eddy_correct_pipeline(): ]) pipeline.run(plugin='Linear') - shutil.rmtree(pipeline.base_dir) diff --git a/nipype/workflows/dmri/fsl/tests/test_tbss.py b/nipype/workflows/dmri/fsl/tests/test_tbss.py index 20f7331fda..9cf2c9fe50 100644 --- a/nipype/workflows/dmri/fsl/tests/test_tbss.py +++ b/nipype/workflows/dmri/fsl/tests/test_tbss.py @@ -126,7 +126,7 @@ def _tbss_test_helper(estimate_skeleton): @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @pytest.mark.skipif(no_fsl_course_data(), reason="fsl data not available") -def disabled_tbss_est_skeleton(): +def test_disabled_tbss_est_skeleton(): _tbss_test_helper(True) # this test is disabled until we figure out what is wrong with TBSS in 5.0.9 @@ -134,5 +134,5 @@ def disabled_tbss_est_skeleton(): @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @pytest.mark.skipif(no_fsl_course_data(), reason="fsl data not available") -def disabled_tbss_est_skeleton_use_precomputed_skeleton(): +def test_disabled_tbss_est_skeleton_use_precomputed_skeleton(): _tbss_test_helper(False) diff --git a/nipype/workflows/fmri/fsl/preprocess.py b/nipype/workflows/fmri/fsl/preprocess.py index ea67667294..aa8ac03673 100644 --- a/nipype/workflows/fmri/fsl/preprocess.py +++ b/nipype/workflows/fmri/fsl/preprocess.py @@ -4,7 +4,6 @@ from __future__ import division import os - from ....interfaces import fsl as fsl # fsl from ....interfaces import utility as util # utility from ....pipeline import engine as pe # pypeline engine @@ -771,7 +770,7 @@ def create_susan_smooth(name="susan_smooth", separate_masks=True): Inputs:: inputnode.in_files : functional runs (filename or list of filenames) - inputnode.fwhm : fwhm for smoothing with SUSAN + inputnode.fwhm : fwhm for smoothing with SUSAN (float or list of floats) inputnode.mask_file : mask used for estimating SUSAN thresholds (but not for smoothing) Outputs:: @@ -788,6 +787,19 @@ def create_susan_smooth(name="susan_smooth", separate_masks=True): >>> smooth.run() # doctest: +SKIP """ + # replaces the functionality of a "for loop" + def cartesian_product(fwhms, in_files, usans, btthresh): + from nipype.utils.filemanip import filename_to_list + # ensure all inputs are lists + in_files = filename_to_list(in_files) + fwhms = [fwhms] if isinstance(fwhms, (int, float)) else fwhms + # create cartesian product lists (s_ = single element of list) + cart_in_file = [s_in_file for s_in_file in in_files for s_fwhm in fwhms] + cart_fwhm = [s_fwhm for s_in_file in in_files for s_fwhm in fwhms] + cart_usans = [s_usans for s_usans in usans for s_fwhm in fwhms] + cart_btthresh = [s_btthresh for s_btthresh in btthresh for s_fwhm in fwhms] + + return cart_in_file, cart_fwhm, cart_usans, cart_btthresh susan_smooth = pe.Workflow(name=name) @@ -807,8 +819,15 @@ def create_susan_smooth(name="susan_smooth", separate_masks=True): functional """ + multi_inputs = pe.Node(util.Function(function=cartesian_product, + output_names=['cart_in_file', + 'cart_fwhm', + 'cart_usans', + 'cart_btthresh']), + name='multi_inputs') + smooth = pe.MapNode(interface=fsl.SUSAN(), - iterfield=['in_file', 'brightness_threshold', 'usans'], + iterfield=['in_file', 'brightness_threshold', 'usans', 'fwhm'], name='smooth') """ @@ -865,10 +884,17 @@ def create_susan_smooth(name="susan_smooth", separate_masks=True): """ Define a function to get the brightness threshold for SUSAN """ - susan_smooth.connect(inputnode, 'fwhm', smooth, 'fwhm') - susan_smooth.connect(inputnode, 'in_files', smooth, 'in_file') - susan_smooth.connect(median, ('out_stat', getbtthresh), smooth, 'brightness_threshold') - susan_smooth.connect(merge, ('out', getusans), smooth, 'usans') + + susan_smooth.connect([ + (inputnode, multi_inputs, [('in_files', 'in_files'), + ('fwhm', 'fwhms')]), + (median, multi_inputs, [(('out_stat', getbtthresh), 'btthresh')]), + (merge, multi_inputs, [(('out', getusans), 'usans')]), + (multi_inputs, smooth, [('cart_in_file', 'in_file'), + ('cart_fwhm', 'fwhm'), + ('cart_btthresh', 'brightness_threshold'), + ('cart_usans', 'usans')]), + ]) outputnode = pe.Node(interface=util.IdentityInterface(fields=['smoothed_files']), name='outputnode') diff --git a/nipype/workflows/rsfmri/fsl/tests/test_resting.py b/nipype/workflows/rsfmri/fsl/tests/test_resting.py index 7ae4483b55..68e62d7ee8 100644 --- a/nipype/workflows/rsfmri/fsl/tests/test_resting.py +++ b/nipype/workflows/rsfmri/fsl/tests/test_resting.py @@ -51,7 +51,7 @@ class TestResting(): @pytest.fixture(autouse=True) def setup_class(self, tmpdir): # setup temp folder - os.chdir(str(tmpdir)) + tmpdir.chdir() self.in_filenames = {key: os.path.abspath(value) for key, value in self.in_filenames.items()} diff --git a/pytest.ini b/pytest.ini index 6247b04cca..ea149d6ed1 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,3 +1,4 @@ [pytest] norecursedirs = .git build dist doc nipype/external tools examples src -addopts = --doctest-modules \ No newline at end of file +addopts = --doctest-modules +doctest_optionflags = ALLOW_UNICODE NORMALIZE_WHITESPACE \ No newline at end of file diff --git a/tools/apigen.py b/tools/apigen.py index d3a732d881..c594042f71 100644 --- a/tools/apigen.py +++ b/tools/apigen.py @@ -103,11 +103,11 @@ def set_package_name(self, package_name): def _get_object_name(self, line): ''' Get second token in line >>> docwriter = ApiDocWriter('sphinx') - >>> docwriter._get_object_name(" def func(): ") # doctest: +ALLOW_UNICODE + >>> docwriter._get_object_name(" def func(): ") u'func' - >>> docwriter._get_object_name(" class Klass(object): ") # doctest: +ALLOW_UNICODE + >>> docwriter._get_object_name(" class Klass(object): ") 'Klass' - >>> docwriter._get_object_name(" class Klass: ") # doctest: +ALLOW_UNICODE + >>> docwriter._get_object_name(" class Klass: ") 'Klass' ''' name = line.split()[1].split('(')[0].strip() diff --git a/tools/interfacedocgen.py b/tools/interfacedocgen.py index 3eb7467c4b..80356d3ded 100644 --- a/tools/interfacedocgen.py +++ b/tools/interfacedocgen.py @@ -124,11 +124,11 @@ def set_package_name(self, package_name): def _get_object_name(self, line): ''' Get second token in line >>> docwriter = ApiDocWriter('sphinx') - >>> docwriter._get_object_name(" def func(): ") # doctest: +ALLOW_UNICODE + >>> docwriter._get_object_name(" def func(): ") u'func' - >>> docwriter._get_object_name(" class Klass(object): ") # doctest: +ALLOW_UNICODE + >>> docwriter._get_object_name(" class Klass(object): ") 'Klass' - >>> docwriter._get_object_name(" class Klass: ") # doctest: +ALLOW_UNICODE + >>> docwriter._get_object_name(" class Klass: ") 'Klass' ''' name = line.split()[1].split('(')[0].strip()