• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python matlab.MatlabCommand类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中nipype.interfaces.matlab.MatlabCommand的典型用法代码示例。如果您正苦于以下问题:Python MatlabCommand类的具体用法?Python MatlabCommand怎么用?Python MatlabCommand使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了MatlabCommand类的16个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:FCP-INDI,项目名称:BrainImagingPipelines,代码行数:35,代码来源:matlab_utils.py


示例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
开发者ID:jelman,项目名称:voxelwise_pib,代码行数:27,代码来源:worldmat2flirtmap_pywrapper.py


示例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
开发者ID:tseytlin,项目名称:gold-pype,代码行数:27,代码来源:wrappers.py


示例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
开发者ID:RanjitK,项目名称:NKI_NYU_Nipype,代码行数:9,代码来源:e_afni.py


示例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
开发者ID:joebathelt,项目名称:Neuroimaging_PythonTools,代码行数:12,代码来源:own_nipype.py


示例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()
开发者ID:satra,项目名称:NiPypeold,代码行数:9,代码来源:base.py


示例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
开发者ID:chaselgrove,项目名称:nipype,代码行数:41,代码来源:base.py


示例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
开发者ID:satra,项目名称:NiPypeold,代码行数:39,代码来源:base.py


示例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
开发者ID:Alunisiira,项目名称:nipype,代码行数:47,代码来源:test_auto_MatlabCommand.py


示例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
开发者ID:miykael,项目名称:nipype-beginner-s-guide,代码行数:31,代码来源:example_fMRI_1_first_level.py


示例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)
#.........这里部分代码省略.........
开发者ID:chaselgrove,项目名称:nipype,代码行数:101,代码来源:base.py


示例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
开发者ID:GIGA-Consciousness,项目名称:structurefunction,代码行数:91,代码来源:gift.py


示例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
开发者ID:GIGA-Consciousness,项目名称:structurefunction,代码行数:79,代码来源:base.py


示例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")
开发者ID:m-guggenmos,项目名称:mgnipype,代码行数:31,代码来源:nipypes.py


示例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'
开发者ID:catcamacho,项目名称:infant_rest,代码行数:31,代码来源:preprocessing_classic.py


示例16: _run_interface

    def _run_interface(self, runtime):
        list_path = op.abspath("SubjectList.lst")
        pet_path, _ = nifti_to_analyze(self.inputs.pet_file)
        t1_path, _ = nifti_to_analyze(self.inputs.t1_file)
        f = open(list_path, 'w')
        f.write("%s;%s" % (pet_path, t1_path))
        f.close()

        orig_t1 = nb.load(self.inputs.t1_file)
        orig_affine = orig_t1.get_affine()

        gm_uint8 = switch_datatype(self.inputs.grey_matter_file)
        gm_path, _ = nifti_to_analyze(gm_uint8)
        iflogger.info("Writing to %s" % gm_path)

        fixed_roi_file, fixed_wm, fixed_csf, remap_dict = fix_roi_values(
            self.inputs.roi_file, self.inputs.grey_matter_binary_mask, 
            self.inputs.white_matter_file,
            self.inputs.csf_file, self.inputs.use_fs_LUT)


        

        rois_path, _ = nifti_to_analyze(fixed_roi_file)
        iflogger.info("Writing to %s" % rois_path)
        iflogger.info("Writing to %s" % fixed_wm)
        iflogger.info("Writing to %s" % fixed_csf)

        wm_uint8 = switch_datatype(fixed_wm)
        wm_path, _ = nifti_to_analyze(wm_uint8)
        iflogger.info("Writing to %s" % wm_path)

        csf_uint8 = switch_datatype(fixed_csf)
        csf_path, _ = nifti_to_analyze(csf_uint8)
        iflogger.info("Writing to %s" % csf_path)

        if self.inputs.use_fs_LUT:
            fs_dir = os.environ['FREESURFER_HOME']
            LUT = op.join(fs_dir, "FreeSurferColorLUT.txt")
            dat_path = write_config_dat(
                fixed_roi_file, LUT, remap_dict)
        else:
            dat_path = write_config_dat(
                fixed_roi_file)
        iflogger.info("Writing to %s" % dat_path)

        d = dict(
            list_path=list_path,
            gm_path=gm_path,
            wm_path=wm_path,
            csf_path=csf_path,
            rois_path=rois_path,
            dat_path=dat_path,
            X_PSF=self.inputs.x_dir_point_spread_function_FWHM,
            Y_PSF=self.inputs.y_dir_point_spread_function_FWHM,
            Z_PSF=self.inputs.z_dir_point_spread_function_FWHM)
        script = Template("""       
        filelist = '$list_path';
        gm = '$gm_path';
        wm = '$wm_path';
        csf = '$csf_path';
        rois = '$rois_path';
        dat = '$dat_path';
        x_fwhm = '$X_PSF';
        y_fwhm = '$Y_PSF';
        z_fwhm = '$Z_PSF';
        runbatch_nogui(filelist, gm, wm, csf, rois, dat, x_fwhm, y_fwhm, z_fwhm)
        """).substitute(d)
        mlab = MatlabCommand(script=script, mfile=True,
                             prescript=[''], postscript=[''])
        result = mlab.run()

        _, foldername, _ = split_filename(self.inputs.pet_file)
        occu_MG_img = glob.glob("pve_%s/r_volume_Occu_MG.img" % foldername)[0]
        analyze_to_nifti(occu_MG_img, affine=orig_affine)
        occu_meltzer_img = glob.glob(
            "pve_%s/r_volume_Occu_Meltzer.img" % foldername)[0]
        analyze_to_nifti(occu_meltzer_img, affine=orig_affine)
        meltzer_img = glob.glob("pve_%s/r_volume_Meltzer.img" % foldername)[0]
        analyze_to_nifti(meltzer_img, affine=orig_affine)
        MG_rousset_img = glob.glob(
            "pve_%s/r_volume_MGRousset.img" % foldername)[0]
        analyze_to_nifti(MG_rousset_img, affine=orig_affine)
        MGCS_img = glob.glob("pve_%s/r_volume_MGCS.img" % foldername)[0]
        analyze_to_nifti(MGCS_img, affine=orig_affine)
        virtual_PET_img = glob.glob(
            "pve_%s/r_volume_Virtual_PET.img" % foldername)[0]
        analyze_to_nifti(virtual_PET_img, affine=orig_affine)
        centrum_semiovalue_WM_img = glob.glob(
            "pve_%s/r_volume_CSWMROI.img" % foldername)[0]
        analyze_to_nifti(centrum_semiovalue_WM_img, affine=orig_affine)
        alfano_alfano_img = glob.glob(
            "pve_%s/r_volume_AlfanoAlfano.img" % foldername)[0]
        analyze_to_nifti(alfano_alfano_img, affine=orig_affine)
        alfano_cs_img = glob.glob("pve_%s/r_volume_AlfanoCS.img" %
                                  foldername)[0]
        analyze_to_nifti(alfano_cs_img, affine=orig_affine)
        alfano_rousset_img = glob.glob(
            "pve_%s/r_volume_AlfanoRousset.img" % foldername)[0]
        analyze_to_nifti(alfano_rousset_img, affine=orig_affine)
#.........这里部分代码省略.........
开发者ID:GIGA-Consciousness,项目名称:structurefunction,代码行数:101,代码来源:pve.py



注:本文中的nipype.interfaces.matlab.MatlabCommand类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python base.scans_for_fnames函数代码示例发布时间:2022-05-27
下一篇:
Python fsl.Info类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap