Skip to content

Commit f709804

Browse files
committed
Merge branch 'master' of git://github.com/nipy/nipype into fix/py2functions
2 parents 68dd94f + 37c9db6 commit f709804

File tree

12 files changed

+161
-53
lines changed

12 files changed

+161
-53
lines changed

nipype/interfaces/afni/preprocess.py

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
import os
1616
import os.path as op
1717

18-
from ...utils.filemanip import (load_json, save_json, split_filename)
18+
from ...utils.filemanip import (load_json, save_json, split_filename,
19+
fname_presuffix)
1920
from ..base import (
2021
CommandLineInputSpec, CommandLine, TraitedSpec,
2122
traits, isdefined, File, InputMultiPath, Undefined, Str)
@@ -3131,7 +3132,7 @@ class QwarpInputSpec(AFNICommandInputSpec):
31313132
'Note that the source dataset in the second run is the SAME as'
31323133
'in the first run. If you don\'t see why this is necessary,'
31333134
'then you probably need to seek help from an AFNI guru.',
3134-
argstr='-inlev %d',
3135+
argstr='-inilev %d',
31353136
xor=['duplo'])
31363137
minpatch = traits.Int(
31373138
desc='* The value of mm should be an odd integer.'
@@ -3462,7 +3463,7 @@ class Qwarp(AFNICommand):
34623463
>>> qwarp2.inputs.inilev = 7
34633464
>>> qwarp2.inputs.iniwarp = ['Q25_warp+tlrc.HEAD']
34643465
>>> qwarp2.cmdline # doctest: +ALLOW_UNICODE
3465-
'3dQwarp -base mni.nii -blur 0.0 2.0 -source structural.nii -inlev 7 -iniwarp Q25_warp+tlrc.HEAD -prefix Q11'
3466+
'3dQwarp -base mni.nii -blur 0.0 2.0 -source structural.nii -inilev 7 -iniwarp Q25_warp+tlrc.HEAD -prefix Q11'
34663467
>>> res2 = qwarp2.run() # doctest: +SKIP
34673468
"""
34683469
_cmd = '3dQwarp'
@@ -3475,29 +3476,38 @@ def _list_outputs(self):
34753476
if not isdefined(self.inputs.out_file):
34763477
prefix = self._gen_fname(self.inputs.in_file, suffix='_QW')
34773478
ext = '.HEAD'
3479+
suffix ='+tlrc'
34783480
else:
34793481
prefix = self.inputs.out_file
34803482
ext_ind = max([prefix.lower().rfind('.nii.gz'),
34813483
prefix.lower().rfind('.nii.')])
34823484
if ext_ind == -1:
34833485
ext = '.HEAD'
3486+
suffix = '+tlrc'
34843487
else:
34853488
ext = prefix[ext_ind:]
3489+
suffix = ''
34863490
print(ext,"ext")
3487-
outputs['warped_source'] = os.path.abspath(self._gen_fname(prefix, suffix='+tlrc')+ext)
3491+
outputs['warped_source'] = fname_presuffix(prefix, suffix=suffix,
3492+
use_ext=False) + ext
34883493
if not self.inputs.nowarp:
3489-
outputs['source_warp'] = os.path.abspath(self._gen_fname(prefix, suffix='_WARP+tlrc')+ext)
3494+
outputs['source_warp'] = fname_presuffix(prefix,
3495+
suffix='_WARP' + suffix, use_ext=False) + ext
34903496
if self.inputs.iwarp:
3491-
outputs['base_warp'] = os.path.abspath(self._gen_fname(prefix, suffix='_WARPINV+tlrc')+ext)
3497+
outputs['base_warp'] = fname_presuffix(prefix,
3498+
suffix='_WARPINV' + suffix, use_ext=False) + ext
34923499
if isdefined(self.inputs.out_weight_file):
34933500
outputs['weights'] = os.path.abspath(self.inputs.out_weight_file)
34943501

34953502
if self.inputs.plusminus:
3496-
outputs['warped_source'] = os.path.abspath(self._gen_fname(prefix, suffix='_PLUS+tlrc')+ext)
3497-
outputs['warped_base'] = os.path.abspath(self._gen_fname(prefix, suffix='_MINUS+tlrc')+ext)
3498-
outputs['source_warp'] = os.path.abspath(self._gen_fname(prefix, suffix='_PLUS_WARP+tlrc')+ext)
3499-
outputs['base_warp'] = os.path.abspath(self._gen_fname(prefix, suffix='_MINUS_WARP+tlrc',)+ext)
3500-
3503+
outputs['warped_source'] = fname_presuffix(prefix,
3504+
suffix='_PLUS' + suffix, use_ext=False) + ext
3505+
outputs['warped_base'] = fname_presuffix(prefix,
3506+
suffix='_MINUS' + suffix, use_ext=False) + ext
3507+
outputs['source_warp'] = fname_presuffix(prefix,
3508+
suffix='_PLUS_WARP' + suffix, use_ext=False) + ext
3509+
outputs['base_warp'] = fname_presuffix(prefix,
3510+
suffix='_MINUS_WARP' + suffix, use_ext=False) + ext
35013511
return outputs
35023512

35033513
def _gen_filename(self, name):

nipype/interfaces/afni/tests/test_auto_Qwarp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def test_Qwarp_inputs():
5151
copyfile=False,
5252
mandatory=True,
5353
),
54-
inilev=dict(argstr='-inlev %d',
54+
inilev=dict(argstr='-inilev %d',
5555
xor=['duplo'],
5656
),
5757
iniwarp=dict(argstr='-iniwarp %s',

nipype/interfaces/ants/resampling.py

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -243,13 +243,15 @@ class ApplyTransformsInputSpec(ANTSCommandInputSpec):
243243
'Gaussian',
244244
'BSpline',
245245
argstr='%s', usedefault=True)
246-
interpolation_parameters = traits.Either(traits.Tuple(traits.Int()), # BSpline (order)
247-
traits.Tuple(traits.Float(), # Gaussian/MultiLabel (sigma, alpha)
248-
traits.Float())
249-
)
250-
transforms = InputMultiPath(File(exists=True), argstr='%s', mandatory=True,
251-
desc='transform files: will be applied in reverse order. For '
252-
'example, the last specified transform will be applied first.')
246+
interpolation_parameters = traits.Either(
247+
traits.Tuple(traits.Int()), # BSpline (order)
248+
traits.Tuple(traits.Float(), # Gaussian/MultiLabel (sigma, alpha)
249+
traits.Float())
250+
)
251+
transforms = traits.Either(
252+
InputMultiPath(File(exists=True)), 'identity', argstr='%s', mandatory=True,
253+
desc='transform files: will be applied in reverse order. For '
254+
'example, the last specified transform will be applied first.')
253255
invert_transform_flags = InputMultiPath(traits.Bool())
254256
default_value = traits.Float(0.0, argstr='--default-value %g', usedefault=True)
255257
print_out_composite_warp_file = traits.Bool(False, requires=["output_image"],
@@ -269,6 +271,15 @@ class ApplyTransforms(ANTSCommand):
269271
--------
270272
271273
>>> from nipype.interfaces.ants import ApplyTransforms
274+
>>> at = ApplyTransforms()
275+
>>> at.inputs.input_image = 'moving1.nii'
276+
>>> at.inputs.reference_image = 'fixed1.nii'
277+
>>> at.inputs.transforms = 'identity'
278+
>>> at.cmdline # doctest: +ALLOW_UNICODE
279+
'antsApplyTransforms --default-value 0 --input moving1.nii \
280+
--interpolation Linear --output moving1_trans.nii \
281+
--reference-image fixed1.nii -t identity'
282+
272283
>>> at = ApplyTransforms()
273284
>>> at.inputs.dimension = 3
274285
>>> at.inputs.input_image = 'moving1.nii'
@@ -338,6 +349,8 @@ def _format_arg(self, opt, spec, val):
338349
if opt == "output_image":
339350
return self._get_output_warped_filename()
340351
elif opt == "transforms":
352+
if val == 'identity':
353+
return '-t identity'
341354
return self._get_transform_filenames()
342355
elif opt == 'interpolation':
343356
if self.inputs.interpolation in ['BSpline', 'MultiLabel', 'Gaussian'] and \

nipype/interfaces/base.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
from ..utils.provenance import write_provenance
3939
from ..utils.misc import is_container, trim, str2bool
4040
from ..utils.filemanip import (md5, hash_infile, FileNotFoundError, hash_timestamp,
41-
split_filename, to_str)
41+
split_filename, to_str, read_stream)
4242
from .traits_extension import (
4343
traits, Undefined, TraitDictObject, TraitListObject, TraitError, isdefined,
4444
File, Directory, DictStrStr, has_metadata, ImageFile)
@@ -1268,9 +1268,7 @@ def __init__(self, name, impl):
12681268
self._buf = ''
12691269
self._rows = []
12701270
self._lastidx = 0
1271-
self.default_encoding = locale.getdefaultlocale()[1]
1272-
if self.default_encoding is None:
1273-
self.default_encoding = 'UTF-8'
1271+
self.default_encoding = locale.getdefaultlocale()[1] or 'UTF-8'
12741272

12751273
def fileno(self):
12761274
"Pass-through for file descriptor."
@@ -1349,10 +1347,6 @@ def run_command(runtime, output=None, timeout=0.01):
13491347
cmdline = runtime.cmdline
13501348
env = _canonicalize_env(runtime.environ)
13511349

1352-
default_encoding = locale.getdefaultlocale()[1]
1353-
if default_encoding is None:
1354-
default_encoding = 'UTF-8'
1355-
13561350
errfile = None
13571351
outfile = None
13581352
stdout = sp.PIPE
@@ -1420,19 +1414,22 @@ def _process(drain=0):
14201414

14211415
if output == 'allatonce':
14221416
stdout, stderr = proc.communicate()
1423-
result['stdout'] = stdout.decode(default_encoding).split('\n')
1424-
result['stderr'] = stderr.decode(default_encoding).split('\n')
1417+
result['stdout'] = read_stream(stdout, logger=iflogger)
1418+
result['stderr'] = read_stream(stderr, logger=iflogger)
14251419

14261420
elif output.startswith('file'):
14271421
proc.wait()
14281422
if outfile is not None:
14291423
stdout.flush()
1430-
result['stdout'] = [line.decode(default_encoding).strip()
1431-
for line in open(outfile, 'rb').readlines()]
1424+
with open(outfile, 'rb') as ofh:
1425+
stdoutstr = ofh.read()
1426+
result['stdout'] = read_stream(stdoutstr, logger=iflogger)
1427+
14321428
if errfile is not None:
14331429
stderr.flush()
1434-
result['stderr'] = [line.decode(default_encoding).strip()
1435-
for line in open(errfile, 'rb').readlines()]
1430+
with open(errfile, 'rb') as efh:
1431+
stderrstr = efh.read()
1432+
result['stderr'] = read_stream(stderrstr, logger=iflogger)
14361433

14371434
if output == 'file':
14381435
result['merged'] = result['stdout']

nipype/interfaces/cmtk/nbs.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@ def ntwks_to_matrices(in_files, edge_key):
3232
for idx, name in enumerate(in_files):
3333
graph = nx.read_gpickle(name)
3434
for u, v, d in graph.edges(data=True):
35-
graph[u][v]['weight'] = d[edge_key] # Setting the edge requested edge value as weight value
35+
try:
36+
graph[u][v]['weight'] = d[edge_key] # Setting the edge requested edge value as weight value
37+
except:
38+
raise KeyError("the graph edges do not have {} attribute".format(edge_key))
3639
matrix[:, :, idx] = nx.to_numpy_matrix(graph) # Retrieve the matrix
3740
return matrix
3841

@@ -77,6 +80,10 @@ class NetworkBasedStatistic(BaseInterface):
7780
output_spec = NetworkBasedStatisticOutputSpec
7881

7982
def _run_interface(self, runtime):
83+
84+
if not have_cv:
85+
raise ImportError("cviewer library is not available")
86+
8087
THRESH = self.inputs.threshold
8188
K = self.inputs.number_of_permutations
8289
TAIL = self.inputs.t_tail
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
from __future__ import unicode_literals
2+
from ..nbs import NetworkBasedStatistic
3+
from ....utils.misc import package_check
4+
import numpy as np
5+
import networkx as nx
6+
import pytest
7+
8+
have_cv = True
9+
try:
10+
package_check('cviewer')
11+
except Exception as e:
12+
have_cv = False
13+
14+
@pytest.fixture()
15+
def creating_graphs(tmpdir):
16+
graphlist = []
17+
graphnames = ["name"+str(i) for i in range(6)]
18+
for idx, name in enumerate(graphnames):
19+
graph = np.random.rand(10,10)
20+
G = nx.from_numpy_matrix(graph)
21+
out_file = str(tmpdir) + graphnames[idx] + '.pck'
22+
# Save as pck file
23+
nx.write_gpickle(G, out_file)
24+
graphlist.append(out_file)
25+
return graphlist
26+
27+
28+
@pytest.mark.skipif(have_cv, reason="tests for import error, cviewer available")
29+
def test_importerror(creating_graphs):
30+
graphlist = creating_graphs
31+
group1 = graphlist[:3]
32+
group2 = graphlist[3:]
33+
34+
nbs = NetworkBasedStatistic()
35+
nbs.inputs.in_group1 = group1
36+
nbs.inputs.in_group2 = group2
37+
nbs.inputs.edge_key = "weight"
38+
39+
with pytest.raises(ImportError) as e:
40+
nbs.run()
41+
assert "cviewer library is not available" == str(e.value)
42+
43+
44+
@pytest.mark.skipif(not have_cv, reason="cviewer has to be available")
45+
def test_keyerror(creating_graphs):
46+
graphlist =creating_graphs
47+
48+
group1 = graphlist[:3]
49+
group2 = graphlist[3:]
50+
51+
nbs = NetworkBasedStatistic()
52+
nbs.inputs.in_group1 = group1
53+
nbs.inputs.in_group2 = group2
54+
nbs.inputs.edge_key = "Your_edge"
55+
56+
with pytest.raises(KeyError) as e:
57+
nbs.run()
58+
assert "the graph edges do not have Your_edge attribute" in str(e.value)

nipype/interfaces/freesurfer/preprocess.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2387,8 +2387,8 @@ class ConcatenateLTAInputSpec(FSTraitedSpec):
23872387
File(exists=True), 'identity.nofile', argstr='%s', position=-2,
23882388
mandatory=True, desc='maps dst1(src2) to dst2')
23892389
out_file = File(
2390-
'concat.lta', usedefault=True, position=-1, argstr='%s',
2391-
hash_files=False,
2390+
position=-1, argstr='%s', hash_files=False, name_source=['in_lta1'],
2391+
name_template='%s_concat', keep_extension=True,
23922392
desc='the combined LTA maps: src1 to dst2 = LTA2*LTA1')
23932393

23942394
# Inversion and transform type
@@ -2434,7 +2434,7 @@ class ConcatenateLTA(FSCommand):
24342434
>>> conc_lta.inputs.in_lta1 = 'lta1.lta'
24352435
>>> conc_lta.inputs.in_lta2 = 'lta2.lta'
24362436
>>> conc_lta.cmdline # doctest: +ALLOW_UNICODE
2437-
'mri_concatenate_lta lta1.lta lta2.lta concat.lta'
2437+
'mri_concatenate_lta lta1.lta lta2.lta lta1_concat.lta'
24382438
24392439
You can use 'identity.nofile' as the filename for in_lta2, e.g.:
24402440
@@ -2459,8 +2459,3 @@ def _format_arg(self, name, spec, value):
24592459
if name == 'out_type':
24602460
value = {'VOX2VOX': 0, 'RAS2RAS': 1}[value]
24612461
return super(ConcatenateLTA, self)._format_arg(name, spec, value)
2462-
2463-
def _list_outputs(self):
2464-
outputs = self.output_spec().get()
2465-
outputs['out_file'] = os.path.abspath(self.inputs.out_file)
2466-
return outputs

nipype/interfaces/freesurfer/tests/test_auto_ConcatenateLTA.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,10 @@ def test_ConcatenateLTA_inputs():
2828
),
2929
out_file=dict(argstr='%s',
3030
hash_files=False,
31+
keep_extension=True,
32+
name_source=['in_lta1'],
33+
name_template='%s_concat',
3134
position=-1,
32-
usedefault=True,
3335
),
3436
out_type=dict(argstr='-out_type %d',
3537
),

nipype/interfaces/fsl/epi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -592,7 +592,7 @@ def _run_interface(self, runtime):
592592
cmd = self._cmd
593593
if all((FSLDIR != '',
594594
cmd == 'eddy_openmp',
595-
not os.path.exists(os.path.join(FSLDIR, cmd)))):
595+
not os.path.exists(os.path.join(FSLDIR, 'bin', cmd)))):
596596
self._cmd = 'eddy'
597597
runtime = super(Eddy, self)._run_interface(runtime)
598598

nipype/pipeline/engine/nodes.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -633,7 +633,7 @@ def _run_command(self, execute, copyfiles=True):
633633
if copyfiles:
634634
self._copyfiles_to_wd(cwd, execute)
635635

636-
message = 'Running node "%s" (a "%s" interface)'
636+
message = 'Running node "%s" ("%s.%s")'
637637
if issubclass(self._interface.__class__, CommandLine):
638638
try:
639639
cmd = self._interface.cmdline
@@ -644,7 +644,7 @@ def _run_command(self, execute, copyfiles=True):
644644
with open(cmdfile, 'wt') as fd:
645645
print(cmd + "\n", file=fd)
646646
message += ', a CommandLine Interface with command:\n%s' % cmd
647-
logger.info(message + '.', self.name,
647+
logger.info(message + '.', self.name, self._interface.__module__,
648648
self._interface.__class__.__name__)
649649
try:
650650
result = self._interface.run()

0 commit comments

Comments
 (0)