Skip to content

Commit 1c9ee90

Browse files
committed
sty: pep8
1 parent 89576e6 commit 1c9ee90

File tree

1 file changed

+64
-53
lines changed

1 file changed

+64
-53
lines changed

nipype/interfaces/spm/base.py

Lines changed: 64 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from ... import logging
2626
logger = logging.getLogger('interface')
2727

28+
2829
def func_is_3d(in_file):
2930
"""Checks if input functional files are 3d."""
3031

@@ -33,41 +34,44 @@ def func_is_3d(in_file):
3334
else:
3435
img = load(in_file)
3536
shape = img.get_shape()
36-
if len(shape) == 3 or (len(shape)==4 and shape[3]==1):
37+
if len(shape) == 3 or (len(shape) == 4 and shape[3] == 1):
3738
return True
3839
else:
3940
return False
4041

42+
4143
def get_first_3dfile(in_files):
4244
if not func_is_3d(in_files):
4345
return None
4446
if isinstance(in_files[0], list):
4547
return in_files[0]
4648
return in_files
4749

50+
4851
def scans_for_fname(fname):
4952
"""Reads a nifti file and converts it to a numpy array storing
5053
individual nifti volumes.
5154
5255
Opens images so will fail if they are not found.
5356
5457
"""
55-
if isinstance(fname,list):
56-
scans = np.zeros((len(fname),),dtype=object)
57-
for sno,f in enumerate(fname):
58-
scans[sno] = '%s,1'%f
58+
if isinstance(fname, list):
59+
scans = np.zeros((len(fname),), dtype=object)
60+
for sno, f in enumerate(fname):
61+
scans[sno] = '%s,1' % f
5962
return scans
6063
img = load(fname)
6164
if len(img.get_shape()) == 3:
62-
return np.array(('%s,1'%fname,),dtype=object)
65+
return np.array(('%s,1' % fname,), dtype=object)
6366
else:
6467
n_scans = img.get_shape()[3]
65-
scans = np.zeros((n_scans,),dtype=object)
68+
scans = np.zeros((n_scans,), dtype=object)
6669
for sno in range(n_scans):
67-
scans[sno] = '%s,%d'% (fname, sno+1)
70+
scans[sno] = '%s,%d' % (fname, sno + 1)
6871
return scans
6972

70-
def scans_for_fnames(fnames,keep4d=False,separate_sessions=False):
73+
74+
def scans_for_fnames(fnames, keep4d=False, separate_sessions=False):
7175
"""Converts a list of files to a concatenated numpy array for each
7276
volume.
7377
@@ -84,14 +88,14 @@ def scans_for_fnames(fnames,keep4d=False,separate_sessions=False):
8488
if func_is_3d(fnames[0]):
8589
fnames = [fnames]
8690
if separate_sessions or keep4d:
87-
flist = np.zeros((len(fnames),),dtype=object)
88-
for i,f in enumerate(fnames):
91+
flist = np.zeros((len(fnames),), dtype=object)
92+
for i, f in enumerate(fnames):
8993
if separate_sessions:
9094
if keep4d:
91-
if isinstance(f,list):
95+
if isinstance(f, list):
9296
flist[i] = np.array(f, dtype=object)
9397
else:
94-
flist[i] = np.array([f],dtype=object)
98+
flist[i] = np.array([f], dtype=object)
9599
else:
96100
flist[i] = scans_for_fname(f)
97101
else:
@@ -102,14 +106,15 @@ def scans_for_fnames(fnames,keep4d=False,separate_sessions=False):
102106
if flist is None:
103107
flist = scans
104108
else:
105-
flist = np.concatenate((flist,scans))
109+
flist = np.concatenate((flist, scans))
106110
return flist
107111

112+
108113
class Info(object):
109114
"""Handles SPM version information
110115
"""
111116
@staticmethod
112-
def version( matlab_cmd = None ):
117+
def version(matlab_cmd=None):
113118
"""Returns the path to the SPM directory in the Matlab path
114119
If path not found, returns None.
115120
@@ -132,20 +137,20 @@ def version( matlab_cmd = None ):
132137
matlab_cmd = os.environ['MATLABCMD']
133138
except:
134139
matlab_cmd = 'matlab -nodesktop -nosplash'
135-
mlab = MatlabCommand(matlab_cmd = matlab_cmd)
140+
mlab = MatlabCommand(matlab_cmd=matlab_cmd)
136141
mlab.inputs.script = """
137-
if isempty(which('spm')),
138-
throw(MException('SPMCheck:NotFound','SPM not in matlab path'));
139-
end;
140-
spm_path = spm('dir');
141-
[name, version] = spm('ver');
142-
fprintf(1, 'NIPYPE path:%s|name:%s|release:%s', spm_path, name, version);
143-
exit;
142+
if isempty(which('spm')),
143+
throw(MException('SPMCheck:NotFound','SPM not in matlab path'));
144+
end;
145+
spm_path = spm('dir');
146+
[name, version] = spm('ver');
147+
fprintf(1, 'NIPYPE path:%s|name:%s|release:%s', spm_path, name, version);
148+
exit;
144149
"""
145150
mlab.inputs.mfile = False
146151
try:
147152
out = mlab.run()
148-
except (IOError,RuntimeError), e:
153+
except (IOError, RuntimeError), e:
149154
# if no Matlab at all -- exception could be raised
150155
# No Matlab -- no spm
151156
logger.debug(str(e))
@@ -158,12 +163,13 @@ def version( matlab_cmd = None ):
158163
out_dict[key] = val
159164
return out_dict
160165

