25
25
from ... import logging
26
26
logger = logging .getLogger ('interface' )
27
27
28
+
28
29
def func_is_3d (in_file ):
29
30
"""Checks if input functional files are 3d."""
30
31
@@ -33,41 +34,44 @@ def func_is_3d(in_file):
33
34
else :
34
35
img = load (in_file )
35
36
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 ):
37
38
return True
38
39
else :
39
40
return False
40
41
42
+
41
43
def get_first_3dfile (in_files ):
42
44
if not func_is_3d (in_files ):
43
45
return None
44
46
if isinstance (in_files [0 ], list ):
45
47
return in_files [0 ]
46
48
return in_files
47
49
50
+
48
51
def scans_for_fname (fname ):
49
52
"""Reads a nifti file and converts it to a numpy array storing
50
53
individual nifti volumes.
51
54
52
55
Opens images so will fail if they are not found.
53
56
54
57
"""
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
59
62
return scans
60
63
img = load (fname )
61
64
if len (img .get_shape ()) == 3 :
62
- return np .array (('%s,1' % fname ,),dtype = object )
65
+ return np .array (('%s,1' % fname ,), dtype = object )
63
66
else :
64
67
n_scans = img .get_shape ()[3 ]
65
- scans = np .zeros ((n_scans ,),dtype = object )
68
+ scans = np .zeros ((n_scans ,), dtype = object )
66
69
for sno in range (n_scans ):
67
- scans [sno ] = '%s,%d' % (fname , sno + 1 )
70
+ scans [sno ] = '%s,%d' % (fname , sno + 1 )
68
71
return scans
69
72
70
- def scans_for_fnames (fnames ,keep4d = False ,separate_sessions = False ):
73
+
74
+ def scans_for_fnames (fnames , keep4d = False , separate_sessions = False ):
71
75
"""Converts a list of files to a concatenated numpy array for each
72
76
volume.
73
77
@@ -84,14 +88,14 @@ def scans_for_fnames(fnames,keep4d=False,separate_sessions=False):
84
88
if func_is_3d (fnames [0 ]):
85
89
fnames = [fnames ]
86
90
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 ):
89
93
if separate_sessions :
90
94
if keep4d :
91
- if isinstance (f ,list ):
95
+ if isinstance (f , list ):
92
96
flist [i ] = np .array (f , dtype = object )
93
97
else :
94
- flist [i ] = np .array ([f ],dtype = object )
98
+ flist [i ] = np .array ([f ], dtype = object )
95
99
else :
96
100
flist [i ] = scans_for_fname (f )
97
101
else :
@@ -102,14 +106,15 @@ def scans_for_fnames(fnames,keep4d=False,separate_sessions=False):
102
106
if flist is None :
103
107
flist = scans
104
108
else :
105
- flist = np .concatenate ((flist ,scans ))
109
+ flist = np .concatenate ((flist , scans ))
106
110
return flist
107
111
112
+
108
113
class Info (object ):
109
114
"""Handles SPM version information
110
115
"""
111
116
@staticmethod
112
- def version ( matlab_cmd = None ):
117
+ def version (matlab_cmd = None ):
113
118
"""Returns the path to the SPM directory in the Matlab path
114
119
If path not found, returns None.
115
120
@@ -132,20 +137,20 @@ def version( matlab_cmd = None ):
132
137
matlab_cmd = os .environ ['MATLABCMD' ]
133
138
except :
134
139
matlab_cmd = 'matlab -nodesktop -nosplash'
135
- mlab = MatlabCommand (matlab_cmd = matlab_cmd )
140
+ mlab = MatlabCommand (matlab_cmd = matlab_cmd )
136
141
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;
144
149
"""
145
150
mlab .inputs .mfile = False
146
151
try :
147
152
out = mlab .run ()
148
- except (IOError ,RuntimeError ), e :
153
+ except (IOError , RuntimeError ), e :
149
154
# if no Matlab at all -- exception could be raised
150
155
# No Matlab -- no spm
151
156
logger .debug (str (e ))
@@ -158,12 +163,13 @@ def version( matlab_cmd = None ):
158
163
out_dict [key ] = val
159
164
return out_dict
160
165
166
+
161
167
def no_spm ():
162
168
""" Checks if SPM is NOT installed
163
169
used with nosetests skipif to skip tests
164
170
that will fail if spm is not installed"""
165
171
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 :
167
173
return True
168
174
else :
169
175
return False
@@ -173,9 +179,10 @@ class SPMCommandInputSpec(BaseInterfaceInputSpec):
173
179
matlab_cmd = traits .Str (desc = 'matlab command to use' )
174
180
paths = InputMultiPath (Directory (), desc = 'Paths to add to matlabpath' )
175
181
mfile = traits .Bool (True , desc = 'Run m-code using m-file' ,
176
- usedefault = True )
182
+ usedefault = True )
177
183
use_mcr = traits .Bool (desc = 'Run m-code using SPM MCR' )
178
184
185
+
179
186
class SPMCommand (BaseInterface ):
180
187
"""Extends `BaseInterface` class to implement SPM specific interfaces.
181
188
@@ -200,7 +207,7 @@ def __init__(self, **inputs):
200
207
self ._matlab_cmd_update ()
201
208
202
209
@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 ):
204
211
cls ._matlab_cmd = matlab_cmd
205
212
cls ._paths = paths
206
213
cls ._use_mcr = use_mcr
@@ -214,7 +221,7 @@ def _matlab_cmd_update(self):
214
221
paths = self .inputs .paths ,
215
222
uses_mcr = self .inputs .use_mcr )
216
223
self .mlab .inputs .script_file = 'pyscript_%s.m' % \
217
- self .__class__ .__name__ .split ('.' )[- 1 ].lower ()
224
+ self .__class__ .__name__ .split ('.' )[- 1 ].lower ()
218
225
219
226
@property
220
227
def jobtype (self ):
@@ -234,7 +241,8 @@ def _check_mlab_inputs(self):
234
241
235
242
def _run_interface (self , runtime ):
236
243
"""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 ()))
238
246
results = self .mlab .run ()
239
247
runtime .returncode = results .runtime .returncode
240
248
if self .mlab .inputs .uses_mcr :
@@ -250,7 +258,6 @@ def _list_outputs(self):
250
258
251
259
raise NotImplementedError
252
260
253
-
254
261
def _format_arg (self , opt , spec , val ):
255
262
"""Convert input to appropriate format for SPM."""
256
263
if spec .is_trait_type (traits .Bool ):
@@ -260,7 +267,7 @@ def _format_arg(self, opt, spec, val):
260
267
261
268
def _parse_inputs (self , skip = ()):
262
269
spmdict = {}
263
- metadata = dict (field = lambda t : t is not None )
270
+ metadata = dict (field = lambda t : t is not None )
264
271
for name , spec in self .inputs .traits (** metadata ).items ():
265
272
if skip and name in skip :
266
273
continue
@@ -325,47 +332,47 @@ def _generate_job(self, prefix='', contents=None):
325
332
if contents is None :
326
333
return jobstring
327
334
if isinstance (contents , list ):
328
- for i ,value in enumerate (contents ):
335
+ for i , value in enumerate (contents ):
329
336
if prefix .endswith (")" ):
330
- newprefix = "%s,%d)" % (prefix [:- 1 ], i + 1 )
337
+ newprefix = "%s,%d)" % (prefix [:- 1 ], i + 1 )
331
338
else :
332
- newprefix = "%s(%d)" % (prefix , i + 1 )
339
+ newprefix = "%s(%d)" % (prefix , i + 1 )
333
340
jobstring += self ._generate_job (newprefix , value )
334
341
return jobstring
335
342
if isinstance (contents , dict ):
336
- for key ,value in contents .items ():
343
+ for key , value in contents .items ():
337
344
newprefix = "%s.%s" % (prefix , key )
338
345
jobstring += self ._generate_job (newprefix , value )
339
346
return jobstring
340
347
if isinstance (contents , np .ndarray ):
341
348
if contents .dtype == np .dtype (object ):
342
349
if prefix :
343
- jobstring += "%s = {...\n " % (prefix )
350
+ jobstring += "%s = {...\n " % (prefix )
344
351
else :
345
352
jobstring += "{...\n "
346
- for i ,val in enumerate (contents ):
353
+ for i , val in enumerate (contents ):
347
354
if isinstance (val , np .ndarray ):
348
355
jobstring += self ._generate_job (prefix = None ,
349
356
contents = val )
350
- elif isinstance (val ,str ):
351
- jobstring += '\' %s\' ;...\n ' % (val )
357
+ elif isinstance (val , str ):
358
+ jobstring += '\' %s\' ;...\n ' % (val )
352
359
else :
353
- jobstring += '%s;...\n ' % str (val )
360
+ jobstring += '%s;...\n ' % str (val )
354
361
jobstring += '};\n '
355
362
else :
356
- for i ,val in enumerate (contents ):
363
+ for i , val in enumerate (contents ):
357
364
for field in val .dtype .fields :
358
365
if prefix :
359
- newprefix = "%s(%d).%s" % (prefix , i + 1 , field )
366
+ newprefix = "%s(%d).%s" % (prefix , i + 1 , field )
360
367
else :
361
- newprefix = "(%d).%s" % ( i + 1 , field )
368
+ newprefix = "(%d).%s" % ( i + 1 , field )
362
369
jobstring += self ._generate_job (newprefix ,
363
370
val [field ])
364
371
return jobstring
365
372
if isinstance (contents , str ):
366
- jobstring += "%s = '%s';\n " % (prefix ,contents )
373
+ jobstring += "%s = '%s';\n " % (prefix , contents )
367
374
return jobstring
368
- jobstring += "%s = %s;\n " % (prefix ,str (contents ))
375
+ jobstring += "%s = %s;\n " % (prefix , str (contents ))
369
376
return jobstring
370
377
371
378
def _make_matlab_command (self , contents , postscript = None ):
@@ -387,7 +394,7 @@ def _make_matlab_command(self, contents, postscript=None):
387
394
388
395
"""
389
396
cwd = os .getcwd ()
390
- mscript = """
397
+ mscript = """
391
398
%% Generated by nipype.interfaces.spm
392
399
if isempty(which('spm')),
393
400
throw(MException('SPMCheck:NotFound','SPM not in matlab path'));
@@ -400,19 +407,23 @@ def _make_matlab_command(self, contents, postscript=None):
400
407
if strcmp(spm('ver'),'SPM8'), spm_jobman('initcfg');end\n
401
408
"""
402
409
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' ]:
405
413
# parentheses
406
414
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 ])
408
417
else :
409
418
#curly brackets
410
419
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 ])
412
422
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 )
416
427
mscript += "load pyjobs_%s;\n \n " % self .jobname
417
428
mscript += """
418
429
if strcmp(spm('ver'),'SPM8'),
0 commit comments