def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == 'target' or opt == 'source': return scans_for_fnames(filename_to_list(val), keep4d=True) if opt == 'apply_to_files': return scans_for_fnames(filename_to_list(val)) return val
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt in ["image_files"]: return scans_for_fnames(val, keep4d=True, separate_sessions=True) if opt in ["flowfield_files"]: return scans_for_fnames(val, keep4d=True) else: return val
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == "target" or (opt == "source" and self.inputs.jobtype != "write"): return scans_for_fnames(filename_to_list(val), keep4d=True) if opt == "apply_to_files": return scans_for_fnames(filename_to_list(val)) if opt == "source" and self.inputs.jobtype == "write": if isdefined(self.inputs.apply_to_files): return scans_for_fnames(val + self.inputs.apply_to_files) else: return scans_for_fnames(val) return val
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt in ["deformation_field", "reference_volume"]: val = [val] if opt in ["deformation_field"]: return scans_for_fnames(val, keep4d=True, separate_sessions=False) if opt in ["in_files", "reference_volume"]: return scans_for_fnames(val, keep4d=False, separate_sessions=False) else: return super(ApplyDeformations, self)._format_arg(opt, spec, val)
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == 'target' or (opt == 'source' and self.inputs.jobtype != "write"): return scans_for_fnames(filename_to_list(val), keep4d=True) if opt == 'apply_to_files': return np.array(filename_to_list(val), dtype=object) if opt == 'source' and self.inputs.jobtype == "write": if isdefined(self.inputs.apply_to_files): return scans_for_fnames(val+self.inputs.apply_to_files) else: return scans_for_fnames(val) return val
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt in ["image_files"]: return scans_for_fnames(val, keep4d=True, separate_sessions=True) elif opt == "regularization_form": mapper = {"Linear": 0, "Membrane": 1, "Bending": 2} return mapper[val] elif opt == "iteration_parameters": params = [] for param in val: new_param = {} new_param["its"] = param[0] new_param["rparam"] = list(param[1]) new_param["K"] = param[2] new_param["slam"] = param[3] params.append(new_param) return params elif opt == "optimization parameters": new_param = {} new_param["lmreg"] = val[0] new_param["cyc"] = val[1] new_param["its"] = val[2] return [new_param] else: return val
def _run_interface(self, runtime): from nipype.interfaces.spm.base import scans_for_fname,scans_for_fnames from nipype.utils.filemanip import filename_to_list,list_to_filename # setup parameters input_dir = "." in_files = "{" asl_first = str(self.inputs.first_image_type) TR = str(self.inputs.TR) # convert images to cell array string in matlab for f in sorted(scans_for_fnames(filename_to_list(self.inputs.in_files))): in_files += "'"+f+"',\n" input_dir = os.path.dirname(f) in_files = in_files[:-2]+"}" self.input_dir = input_dir d = dict(in_files=in_files,in_dir=input_dir,first_image_type=asl_first,TR =TR) myscript = Template(""" warning('off','all'); cd('$in_dir'); input = char($in_files); asl_script(input,$first_image_type,0,$TR); exit; """).substitute(d) mlab = MatlabCommand(script=myscript,matlab_cmd="matlab -nodesktop -nosplash",mfile=True) result = mlab.run() return result.runtime
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm""" import numpy as np if opt in ["image_files"]: return scans_for_fnames(val, keep4d=True, separate_sessions=True) elif opt == "regularization_form": mapper = {"Linear": 0, "Membrane": 1, "Bending": 2} return mapper[val] elif opt == "iteration_parameters": params = [] for param in val: new_param = {} new_param["its"] = param[0] new_param["rparam"] = list(param[1]) new_param["K"] = param[2] new_param["template"] = np.array([param[3]], dtype=object) params.append(new_param) return params elif opt == "optimization_parameters": new_param = {} new_param["lmreg"] = val[0] new_param["cyc"] = val[1] new_param["its"] = val[2] return [new_param] else: return super(DARTELExistingTemplate, self)._format_arg(opt, spec, val)
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt in ['channel_files', 'channel_info']: # structure have to be recreated because of some weird traits error new_channel = {} new_channel['vols'] = scans_for_fnames(self.inputs.channel_files) if isdefined(self.inputs.channel_info): info = self.inputs.channel_info new_channel['biasreg'] = info[0] new_channel['biasfwhm'] = info[1] new_channel['write'] = [int(info[2][0]), int(info[2][1])] return [new_channel] elif opt == 'tissues': new_tissues = [] for tissue in val: new_tissue = {} new_tissue['tpm'] = np.array( [','.join([tissue[0][0], str(tissue[0][1])])], dtype=object) new_tissue['ngaus'] = tissue[1] new_tissue['native'] = [int(tissue[2][0]), int(tissue[2][1])] new_tissue['warped'] = [int(tissue[3][0]), int(tissue[3][1])] new_tissues.append(new_tissue) return new_tissues elif opt == 'write_deformation_fields': return super(MultiChannelSegment, self)._format_arg( opt, spec, [int(val[0]), int(val[1])]) else: return super(MultiChannelSegment, self)._format_arg(opt, spec, val)
def test_generate_job(): class TestClass(spm.SPMCommand): input_spec = spm.SPMCommandInputSpec dc = TestClass() # dc = derived_class out = dc._generate_job() yield assert_equal, out, '' # struct array contents = {'contents': [1, 2, 3, 4]} out = dc._generate_job(contents=contents) yield assert_equal, out, ('.contents(1) = 1;\n.contents(2) = 2;' '\n.contents(3) = 3;\n.contents(4) = 4;\n') # cell array of strings filelist, outdir, cwd = create_files_in_directory() names = spm.scans_for_fnames(filelist, keep4d=True) contents = {'files': names} out = dc._generate_job(prefix='test', contents=contents) yield assert_equal, out, "test.files = {...\n'a.nii';...\n'b.nii';...\n};\n" clean_directory(outdir, cwd) # string assignment contents = 'foo' out = dc._generate_job(prefix='test', contents=contents) yield assert_equal, out, "test = 'foo';\n" # cell array of vectors contents = {'onsets': np.array((1, ), dtype=object)} contents['onsets'][0] = [1, 2, 3, 4] out = dc._generate_job(prefix='test', contents=contents) yield assert_equal, out, 'test.onsets = {...\n[1, 2, 3, 4];...\n};\n'
def test_generate_job(create_files_in_directory): class TestClass(spm.SPMCommand): input_spec = spm.SPMCommandInputSpec dc = TestClass() # dc = derived_class out = dc._generate_job() assert out == "" # struct array contents = {"contents": [1, 2, 3, 4]} out = dc._generate_job(contents=contents) assert out == (".contents(1) = 1;\n.contents(2) = 2;" "\n.contents(3) = 3;\n.contents(4) = 4;\n") # cell array of strings filelist, outdir = create_files_in_directory names = spm.scans_for_fnames(filelist, keep4d=True) contents = {"files": names} out = dc._generate_job(prefix="test", contents=contents) assert out == "test.files = {...\n'a.nii';...\n'b.nii';...\n};\n" # string assignment contents = "foo" out = dc._generate_job(prefix="test", contents=contents) assert out == "test = 'foo';\n" # cell array of vectors contents = {"onsets": np.array((1, ), dtype=object)} contents["onsets"][0] = [1, 2, 3, 4] out = dc._generate_job(prefix="test", contents=contents) assert out == "test.onsets = {...\n[1, 2, 3, 4];...\n};\n"
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt in ["channel_files", "channel_info"]: # structure have to be recreated, because of some weird traits error new_channel = {} new_channel["vols"] = scans_for_fnames(self.inputs.channel_files) if isdefined(self.inputs.channel_info): info = self.inputs.channel_info new_channel["biasreg"] = info[0] new_channel["biasfwhm"] = info[1] new_channel["write"] = [int(info[2][0]), int(info[2][1])] return [new_channel] elif opt == "tissues": new_tissues = [] for tissue in val: new_tissue = {} new_tissue["tpm"] = np.array([",".join([tissue[0][0], str(tissue[0][1])])], dtype=object) new_tissue["ngaus"] = tissue[1] new_tissue["native"] = [int(tissue[2][0]), int(tissue[2][1])] new_tissue["warped"] = [int(tissue[3][0]), int(tissue[3][1])] new_tissues.append(new_tissue) return new_tissues elif opt == "write_deformation_fields": return super(NewSegment, self)._format_arg(opt, spec, [int(val[0]), int(val[0])]) else: return super(NewSegment, self)._format_arg(opt, spec, val)
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt in ['image_files']: return scans_for_fnames(val, keep4d=True, separate_sessions=True) elif opt == 'regularization_form': mapper = {'Linear':0, 'Membrane':1, 'Bending':2} return mapper[val] elif opt == 'iteration_parameters': params = [] for param in val: new_param = {} new_param['its'] = param[0] new_param['rparam'] = list(param[1]) new_param['K'] = param[2] new_param['slam'] = param[3] params.append(new_param) return params elif opt == 'optimization parameters': new_param = {} new_param['lmreg'] = val[0] new_param['cyc'] = val[1] new_param['its'] = val[2] return [new_param] else: return val
def test_generate_job(create_files_in_directory): class TestClass(spm.SPMCommand): input_spec = spm.SPMCommandInputSpec dc = TestClass() # dc = derived_class out = dc._generate_job() assert out == '' # struct array contents = {'contents': [1, 2, 3, 4]} out = dc._generate_job(contents=contents) assert out == ('.contents(1) = 1;\n.contents(2) = 2;' '\n.contents(3) = 3;\n.contents(4) = 4;\n') # cell array of strings filelist, outdir = create_files_in_directory names = spm.scans_for_fnames(filelist, keep4d=True) contents = {'files': names} out = dc._generate_job(prefix='test', contents=contents) assert out == "test.files = {...\n'a.nii';...\n'b.nii';...\n};\n" # string assignment contents = 'foo' out = dc._generate_job(prefix='test', contents=contents) assert out == "test = 'foo';\n" # cell array of vectors contents = {'onsets': np.array((1,), dtype=object)} contents['onsets'][0] = [1, 2, 3, 4] out = dc._generate_job(prefix='test', contents=contents) assert out == 'test.onsets = {...\n[1, 2, 3, 4];...\n};\n'
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ import numpy as np if opt in ['image_files']: return scans_for_fnames(val, keep4d=True, separate_sessions=True) elif opt == 'regularization_form': mapper = {'Linear': 0, 'Membrane': 1, 'Bending': 2} return mapper[val] elif opt == 'iteration_parameters': params = [] for param in val: new_param = {} new_param['its'] = param[0] new_param['rparam'] = list(param[1]) new_param['K'] = param[2] new_param['template'] = np.array([param[3]], dtype=object) params.append(new_param) return params elif opt == 'optimization_parameters': new_param = {} new_param['lmreg'] = val[0] new_param['cyc'] = val[1] new_param['its'] = val[2] return [new_param] else: return super(DARTELExistingTemplate, self)._format_arg(opt, spec, val)
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == 'in_files': return scans_for_fnames(filename_to_list(val), keep4d=False, separate_sessions=True) return val
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == "in_files": return scans_for_fnames(val, keep4d=True, separate_sessions=True) if opt == "register_to_mean": # XX check if this is necessary return int(val) return val
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for SPM """ if opt in ['in_files']: return scans_for_fnames(filename_to_list(val), keep4d=False) if opt == 'deformation_field': return np.array([list_to_filename(val)], dtype=object) return super(ApplyDeformationField, self)._format_arg(opt, spec, val)
def _parse_inputs(self): """validate spm realign options if set to None ignore """ einputs = super(Level1Design, self)._parse_inputs(skip=('mask_threshold')) for sessinfo in einputs[0]['sess']: sessinfo['scans'] = scans_for_fnames(filename_to_list(sessinfo['scans']), keep4d=False) if not isdefined(self.inputs.spm_mat_dir): einputs[0]['dir'] = np.array([str(os.getcwd())], dtype=object) return einputs
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm""" if opt == "in_files": if isinstance(val, list): return scans_for_fnames(val) else: return scans_for_fname(val) return super(CAT12SANLMDenoising, self)._format_arg(opt, spec, val)
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm""" if opt == "in_files": if isinstance(val, list): return scans_for_fnames(val) else: return scans_for_fname(val) elif opt in ["tpm", "shooting_tpm"]: return Cell2Str(val) return super(CAT12Segment, self)._format_arg(opt, spec, val)
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm""" if opt == "in_files": if isinstance(val, list): return scans_for_fnames(val) else: return scans_for_fname(val) if opt == "spm_type": type_map = {"same": 0, "uint8": 2, "uint16": 512, "float32": 16} val = type_map[val] return super(CAT12SANLMDenoising, self)._format_arg(opt, spec, val)
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == 'in_files': return scans_for_fnames(filename_to_list(val)) if opt == 'target': return scans_for_fname(filename_to_list(val)) if opt == 'deformation': return np.array([list_to_filename(val)], dtype=object) if opt == 'deformation_field': return np.array([list_to_filename(val)], dtype=object) return val
def _format_arg(self, opt, spec, val): if opt in ["in_files"]: return scans_for_fnames(filename_to_list(val)) if opt == "fwhm": if not isinstance(val, list): return [val, val, val] if isinstance(val, list): if len(val) == 1: return [val[0], val[0], val[0]] else: return val return val
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt in ["template_file"]: return np.array([val], dtype=object) elif opt in ["flowfield_files"]: return scans_for_fnames(val, keep4d=True) elif opt in ["apply_to_files"]: return scans_for_fnames(val, keep4d=True, separate_sessions=True) elif opt == "voxel_size": return list(val) elif opt == "bounding_box": return list(val) elif opt == "fwhm": if not isinstance(val, tuple): return [val, val, val] if isinstance(val, tuple): return val elif opt == "modulate": return int(val) else: return val
def _parse_inputs(self): """validate spm realign options if set to None ignore """ einputs = super(Normalize, self)._parse_inputs(skip=("jobtype", "apply_to_files")) if isdefined(self.inputs.apply_to_files): inputfiles = deepcopy(self.inputs.apply_to_files) if isdefined(self.inputs.source): inputfiles.extend(self.inputs.source) einputs[0]["subj"]["resample"] = scans_for_fnames(inputfiles) jobtype = self.inputs.jobtype if jobtype in ["estwrite", "write"]: if not isdefined(self.inputs.apply_to_files): if isdefined(self.inputs.source): einputs[0]["subj"]["resample"] = scans_for_fname(self.inputs.source) return [{"%s" % (jobtype): einputs[0]}]
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == "template": return scans_for_fname(filename_to_list(val)) if opt == "source": return scans_for_fname(filename_to_list(val)) if opt == "apply_to_files": return scans_for_fnames(filename_to_list(val)) if opt == "parameter_file": return np.array([list_to_filename(val)], dtype=object) if opt in ["write_wrap"]: if len(val) != 3: raise ValueError("%s must have 3 elements" % opt) return val
def _format_arg(self, opt, spec, val): if opt in ['in_files']: return scans_for_fnames(filename_to_list(val)) if opt == 'fwhm': if not isinstance(val, list): return [val, val, val] if isinstance(val, list): if len(val) == 1: return [val[0], val[0], val[0]] else: return val if opt == 'implicit_masking': return int(val) return val
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == 'template': return scans_for_fname(filename_to_list(val)) if opt == 'source': return scans_for_fname(filename_to_list(val)) if opt == 'apply_to_files': return scans_for_fnames(filename_to_list(val)) if opt == 'parameter_file': return np.array([list_to_filename(val)], dtype=object) if opt in ['write_wrap']: if len(val) != 3: raise ValueError('%s must have 3 elements' % opt) return super(Normalize, self)._format_arg(opt, spec, val)
def _parse_inputs(self): """validate spm realign options if set to None ignore """ einputs = super(Normalize, self)._parse_inputs(skip=('jobtype', 'apply_to_files')) if isdefined(self.inputs.apply_to_files): inputfiles = deepcopy(self.inputs.apply_to_files) if isdefined(self.inputs.source): inputfiles.extend(self.inputs.source) einputs[0]['subj']['resample'] = scans_for_fnames(inputfiles) jobtype = self.inputs.jobtype if jobtype in ['estwrite', 'write']: if not isdefined(self.inputs.apply_to_files): if isdefined(self.inputs.source): einputs[0]['subj']['resample'] = scans_for_fname(self.inputs.source) return [{'%s' % (jobtype):einputs[0]}]
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == 'in_files': infiles = scans_for_fnames(val, keep4d=True, separate_sessions=True) #return self._reformat_dict_for_savemat(dict(scans = infiles)) return infiles #if opt == 'phase_map': # infiles = val # return self._reformat_dict_for_savemat(dict(pmscan = infiles)) if opt == 'register_to_mean': # XX check if this is necessary return int(val) return val
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ clean_masks_dict = {'no':0, 'light':1, 'thorough':2} if opt in ['data', 'tissue_prob_maps']: if isinstance(val, list): return scans_for_fnames(val) else: return scans_for_fname(val) if 'output_type' in opt: return [int(v) for v in val] if opt == 'save_bias_corrected': return int(val) if opt == 'mask_image': return scans_for_fname(val) if opt == 'clean_masks': return clean_masks_dict[val] return val
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ clean_masks_dict = {"no": 0, "light": 1, "thorough": 2} if opt in ["data", "tissue_prob_maps"]: if isinstance(val, list): return scans_for_fnames(val) else: return scans_for_fname(val) if "output_type" in opt: return [int(v) for v in val] if opt == "save_bias_corrected": return int(val) if opt == "mask_image": return scans_for_fname(val) if opt == "clean_masks": return clean_masks_dict[val] return val
def _list_outputs(self): import scipy.io as sp #setup subject input_dir = "." for f in scans_for_fnames(filename_to_list(self.inputs.in_files)): input_dir = os.path.dirname(f) break pt = re.compile(".*/embarc_CU_(.*)_mri_fmriraw.*") mt = pt.match(input_dir) if mt: subject = mt.group(1) # get the float value mat = sp.loadmat(os.path.abspath(input_dir+"/mean_CBF_spm_save.mat"),squeeze_me=True) outputs = self._outputs().get() outputs['cbf_image'] = os.path.abspath(input_dir+"/meanCBF_"+subject+".nii") outputs['cbf_value'] = mat['L'] return outputs
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == "channel_files": # structure have to be recreated, because of some weird traits error new_channels = [] for channel in val: new_channel = {} new_channel["vols"] = scans_for_fname(filename_to_list(channel)) new_channels.append(new_channel) return new_channels elif opt == "channel_info": # structure have to be recreated, because of some weird traits error new_channels = [] for channel in val: new_channel = {} new_channel["biasreg"] = channel[0] new_channel["biasfwhm"] = channel[1] new_channel["write"] = [int(channel[2][0]), int(channel[2][1])] new_channels.append(new_channel) return new_channels elif opt == "tissues": new_tissues = [] for tissue in val: new_tissue = {} new_tissue["tpm"] = scans_for_fnames(tissue[0]) new_tissue["ngauss"] = tissue[1] new_tissue["native"] = [int(tissue[2][0]), int(tissue[2][1])] new_tissue["warped"] = [int(tissue[3][0]), int(tissue[3][1])] new_tissues.append(new_tissue) return new_tissues
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt in ['channel_files', 'channel_info']: # structure have to be recreated, because of some weird traits error new_channel = {} new_channel['vols'] = scans_for_fnames(self.inputs.channel_files) if isdefined(self.inputs.channel_info): info = self.inputs.channel_info new_channel['biasreg'] = info[0] new_channel['biasfwhm'] = info[1] new_channel['write'] = [int(info[2][0]), int(info[2][1])] return [new_channel] elif opt == 'tissues': new_tissues = [] for tissue in val: new_tissue = {} new_tissue['tpm'] = np.array([','.join([tissue[0][0], str(tissue[0][1])])], dtype=object) new_tissue['ngaus'] = tissue[1] new_tissue['native'] = [int(tissue[2][0]), int(tissue[2][1])] new_tissue['warped'] = [int(tissue[3][0]), int(tissue[3][1])] new_tissues.append(new_tissue) return new_tissues
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == 'channel_files': # structure have to be recreated, because of some weird traits error new_channels = [] for channel in val: new_channel = {} new_channel['vols'] = scans_for_fname(filename_to_list(channel)) new_channels.append(new_channel) return new_channels elif opt == 'channel_info': # structure have to be recreated, because of some weird traits error new_channels = [] for channel in val: new_channel = {} new_channel['biasreg'] = channel[0] new_channel['biasfwhm'] = channel[1] new_channel['write'] = [int(channel[2][0]), int(channel[2][1])] new_channels.append(new_channel) return new_channels elif opt == 'tissues': new_tissues = [] for tissue in val: new_tissue = {} new_tissue['tpm'] = scans_for_fnames(tissue[0]) new_tissue['ngauss'] = tissue[1] new_tissue['native'] = [int(tissue[2][0]), int(tissue[2][1])] new_tissue['warped'] = [int(tissue[3][0]), int(tissue[3][1])] new_tissues.append(new_tissue) return new_tissues
def test_scan_for_fnames(create_files_in_directory): filelist, outdir = create_files_in_directory names = spm.scans_for_fnames(filelist, keep4d=True) assert names[0] == filelist[0] assert names[1] == filelist[1]
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == 'in_file': return scans_for_fnames(filename_to_list(val)) return val
def test_scan_for_fnames(): filelist, outdir, cwd = create_files_in_directory() names = spm.scans_for_fnames(filelist, keep4d=True) yield assert_equal, names[0], filelist[0] yield assert_equal, names[1], filelist[1] clean_directory(outdir, cwd)
def _format_arg(self, opt, spec, val): """Convert input to appropriate format for spm """ if opt == 'scans' or opt == 'pmscan': return scans_for_fnames(filename_to_list(val)) return super(RealignUnwarp, self)._format_arg(opt, spec, val)