166+
161167
def no_spm():
162168
""" Checks if SPM is NOT installed
163169
used with nosetests skipif to skip tests
164170
that will fail if spm is not installed"""
165171

166-
if Info.version() == None or 'NIPYPE_NO_MATLAB' in os.environ:
172+
if Info.version() is None or 'NIPYPE_NO_MATLAB' in os.environ:
167173
return True
168174
else:
169175
return False
@@ -173,9 +179,10 @@ class SPMCommandInputSpec(BaseInterfaceInputSpec):
173179
matlab_cmd = traits.Str(desc='matlab command to use')
174180
paths = InputMultiPath(Directory(), desc='Paths to add to matlabpath')
175181
mfile = traits.Bool(True, desc='Run m-code using m-file',
176-
usedefault=True)
182+
usedefault=True)
177183
use_mcr = traits.Bool(desc='Run m-code using SPM MCR')
178184

185+
179186
class SPMCommand(BaseInterface):
180187
"""Extends `BaseInterface` class to implement SPM specific interfaces.
181188
@@ -200,7 +207,7 @@ def __init__(self, **inputs):
200207
self._matlab_cmd_update()
201208

202209
@classmethod
203-
def set_mlab_paths(cls, matlab_cmd=None, paths = None, use_mcr=None):
210+
def set_mlab_paths(cls, matlab_cmd=None, paths=None, use_mcr=None):
204211
cls._matlab_cmd = matlab_cmd
205212
cls._paths = paths
206213
cls._use_mcr = use_mcr
@@ -214,7 +221,7 @@ def _matlab_cmd_update(self):
214221
paths=self.inputs.paths,
215222
uses_mcr=self.inputs.use_mcr)
216223
self.mlab.inputs.script_file = 'pyscript_%s.m' % \
217-
self.__class__.__name__.split('.')[-1].lower()
224+
self.__class__.__name__.split('.')[-1].lower()
218225

219226
@property
220227
def jobtype(self):
@@ -234,7 +241,8 @@ def _check_mlab_inputs(self):
234241

235242
def _run_interface(self, runtime):
236243
"""Executes the SPM function using MATLAB."""
237-
self.mlab.inputs.script = self._make_matlab_command(deepcopy(self._parse_inputs()))
244+
self.mlab.inputs.script = self._make_matlab_command(
245+
deepcopy(self._parse_inputs()))
238246
results = self.mlab.run()
239247
runtime.returncode = results.runtime.returncode
240248
if self.mlab.inputs.uses_mcr:
@@ -250,7 +258,6 @@ def _list_outputs(self):
250258

251259
raise NotImplementedError
252260

253-
254261
def _format_arg(self, opt, spec, val):
255262
"""Convert input to appropriate format for SPM."""
256263
if spec.is_trait_type(traits.Bool):
@@ -260,7 +267,7 @@ def _format_arg(self, opt, spec, val):
260267

261268
def _parse_inputs(self, skip=()):
262269
spmdict = {}
263-
metadata=dict(field=lambda t : t is not None)
270+
metadata = dict(field=lambda t: t is not None)
264271
for name, spec in self.inputs.traits(**metadata).items():
265272
if skip and name in skip:
266273
continue
@@ -325,47 +332,47 @@ def _generate_job(self, prefix='', contents=None):
325332
if contents is None:
326333
return jobstring
327334
if isinstance(contents, list):
328-
for i,value in enumerate(contents):
335+
for i, value in enumerate(contents):
329336
if prefix.endswith(")"):
330-
newprefix = "%s,%d)" % (prefix[:-1], i+1)
337+
newprefix = "%s,%d)" % (prefix[:-1], i + 1)
331338
else:
332-
newprefix = "%s(%d)" % (prefix, i+1)
339+
newprefix = "%s(%d)" % (prefix, i + 1)
333340
jobstring += self._generate_job(newprefix, value)
334341
return jobstring
335342
if isinstance(contents, dict):
336-
for key,value in contents.items():
343+
for key, value in contents.items():
337344
newprefix = "%s.%s" % (prefix, key)
338345
jobstring += self._generate_job(newprefix, value)
339346
return jobstring
340347
if isinstance(contents, np.ndarray):
341348
if contents.dtype == np.dtype(object):
342349
if prefix:
343-
jobstring += "%s = {...\n"%(prefix)
350+
jobstring += "%s = {...\n" % (prefix)
344351
else:
345352
jobstring += "{...\n"
346-
for i,val in enumerate(contents):
353+
for i, val in enumerate(contents):
347354
if isinstance(val, np.ndarray):
348355
jobstring += self._generate_job(prefix=None,
349356
contents=val)
350-
elif isinstance(val,str):
351-
jobstring += '\'%s\';...\n'%(val)
357+
elif isinstance(val, str):
358+
jobstring += '\'%s\';...\n' % (val)
352359
else:
353-
jobstring += '%s;...\n'%str(val)
360+
jobstring += '%s;...\n' % str(val)
354361
jobstring += '};\n'
355362
else:
356-
for i,val in enumerate(contents):
363+
for i, val in enumerate(contents):
357364
for field in val.dtype.fields:
358365
if prefix:
359-
newprefix = "%s(%d).%s"%(prefix, i+1, field)
366+
newprefix = "%s(%d).%s" % (prefix, i + 1, field)
360367
else:
361-
newprefix = "(%d).%s"%(i+1, field)
368+
newprefix = "(%d).%s" % (i + 1, field)
362369
jobstring += self._generate_job(newprefix,
363370
val[field])
364371
return jobstring
365372
if isinstance(contents, str):
366-
jobstring += "%s = '%s';\n" % (prefix,contents)
373+
jobstring += "%s = '%s';\n" % (prefix, contents)
367374
return jobstring
368-
jobstring += "%s = %s;\n" % (prefix,str(contents))
375+
jobstring += "%s = %s;\n" % (prefix, str(contents))
369376
return jobstring
370377

371378
def _make_matlab_command(self, contents, postscript=None):
@@ -387,7 +394,7 @@ def _make_matlab_command(self, contents, postscript=None):
387394
388395
"""
389396
cwd = os.getcwd()
390-
mscript = """
397+
mscript = """
391398
%% Generated by nipype.interfaces.spm
392399
if isempty(which('spm')),
393400
throw(MException('SPMCheck:NotFound','SPM not in matlab path'));
@@ -400,19 +407,23 @@ def _make_matlab_command(self, contents, postscript=None):
400407
if strcmp(spm('ver'),'SPM8'), spm_jobman('initcfg');end\n
401408
"""
402409
if self.mlab.inputs.mfile:
403-
if self.jobname in ['st','smooth','preproc','preproc8','fmri_spec','fmri_est',
404-
'factorial_design', 'defs'] :
410+
if self.jobname in ['st', 'smooth', 'preproc', 'preproc8',
411+
'fmri_spec', 'fmri_est', 'factorial_design',
412+
'defs']:
405413
# parentheses
406414
mscript += self._generate_job('jobs{1}.%s{1}.%s(1)' %
407-
(self.jobtype,self.jobname), contents[0])
415+
(self.jobtype, self.jobname),
416+
contents[0])
408417
else:
409418
#curly brackets
410419
mscript += self._generate_job('jobs{1}.%s{1}.%s{1}' %
411-
(self.jobtype,self.jobname), contents[0])
420+
(self.jobtype, self.jobname),
421+
contents[0])
412422
else:
413-
jobdef = {'jobs':[{self.jobtype:[{self.jobname:self.reformat_dict_for_savemat
414-
(contents[0])}]}]}
415-
savemat(os.path.join(cwd,'pyjobs_%s.mat'%self.jobname), jobdef)
423+
jobdef = {'jobs': [{self.jobtype:
424+
[{self.jobname:self.reformat_dict_for_savemat
425+
(contents[0])}]}]}
426+
savemat(os.path.join(cwd, 'pyjobs_%s.mat' % self.jobname), jobdef)
416427
mscript += "load pyjobs_%s;\n\n" % self.jobname
417428
mscript += """
418429
if strcmp(spm('ver'),'SPM8'),

0 commit comments

Comments
 (0)