本文整理汇总了Python中nipype.interfaces.matlab.MatlabCommand类的典型用法代码示例。如果您正苦于以下问题:Python MatlabCommand类的具体用法?Python MatlabCommand怎么用?Python MatlabCommand使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MatlabCommand类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _run_interface
def _run_interface(self, runtime):
from nipype.interfaces.matlab import MatlabCommand
def islist(i):
if not isinstance(i,list):
i = [str(i)]
return i
else:
I = []
for l in i:
if not l.endswith('.par'):
I.append(str(l))
else:
shutil.copy2(l,l+'.txt')
I.append(l+'.txt')
return I
info = {}
info["functional_files"] = islist(self.inputs.functional_files)
info["structural_files"] = islist(self.inputs.structural_files)
info["csf_mask"] = islist(self.inputs.csf_mask)
info["white_mask"] = islist(self.inputs.white_mask)
info["grey_mask"] = islist(self.inputs.grey_mask)
info["TR"] = float(self.inputs.tr)
info["realignment_parameters"] = islist(self.inputs.realignment_parameters)
info["outliers"] = islist(self.inputs.outliers)
info["norm_components"] = islist(self.inputs.norm_components)
info["filename"] = '%s/conn_%s.mat'%(os.getcwd(),self.inputs.project_name)
info["n_subjects"] = int(self.inputs.n_subjects)
conn_inputs = os.path.abspath('inputs_to_conn.mat')
sio.savemat(conn_inputs, {"in":info})
print "saved conn_inputs.mat file"
script="""load %s; batch=bips_load_conn(in); conn_batch(batch)"""%conn_inputs
mlab = MatlabCommand(script=script, mfile=True)
result = mlab.run()
return result.runtime
示例2: _run_interface
def _run_interface(self, runtime):
d = dict(worldmat=self.inputs.worldmat,
src=self.inputs.src,
trg=self.inputs.trg,
output_file=self.inputs.output_file)
#this is your MATLAB code template
script = Template("""worldmat = '$worldmat';
src = '$src';
trg = '$trg';
output_file = '$output_file'
worldmat2flirtmap(worldmat, src, trg, output_file);
exit;
""").substitute(d)
# mfile = True will create an .m file with your script and executed.
# Alternatively
# mfile can be set to False which will cause the matlab code to be
# passed
# as a commandline argument to the matlab executable
# (without creating any files).
# This, however, is less reliable and harder to debug
# (code will be reduced to
# a single line and stripped of any comments).
mlab = MatlabCommand(script=script, mfile=True)
result = mlab.run()
return result.runtime
示例3: _run_interface
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
示例4: _run_interface
def _run_interface(self, runtime):
d = dict(in_file=self.inputs.in_file,mask_file=self.inputs.mask_file,out_file=self.inputs.out_file)
script = Template("""addpath('/home/sharad/fcon1000/lib/');in_file = '$in_file';mask_file = '$mask_file';out_file = '$out_file';reho(in_file,mask_file,out_file);exit;""").substitute(d)
mlab = MatlabCommand(script=script, mfile=True)
result = mlab.run()
return result.runtime
示例5: _run_interface
def _run_interface(self, runtime):
d = dict(in_file=self.inputs.in_file,
out_folder=self.inputs.out_folder,
subject_id=self.inputs.subject_id)
#this is your MATLAB code template
script = Template("""
cd '$out_folder'
WaveletDespike('$in_file','$subject_id')""").substitute(d)
mlab = MatlabCommand(script=script, mfile=True)
result = mlab.run()
return result.runtime
示例6: _matlab_cmd_update
def _matlab_cmd_update(self):
# MatlabCommand has to be created here,
# because matlab_cmb is not a proper input
# and can be set only during init
self.mlab = MatlabCommand(matlab_cmd=self.inputs.matlab_cmd,
mfile=self.inputs.mfile,
paths=self.inputs.paths)
self.mlab.inputs.script_file = 'pyscript_%s.m' % \
self.__class__.__name__.split('.')[-1].lower()
示例7: version
def version( matlab_cmd = None ):
"""Returns the path to the SPM directory in the Matlab path
If path not found, returns None.
Parameters
----------
matlab_cmd : String specifying default matlab command
default None, will look for environment variable MATLABCMD
and use if found, otherwise falls back on MatlabCommand
default of 'matlab -nodesktop -nosplash'
Returns
-------
spm_path : string representing path to SPM directory
returns None of path not found
"""
if matlab_cmd is None:
try:
matlab_cmd = os.environ['MATLABCMD']
except:
matlab_cmd = 'matlab -nodesktop -nosplash'
mlab = MatlabCommand(matlab_cmd = matlab_cmd)
mlab.inputs.script = """
if isempty(which('spm')),
throw(MException('SPMCheck:NotFound','SPM not in matlab path'));
end;
spm_path = spm('dir');
[name, version] = spm('ver');
fprintf(1, 'NIPYPE path:%s|name:%s|release:%s', spm_path, name, version);
exit;
"""
mlab.inputs.mfile = False
try:
out = mlab.run()
except (IOError,RuntimeError), e:
# if no Matlab at all -- exception could be raised
# No Matlab -- no spm
logger.debug(str(e))
return None
示例8: version
def version( matlab_cmd = None ):
"""Returns the path to the SPM directory in the Matlab path
If path not found, returns None.
Parameters
----------
matlab_cmd : String specifying default matlab command
default None, will look for environment variable MATLABCMD
and use if found, otherwise falls back on MatlabCommand
default of 'matlab -nodesktop -nosplash'
Returns
-------
spm_path : string representing path to SPM directory
returns None of path not found
"""
if matlab_cmd is None:
try:
matlab_cmd = os.environ['MATLABCMD']
except:
matlab_cmd = 'matlab -nodesktop -nosplash'
mlab = MatlabCommand(matlab_cmd = matlab_cmd)
mlab.inputs.script_file = 'spminfo'
mlab.inputs.script = """
if isempty(which('spm')),
throw(MException('SPMCheck:NotFound','SPM not in matlab path'));
end;
spm_path = spm('dir');
fprintf(1, 'NIPYPE %s', spm_path);
"""
out = mlab.run()
if out.runtime.returncode == 0:
spm_path = sd._strip_header(out.runtime.stdout)
else:
logger.debug(out.runtime.stderr)
return None
return spm_path
示例9: test_MatlabCommand_inputs
def test_MatlabCommand_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
logfile=dict(argstr='-logfile %s',
),
mfile=dict(usedefault=True,
),
nodesktop=dict(argstr='-nodesktop',
nohash=True,
usedefault=True,
),
nosplash=dict(argstr='-nosplash',
nohash=True,
usedefault=True,
),
paths=dict(),
postscript=dict(usedefault=True,
),
prescript=dict(usedefault=True,
),
script=dict(argstr='-r "%s;exit"',
mandatory=True,
position=-1,
),
script_file=dict(usedefault=True,
),
single_comp_thread=dict(argstr='-singleCompThread',
nohash=True,
),
terminal_output=dict(mandatory=True,
nohash=True,
),
uses_mcr=dict(nohash=True,
xor=['nodesktop', 'nosplash', 'single_comp_thread'],
),
)
inputs = MatlabCommand.input_spec()
for key, metadata in input_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(inputs.traits()[key], metakey), value
示例10: import
from os.path import join as opj
from nipype.interfaces.afni import Despike
from nipype.interfaces.freesurfer import (BBRegister, ApplyVolTransform,
Binarize, MRIConvert, FSCommand)
from nipype.interfaces.spm import (SliceTiming, Realign, Smooth, Level1Design,
EstimateModel, EstimateContrast)
from nipype.interfaces.utility import Function, IdentityInterface
from nipype.interfaces.io import FreeSurferSource, SelectFiles, DataSink
from nipype.algorithms.rapidart import ArtifactDetect
from nipype.algorithms.misc import TSNR, Gunzip
from nipype.algorithms.modelgen import SpecifySPMModel
from nipype.pipeline.engine import Workflow, Node, MapNode
# MATLAB - Specify path to current SPM and the MATLAB's default mode
from nipype.interfaces.matlab import MatlabCommand
MatlabCommand.set_default_paths('/usr/local/MATLAB/R2014a/toolbox/spm12')
MatlabCommand.set_default_matlab_cmd("matlab -nodesktop -nosplash")
# FreeSurfer - Specify the location of the freesurfer folder
fs_dir = '~/nipype_tutorial/freesurfer'
FSCommand.set_default_subjects_dir(fs_dir)
###
# Specify variables
experiment_dir = '~/nipype_tutorial' # location of experiment folder
subject_list = ['sub001', 'sub002', 'sub003',
'sub004', 'sub005', 'sub006',
'sub007', 'sub008', 'sub009',
'sub010'] # list of subject identifiers
output_dir = 'output_fMRI_example_1st' # name of 1st-level output folder
示例11: SPMCommand
class SPMCommand(BaseInterface):
"""Extends `BaseInterface` class to implement SPM specific interfaces.
WARNING: Pseudo prototype class, meant to be subclassed
"""
input_spec = SPMCommandInputSpec
_jobtype = 'basetype'
_jobname = 'basename'
_matlab_cmd = None
_paths = None
_use_mcr = None
def __init__(self, **inputs):
super(SPMCommand, self).__init__(**inputs)
self.inputs.on_trait_change(self._matlab_cmd_update, ['matlab_cmd',
'mfile',
'paths',
'use_mcr'])
self._check_mlab_inputs()
self._matlab_cmd_update()
@classmethod
def set_mlab_paths(cls, matlab_cmd=None, paths = None, use_mcr=None):
cls._matlab_cmd = matlab_cmd
cls._paths = paths
cls._use_mcr = use_mcr
def _matlab_cmd_update(self):
# MatlabCommand has to be created here,
# because matlab_cmb is not a proper input
# and can be set only during init
self.mlab = MatlabCommand(matlab_cmd=self.inputs.matlab_cmd,
mfile=self.inputs.mfile,
paths=self.inputs.paths,
uses_mcr=self.inputs.use_mcr)
self.mlab.inputs.script_file = 'pyscript_%s.m' % \
self.__class__.__name__.split('.')[-1].lower()
@property
def jobtype(self):
return self._jobtype
@property
def jobname(self):
return self._jobname
def _check_mlab_inputs(self):
if not isdefined(self.inputs.matlab_cmd) and self._matlab_cmd:
self.inputs.matlab_cmd = self._matlab_cmd
if not isdefined(self.inputs.paths) and self._paths:
self.inputs.paths = self._paths
if not isdefined(self.inputs.use_mcr) and self._use_mcr:
self.inputs.use_mcr = self._use_mcr
def _run_interface(self, runtime):
"""Executes the SPM function using MATLAB."""
self.mlab.inputs.script = self._make_matlab_command(deepcopy(self._parse_inputs()))
results = self.mlab.run()
runtime.returncode = results.runtime.returncode
if self.mlab.inputs.uses_mcr:
if 'Skipped' in results.runtime.stdout:
self.raise_exception(runtime)
runtime.stdout = results.runtime.stdout
runtime.stderr = results.runtime.stderr
runtime.merged = results.runtime.merged
return runtime
def _list_outputs(self):
"""Determine the expected outputs based on inputs."""
raise NotImplementedError
def _format_arg(self, opt, spec, val):
"""Convert input to appropriate format for SPM."""
return val
def _parse_inputs(self, skip=()):
spmdict = {}
metadata=dict(field=lambda t : t is not None)
for name, spec in self.inputs.traits(**metadata).items():
if skip and name in skip:
continue
value = getattr(self.inputs, name)
if not isdefined(value):
continue
field = spec.field
if '.' in field:
fields = field.split('.')
dictref = spmdict
for f in fields[:-1]:
if f not in dictref.keys():
dictref[f] = {}
dictref = dictref[f]
dictref[fields[-1]] = self._format_arg(name, spec, value)
else:
spmdict[field] = self._format_arg(name, spec, value)
#.........这里部分代码省略.........
示例12: _run_interface
def _run_interface(self, runtime):
in_files = self.inputs.in_files
data_dir = op.join(os.getcwd(),'origdata')
if not op.exists(data_dir):
os.makedirs(data_dir)
all_names = []
print 'Multiple ({n}) input images detected! Copying to {d}...'.format(n=len(self.inputs.in_files), d=data_dir)
for in_file in self.inputs.in_files:
path, name, ext = split_filename(in_file)
shutil.copyfile(in_file, op.join(data_dir, name) + ext)
if ext == '.img':
shutil.copyfile(op.join(path, name) + '.hdr', op.join(data_dir, name) + '.hdr')
elif ext == '.hdr':
shutil.copyfile(op.join(path, name) + '.img', op.join(data_dir, name) + '.img')
all_names.append(name)
print 'Copied!'
input_files_as_str = op.join(data_dir, os.path.commonprefix(all_names) + '*' + ext)
number_of_components = self.inputs.desired_number_of_components
output_dir = os.getcwd()
prefix = self.inputs.prefix
d = dict(output_dir=output_dir, prefix=prefix, number_of_components=number_of_components, in_files=input_files_as_str)
variables = Template("""
%% After entering the parameters, use icatb_batch_file_run(inputFile);
modalityType = 'fMRI';
which_analysis = 1;
perfType = 1;
keyword_designMatrix = 'no';
dataSelectionMethod = 4;
input_data_file_patterns = {'$in_files'};
dummy_scans = 0;
outputDir = '$output_dir';
prefix = '$prefix';
maskFile = [];
group_pca_type = 'subject specific';
backReconType = 'gica';
%% Data Pre-processing options
% 1 - Remove mean per time point
% 2 - Remove mean per voxel
% 3 - Intensity normalization
% 4 - Variance normalization
preproc_type = 3;
pcaType = 1;
pca_opts.stack_data = 'yes';
pca_opts.precision = 'single';
pca_opts.tolerance = 1e-4;
pca_opts.max_iter = 1000;
numReductionSteps = 2;
doEstimation = 0;
estimation_opts.PC1 = 'mean';
estimation_opts.PC2 = 'mean';
estimation_opts.PC3 = 'mean';
numOfPC1 = $number_of_components;
numOfPC2 = $number_of_components;
numOfPC3 = 0;
%% Scale the Results. Options are 0, 1, 2, 3 and 4
% 0 - Don't scale
% 1 - Scale to Percent signal change
% 2 - Scale to Z scores
% 3 - Normalize spatial maps using the maximum intensity value and multiply timecourses using the maximum intensity value
% 4 - Scale timecourses using the maximum intensity value and spatial maps using the standard deviation of timecourses
scaleType = 0;
algoType = 1;
refFunNames = {'Sn(1) right*bf(1)', 'Sn(1) left*bf(1)'};
refFiles = {which('ref_default_mode.nii'), which('ref_left_visuomotor.nii'), which('ref_right_visuomotor.nii')};
%% ICA Options - Name by value pairs in a cell array. Options will vary depending on the algorithm. See icatb_icaOptions for more details. Some options are shown below.
%% Infomax - {'posact', 'off', 'sphering', 'on', 'bias', 'on', 'extended', 0}
%% FastICA - {'approach', 'symm', 'g', 'tanh', 'stabilization', 'on'}
icaOptions = {'posact', 'off', 'sphering', 'on', 'bias', 'on', 'extended', 0};
""").substitute(d)
file = open('input_batch.m', 'w')
file.writelines(variables)
file.close()
script = """param_file = icatb_read_batch_file('input_batch.m');
load(param_file);
global FUNCTIONAL_DATA_FILTER;
global ZIP_IMAGE_FILES;
FUNCTIONAL_DATA_FILTER = '*.nii';
ZIP_IMAGE_FILES = 'No';
icatb_runAnalysis(sesInfo, 1);"""
result = MatlabCommand(script=script, mfile=True, prescript=[''], postscript=[''])
r = result.run()
return runtime
示例13: _run_interface
def _run_interface(self, runtime):
data_dir = op.abspath('./denoise/components')
if not os.path.exists(data_dir):
os.makedirs(data_dir)
in_files = self.inputs.in_files
if len(self.inputs.in_files) > 1:
print 'Multiple ({n}) input images detected! Copying to {d}...'.format(n=len(self.inputs.in_files), d=data_dir)
for in_file in self.inputs.in_files:
path, name, ext = split_filename(in_file)
shutil.copyfile(in_file, op.join(data_dir, name) + ext)
if ext == '.img':
shutil.copyfile(op.join(path, name) + '.hdr',
op.join(data_dir, name) + '.hdr')
elif ext == '.hdr':
shutil.copyfile(op.join(path, name) + '.img',
op.join(data_dir, name) + '.img')
print 'Copied!'
in_files = self.inputs.in_files
elif isdefined(self.inputs.in_file4d):
print 'Single four-dimensional image selected. Splitting and copying to {d}'.format(d=data_dir)
in_files = nb.four_to_three(self.inputs.in_file4d)
for in_file in in_files:
path, name, ext = split_filename(in_file)
shutil.copyfile(in_file, op.join(data_dir, name) + ext)
print 'Copied!'
else:
print 'Single functional image provided. Ending...'
in_files = self.inputs.in_files
nComponents = len(in_files)
path, name, ext = split_filename(self.inputs.time_course_image)
shutil.copyfile(self.inputs.time_course_image,
op.join(data_dir, name) + ext)
if ext == '.img':
shutil.copyfile(op.join(path, name) + '.hdr',
op.join(data_dir, name) + '.hdr')
elif ext == '.hdr':
shutil.copyfile(op.join(path, name) + '.img',
op.join(data_dir, name) + '.img')
data_dir = op.abspath('./denoise')
path, name, ext = split_filename(self.inputs.ica_mask_image)
shutil.copyfile(self.inputs.ica_mask_image,
op.join(data_dir, name) + ext)
if ext == '.img':
shutil.copyfile(op.join(path, name) + '.hdr',
op.join(data_dir, name) + '.hdr')
elif ext == '.hdr':
shutil.copyfile(op.join(path, name) + '.img',
op.join(data_dir, name) + '.img')
mask_file = op.join(data_dir, name)
repetition_time = self.inputs.repetition_time
neuronal_image = op.abspath(self.inputs.out_neuronal_image)
non_neuronal_image = op.abspath(self.inputs.out_non_neuronal_image)
coma_rest_lib_path = op.abspath(self.inputs.coma_rest_lib_path)
d = dict(
data_dir=data_dir, mask_name=mask_file, nComponents=nComponents, Tr=repetition_time,
nameNeuronal=neuronal_image, nameNonNeuronal=non_neuronal_image, coma_rest_lib_path=coma_rest_lib_path)
script = Template("""
restlib_path = '$coma_rest_lib_path';
setup_restlib_paths(restlib_path)
dataDir = '$data_dir';
maskName = '$mask_name';
nCompo = $nComponents;
Tr = $Tr;
nameNeuronalData = '$nameNeuronal';
nameNonNeuronalData = '$nameNonNeuronal';
denoiseImage(dataDir,maskName,nCompo,Tr,nameNeuronalData,nameNonNeuronalData, restlib_path);
""").substitute(d)
result = MatlabCommand(script=script, mfile=True,
prescript=[''], postscript=[''])
r = result.run()
print 'Neuronal component image saved as {n}'.format(n=neuronal_image)
print 'Non-neuronal component image saved as {n}'.format(n=non_neuronal_image)
return runtime
示例14: display_crash_files
import os
import socket
from nipype.interfaces.matlab import MatlabCommand
if socket.gethostname() == 'malin':
os.environ['MATLABCMD'] = "/opt/matlab/R2015b/bin/matlab -nodesktop -nosplash"
MatlabCommand.set_default_paths('/opt/matlab/R2015b/toolbox/spm12')
MatlabCommand.set_default_matlab_cmd("/opt/matlab/R2015b/bin/matlab -nodesktop -nosplash")
TPM = '/opt/matlab/R2015b/toolbox/spm12/tpm/TPM.nii'
# os.environ['MATLABCMD'] = "/opt/matlab/R2012a/bin/matlab -nodesktop -nosplash"
# MatlabCommand.set_default_paths('/opt/matlab/R2012a/toolbox/spm12')
# MatlabCommand.set_default_matlab_cmd("/opt/matlab/R2012a/bin/matlab -nodesktop -nosplash")
elif socket.gethostname() == 'cala':
os.environ['MATLABCMD'] = "/opt/matlab/64bit/R2015a/bin/matlab -nodesktop -nosplash"
MatlabCommand.set_default_paths('/opt/matlab/64bit/R2015a/toolbox/spm12')
MatlabCommand.set_default_matlab_cmd("/opt/matlab/64bit/R2015a/bin/matlab -nodesktop -nosplash")
TPM = '/opt/matlab/64bit/R2015a/toolbox/spm12/tpm/TPM.nii'
def display_crash_files(crashfile, rerun=False):
from nipype.utils.filemanip import loadcrash
crash_data = loadcrash(crashfile)
node = crash_data['node']
tb = crash_data['traceback']
print("\n")
print("File: %s"%crashfile)
print("Node: %s"%node)
if node.base_dir:
print("Working directory: %s" % node.output_dir())
else:
print("Node crashed before execution")
print("\n")
示例15:
from nipype.interfaces.fsl.epi import ApplyTOPUP, TOPUP
from nipype.interfaces.freesurfer import Resample, Binarize, MRIConvert
from nipype.algorithms.confounds import CompCor
from nipype.interfaces.afni.preprocess import Bandpass
from nipype.interfaces.afni.utils import AFNItoNIFTI
from nipype.interfaces.ants import ApplyTransforms, Registration
from nipype.algorithms.misc import Gunzip
from pandas import DataFrame, Series
#set output file type for FSL to NIFTI
from nipype.interfaces.fsl.preprocess import FSLCommand
FSLCommand.set_default_output_type('NIFTI')
# MATLAB setup - Specify path to current SPM and the MATLAB's default mode
from nipype.interfaces.matlab import MatlabCommand
MatlabCommand.set_default_paths('~/spm12')
MatlabCommand.set_default_matlab_cmd("matlab -nodesktop -nosplash")
# Set study variables
setup='sherlock'
sample='6mo' #6mo or newborn
sequence='spiral'#spiral or mux6
if setup=='sherlock':
studyhome = '/oak/stanford/groups/iang/BABIES_data/BABIES_rest'
raw_data = studyhome + '/subjDir/all'
output_dir = studyhome + '/processed/preproc'
workflow_dir = studyhome + '/workflows'
elif setup=='Cat':
studyhome = '/Users/catcamacho/Box/SNAP/BABIES/BABIES_rest'
raw_data = studyhome + '/rest_raw'