def run_m_script(m_file): """ Runs a matlab m file for SPM, determining automatically if it must be launched with SPM or SPM Standalone If launch with spm standalone, the line 'spm_jobman('run', matlabbatch)' must be removed because unnecessary Args: m_file: (str) path to Matlab m file Returns: output_mat_file: (str) path to the SPM.mat file needed in SPM analysis """ import platform from os import system from os.path import abspath, basename, dirname, isfile, join from nipype.interfaces.matlab import MatlabCommand, get_matlab_command import clinica.pipelines.statistics_volume.statistics_volume_utils as utls from clinica.utils.spm import spm_standalone_is_available assert isinstance(m_file, str), "[Error] Argument must be a string" if not isfile(m_file): raise FileNotFoundError("[Error] File " + m_file + "does not exist") assert m_file[-2:] == ".m", ( "[Error] " + m_file + " is not a Matlab file (extension must be .m)") # Generate command line to run if spm_standalone_is_available(): utls.delete_last_line(m_file) # SPM standalone must be run directly from its root folder if platform.system().lower().startswith("darwin"): # Mac OS cmdline = ( "cd $SPMSTANDALONE_HOME && ./run_spm12.sh $MCR_HOME batch " + m_file) elif platform.system().lower().startswith("linux"): # Linux OS cmdline = "$SPMSTANDALONE_HOME/run_spm12.sh $MCR_HOME batch " + m_file else: raise SystemError("Clinica only support Mac OS and Linux") system(cmdline) else: MatlabCommand.set_default_matlab_cmd(get_matlab_command()) matlab = MatlabCommand() if platform.system().lower().startswith("linux"): matlab.inputs.args = "-nosoftwareopengl" matlab.inputs.paths = dirname(m_file) matlab.inputs.script = basename(m_file)[:-2] matlab.inputs.single_comp_thread = False matlab.inputs.logfile = abspath("./matlab_output.log") matlab.run() output_mat_file = abspath( join(dirname(m_file), "..", "2_sample_t_test", "SPM.mat")) if not isfile(output_mat_file): raise RuntimeError("Output matrix " + output_mat_file + " was not produced") return output_mat_file
def run_matlab(caps_dir, output_dir, subjects_visits_tsv, pipeline_parameters): """ Wrap the call of SurfStat using clinicasurfstat.m Matlab script. Args: caps_dir (str): CAPS directory containing surface-based features output_dir (str): Output directory that will contain outputs of clinicasurfstat.m subjects_visits_tsv (str): TSV file containing the GLM information pipeline_parameters (dict): parameters of StatisticsSurface pipeline """ import os from nipype.interfaces.matlab import MatlabCommand, get_matlab_command import clinica.pipelines as clinica_pipelines from clinica.utils.check_dependency import check_environment_variable from clinica.pipelines.statistics_surface.statistics_surface_utils import covariates_to_design_matrix, get_string_format_from_tsv path_to_matlab_script = os.path.join( os.path.dirname(clinica_pipelines.__path__[0]), 'lib', 'clinicasurfstat') freesurfer_home = check_environment_variable('FREESURFER_HOME', 'FreeSurfer') MatlabCommand.set_default_matlab_cmd(get_matlab_command()) matlab = MatlabCommand() matlab.inputs.paths = path_to_matlab_script matlab.inputs.script = """ clinicasurfstat('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, '%s', %.3f, '%s', %.3f, '%s', %.3f); """ % (os.path.join(caps_dir, 'subjects'), output_dir, subjects_visits_tsv, covariates_to_design_matrix(pipeline_parameters['contrast'], pipeline_parameters['covariates']), pipeline_parameters['contrast'], get_string_format_from_tsv(subjects_visits_tsv), pipeline_parameters['glm_type'], pipeline_parameters['group_label'], freesurfer_home, pipeline_parameters['custom_file'], pipeline_parameters['measure_label'], 'sizeoffwhm', pipeline_parameters['full_width_at_half_maximum'], 'thresholduncorrectedpvalue', 0.001, 'thresholdcorrectedpvalue', 0.05, 'clusterthreshold', pipeline_parameters['cluster_threshold']) # This will create a file: pyscript.m , the pyscript.m is the default name matlab.inputs.mfile = True # This will stop running with single thread matlab.inputs.single_comp_thread = False matlab.inputs.logfile = 'group-' + pipeline_parameters[ 'group_label'] + '_matlab.log' # cprint("Matlab logfile is located at the following path: %s" % matlab.inputs.logfile) # cprint("Matlab script command = %s" % matlab.inputs.script) # cprint("MatlabCommand inputs flag: single_comp_thread = %s" % matlab.inputs.single_comp_thread) # cprint("MatlabCommand choose which matlab to use(matlab_cmd): %s" % get_matlab_command()) matlab.run() return output_dir
def run_m_script(m_file): """ Runs a matlab m file for SPM, determining automatically if it must be launched with SPM or SPM Standalone If launch with spm standalone, the line 'spm_jobman('run', matlabbatch)' must be removed because unnecessary Args: m_file: (str) path to Matlab m file Returns: output_mat_file: (str) path to the SPM.mat file needed in SPM analysis """ from os.path import isfile, dirname, basename, abspath, join from os import system from clinica.utils.spm import use_spm_standalone import clinica.pipelines.statistics_volume.statistics_volume_utils as utls from nipype.interfaces.matlab import MatlabCommand, get_matlab_command import platform assert isinstance(m_file, str), '[Error] Argument must be a string' if not isfile(m_file): raise FileNotFoundError('[Error] File ' + m_file + 'does not exist') assert m_file[-2:] == '.m', '[Error] ' + m_file + ' is not a Matlab file (extension must be .m)' # Generate command line to run if use_spm_standalone(): utls.delete_last_line(m_file) # SPM standalone must be run directly from its root folder if platform.system().lower().startswith('darwin'): # Mac OS cmdline = 'cd $SPMSTANDALONE_HOME && ./run_spm12.sh $MCR_HOME batch ' + m_file elif platform.system().lower().startswith('linux'): # Linux OS cmdline = '$SPMSTANDALONE_HOME/run_spm12.sh $MCR_HOME batch ' + m_file else: raise SystemError('Clinica only support Mac OS and Linux') system(cmdline) else: MatlabCommand.set_default_matlab_cmd(get_matlab_command()) matlab = MatlabCommand() if platform.system().lower().startswith('linux'): matlab.inputs.args = '-nosoftwareopengl' matlab.inputs.paths = dirname(m_file) matlab.inputs.script = basename(m_file)[:-2] matlab.inputs.single_comp_thread = False matlab.inputs.logfile = abspath('./matlab_output.log') matlab.run() output_mat_file = abspath(join(dirname(m_file), '..', '2_sample_t_test', 'SPM.mat')) if not isfile(output_mat_file): raise RuntimeError('Output matrix ' + output_mat_file + ' was not produced') return output_mat_file
import matplotlib.pyplot as plt import numpy as np from nipype.pipeline.engine import Workflow, Node, MapNode from nipype.interfaces.io import SelectFiles, DataSink from os.path import join as opj from nipype.interfaces.utility import IdentityInterface, Function, Select, Merge import nipype.interfaces.spm as spm import nipype.interfaces.ants as ants import nipype.interfaces.afni as afni import nipype.interfaces.fsl as fsl from nipype import config cfg = dict(execution={'remove_unnecessary_outputs': False}) config.update_config(cfg) MatlabCommand.set_default_paths('/Users/amr/Downloads/spm12') MatlabCommand.set_default_matlab_cmd("matlab -nodesktop -nosplash") # import nipype.interfaces.matlab as mlab # mlab.MatlabCommand.set_default_matlab_cmd("matlab -nodesktop -nosplash") # mlab.MatlabCommand.set_default_paths('/home/amr/Documents/MATLAB/toolbox/spm8') # ======================================================================================================== # In[2]: experiment_dir = '/media/amr/Amr_4TB/Work/stimulation' subject_list = [ '005', '007', '008', '010', '013', '024', '025', '026', '027', '028', '038', '040', '041', '042', '051', '052', '053', '054', '055', '059', '060', '061', '079', '081' ]
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' output_dir = studyhome + '/processed/preproc'
# ====================================================================== # define paths depending on the operating system (OS) platform: project = 'highspeed' # initialize empty paths: path_root = None sub_list = None # path to the project root: project_name = 'highspeed-glm' path_root = os.getenv('PWD').split(project_name)[0] + project_name if 'darwin' in sys.platform: path_spm = '/Users/Shared/spm12' path_matlab = '/Applications/MATLAB_R2017a.app/bin/matlab -nodesktop -nosplash' # set paths for spm: spm.SPMCommand.set_mlab_paths(paths=path_spm, matlab_cmd=path_matlab) MatlabCommand.set_default_paths(path_spm) MatlabCommand.set_default_matlab_cmd(path_matlab) sub_list = ['sub-01'] elif 'linux' in sys.platform: # path_matlab = '/home/mpib/wittkuhn/spm12.simg eval \$SPMMCRCMD' # path_matlab = opj('/home', 'beegfs', 'wittkuhn', 'tools', 'spm', 'spm12.simg eval \$SPMMCRCMD') singularity_cmd = 'singularity run -B /home/mpib/wittkuhn -B /mnt/beegfs/home/wittkuhn /home/mpib/wittkuhn/highspeed/highspeed-glm/tools/spm/spm12.simg' singularity_spm = 'eval \$SPMMCRCMD' path_matlab = ' '.join([singularity_cmd, singularity_spm]) spm.SPMCommand.set_mlab_paths(matlab_cmd=path_matlab, use_mcr=True) # grab the list of subjects from the bids data set: layout = BIDSLayout(opj(path_root, 'bids')) # get all subject ids: sub_list = sorted(layout.get_subjects()) # create a template to add the "sub-" prefix to the ids sub_template = ['sub-'] * len(sub_list) # add the prefix to all ids:
def runmatlab(output_dir, noddi_img, brain_mask, roi_mask, bval, bvec, prefix, bStep, num_cores, path_to_matscript, noddi_toolbox_dir, nifti_matlib_dir): """ The wrapper to call noddi matlab script. Args: output_dir: noddi_img: brain_mask: roi_mask: bval: bvec: prefix: bStep: num_cores: Returns: """ from nipype.interfaces.matlab import MatlabCommand, get_matlab_command from os.path import join import sys import os # here, we check out the os, basically, clinica works for linux and MAC OS X. if sys.platform.startswith('linux'): print "###Note: your platform is linux, the default command line for Matlab(matlab_cmd) is matlab, but you can also export a variable MATLABCMD, which points to your matlab, in your .bashrc to set matlab_cmd, this can help you to choose which Matlab to run when you have more than one Matlab. " elif sys.platform.startswith('darwin'): try: if 'MATLABCMD' not in os.environ: raise RuntimeError( "###Note: your platform is MAC OS X, the default command line for Matlab(matlab_cmd) is matlab, but it does not work on OS X, you mush export a variable MATLABCMD, which points to your matlab, in your .bashrc to set matlab_cmd. Note, Mac os x will always choose to use OpengGl hardware mode." ) except Exception as e: print(str(e)) exit(1) else: print "Clinica will not work on your platform " MatlabCommand.set_default_matlab_cmd( get_matlab_command() ) # this is to set the matlab_path(os.environ) in your bashrc file, to choose which version of matlab do you wanna use # here, set_default_matlab_cmd is a @classmethod matlab = MatlabCommand() # add the dynamic traits # openGL_trait = traits.Bool(True, argstr='-nosoftwareopengl', usedefault=True, desc='Switch on hardware openGL', nohash=True) # matlab.input_spec.add_trait(matlab.input_spec(), 'nosoftwareopengl', openGL_trait() ) if sys.platform.startswith('linux'): matlab.inputs.args = '-nosoftwareopengl' # Bug, for my laptop, it does not work, but the command line does have the flag -nosoftwareopengl, we should try on other computer's matlab to check if this flag works! matlab.inputs.paths = path_to_matscript # CLINICA_HOME, this is the path to add into matlab, addpath matlab.inputs.script = """ noddiprocessing('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d'); """ % ( output_dir, noddi_img, brain_mask, roi_mask, bval, bvec, prefix, bStep, noddi_toolbox_dir, nifti_matlib_dir, num_cores ) # here, we should define the inputs for the matlab function that you want to use matlab.inputs.mfile = True # this will create a file: pyscript.m , the pyscript.m is the default name matlab.inputs.single_comp_thread = False # this will stop runing with single thread matlab.inputs.logfile = join(output_dir, prefix + "_matlab_output.log") print "Matlab logfile is located in the folder: %s" % matlab.inputs.logfile print "Matlab script command = %s" % matlab.inputs.script print "MatlabCommand inputs flag: single_comp_thread = %s" % matlab.inputs.single_comp_thread print "MatlabCommand choose which matlab to use(matlab_cmd): %s" % get_matlab_command( ) if sys.platform.startswith('linux'): print "MatlabCommand inputs flag: nosoftwareopengl = %s" % matlab.inputs.args matlab.run() # grab the output images fit_icvf = os.path.join(output_dir, prefix + '_ficvf.nii') fit_isovf = os.path.join(output_dir, prefix + '_fiso.nii') fit_od = os.path.join(output_dir, prefix + '_odi.nii') return fit_icvf, fit_isovf, fit_od
def runmatlab(input_directory, output_directory, subjects_visits_tsv, design_matrix, contrast, str_format, glm_type, group_label, freesurfer_home, surface_file, path_to_matscript, full_width_at_half_maximum, threshold_uncorrected_pvalue, threshold_corrected_pvalue, cluster_threshold, feature_label): """ a wrapper the matlab script of surfstat with nipype. Args: input_directory: surfstat_input_dir where containing all the subjects' output in CAPS directory output_directory: output folder to contain the result in CAPS folder subjects_visits_tsv: tsv file containing the glm information design_matrix: str, the linear model that fits into the GLM, for example '1+group'. contrast: string, the contrast matrix for GLM, if the factor you choose is categorized variable, clinica_surfstat will create two contrasts, for example, contrast = 'Label', this will create contrastpos = Label.AD - Label.CN, contrastneg = Label.CN - Label.AD; if the fac- tory that you choose is a continuous factor, clinica_surfstat will just create one contrast, for example, contrast = 'Age', but note, the string name that you choose should be exactly the same with the columns names in your subjects_visits_tsv. str_format:string, the str_format which uses to read your tsv file, the type of the string should corresponds exactly with the columns in the tsv file. Defaut parameters, we set these parameters to be some default values, but you can also set it by yourself: glm_type: based on the hypothesis, you should define one of the glm types, "group_comparison", "correlation" group_label: current group name for this analysis freesurfer_home: the environmental variable $FREESURFER_HOME surface_file: Specify where to find the data surfaces file in the "CAPS/subject" directory, using specific keywords. For instance, to catch for each subject the cortical thickness, the string used will be: '@subject/@session/t1/freesurfer_cross_sectional/@subject_@session/surf/@[email protected]' More information is available on the documentation page of the surfstat pipelines. The keywords @subject @ session @hemi @fwhm represents the variable parts. path_to_matscript: path to find the matlab script full_width_at_half_maximum: fwhm for the surface smoothing, default is 20, integer. threshold_uncorrected_pvalue: threshold to display the uncorrected Pvalue, float, default is 0.001. threshold_corrected_pvalue: the threshold to display the corrected cluster, default is 0.05, float. cluster_threshold: threshold to define a cluster in the process of cluster-wise correction, default is 0.001, float. Returns: """ from nipype.interfaces.matlab import MatlabCommand, get_matlab_command from os.path import join import sys from clinica.utils.stream import cprint MatlabCommand.set_default_matlab_cmd( get_matlab_command()) # this is to set the matlab_path(os.environ) in your bashrc file, to choose which version of matlab do you wanna use # here, set_default_matlab_cmd is a @classmethod matlab = MatlabCommand() # add the dynamic traits # openGL_trait = traits.Bool(True, argstr='-nosoftwareopengl', usedefault=True, desc='Switch on hardware openGL', nohash=True) # matlab.input_spec.add_trait(matlab.input_spec(), 'nosoftwareopengl', openGL_trait() ) if sys.platform.startswith('linux'): matlab.inputs.args = '-nosoftwareopengl' # Bug, for my laptop, it does not work, but the command line does have the flag -nosoftwareopengl, we should try on other computer's matlab to check if this flag works! matlab.inputs.paths = path_to_matscript # CLINICA_HOME, this is the path to add into matlab, addpath matlab.inputs.script = """ clinicasurfstat('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, '%s', %.3f, '%s', %.3f, '%s', %.3f); """ % (input_directory, output_directory, subjects_visits_tsv, design_matrix, contrast, str_format, glm_type, group_label, freesurfer_home, surface_file, feature_label, 'sizeoffwhm', full_width_at_half_maximum, 'thresholduncorrectedpvalue', threshold_uncorrected_pvalue, 'thresholdcorrectedpvalue', threshold_corrected_pvalue, 'clusterthreshold', cluster_threshold) # here, we should define the inputs for the matlab function that you want to use matlab.inputs.mfile = True # this will create a file: pyscript.m , the pyscript.m is the default name matlab.inputs.single_comp_thread = False # this will stop runing with single thread matlab.inputs.logfile = join(output_directory, "matlab_output.log") cprint("Matlab logfile is located in the folder: %s" % matlab.inputs.logfile) cprint("Matlab script command = %s" % matlab.inputs.script) cprint("MatlabCommand inputs flag: single_comp_thread = %s" % matlab.inputs.single_comp_thread) cprint("MatlabCommand choose which matlab to use(matlab_cmd): %s" % get_matlab_command()) if sys.platform.startswith('linux'): cprint("MatlabCommand inputs flag: nosoftwareopengl = %s" % matlab.inputs.args) out = matlab.run() return out
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 #change ##Edit as necessary # preprocess(studyfile, startSubject, endSubject): #Have to check this path MatlabCommand.set_default_paths( '/Users/lighthalllab/Documents/MATLAB/toolbox/spm12') MatlabCommand.set_default_matlab_cmd( "/Applications/MATLAB_R2015a.app/bin/matlab -nodesktop -nosplash") """ # FreeSurfer - Specify the location of the freesurfer folder fs_dir = '/Volumes/Research2/Lighthall_Lab/experiments/cjfmri-1/data/fmri/Lucy_testing/Copy/Func/freesurfer' FSCommand.set_default_subjects_dir(fs_dir)""" ### # Specify variables experiment_dir = '/Volumes/Research2/Lighthall_Lab/experiments/cjfmri-1/data/fmri/Lucy_testing/Copy/Func' # location of experiment folder output_dir = 'output_fMRI_example_1st' # name of 1st-level output folder working_dir = 'workingdir_fMRI_example_4rd' # name of 1st-level working directory subject_list = ["1002", "1003"] # list of subject identifiers session_list = ['Enc1', 'Jud2'] # list of session identifiers number_of_slices = 38 # number of slices in volume
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")
#!/usr/bin/env python import nipype.interfaces.spm as spm import nipype.pipeline.engine as pe from nipype.interfaces.matlab import MatlabCommand matlab_cmd = '/usr/local/MATLAB/R2019a/bin/matlab' default_mask = '/media/grg/home/grg/SPM/MNI_T1_brain_wo_csf.nii' spm.SPMCommand.set_mlab_paths(matlab_cmd=matlab_cmd) MatlabCommand.set_default_matlab_cmd('matlab -nodesktop -noplash') def make_contrasts(names): contrasts = [] cont1 = ('Effect of age (+)', 'T', ['age'], [1]) cont2 = ('Effect of age (-)', 'T', ['age'], [-1]) contrasts.append(cont1) contrasts.append(cont2) return contrasts # cont1 = ('Apo2-3>Apo2-4', 'T', ['Apoe2-3', 'Apoe2-4'], [1, -1]) # cont2 = ('Apo2-4>Apo3-3', 'T', ['Apoe2-4', 'Apoe3-3'], [1, -1]) # cont3 = ('Apo3-3>Apo3-4', 'T', ['Apoe3-3', 'Apoe3-4'], [1, -1]) # cont4 = ('Apo3-4>Apo4-4', 'T', ['Apoe3-4', 'Apoe4-4'], [1, -1]) # cont4 = ('Apo4-4>Apo3-3', 'T', ['Apoe4-4', 'Apoe3-3'], [1, -1]) # cont5 = ('Main effect ApoE', 'F', [cont1, cont2, cont3, cont4]) # cont6 = ('C<NC', 'T', ['Apoe2-3', 'Apoe2-4', 'Apoe3-3', 'Apoe3-4', 'Apoe4-4'], [3, -2, 3, -2, -2]) # cont7 = ('C>NC', 'T', ['Apoe2-3', 'Apoe2-4', 'Apoe3-3', 'Apoe3-4', 'Apoe4-4'], [-3, 2, -3, 2, 2])