Esempio n. 1
0
def set_spm():

    spm.SPMCommand.set_mlab_paths(matlab_cmd='matlab -nodesktop -nosplash')

    if get_matlab_command() is None:
        print("could not find matlab, will try with mcr_spm version")

        try:
            spm_dir = os.environ["SPM_DIR"]
            spm_ver = os.environ["SPM_VERSION"]
            mcr_version = os.environ["MCR_VERSION"]
        except KeyError:
            print("Error, could not find SPM or MCR environement")
            return False

        print("OK, SPM {} MCR version {} was found".format(
            spm_ver, mcr_version))

        spm_cmd = '{}/run_spm{}.sh /opt/mcr/{} script'.format(
            spm_dir, spm_ver, mcr_version)
        spm.SPMCommand.set_mlab_paths(matlab_cmd=spm_cmd, use_mcr=True)
        return True

    else:
        print("OK, matlab was found")
        return True
Esempio n. 2
0
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
Esempio n. 3
0
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
Esempio n. 4
0
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
Esempio n. 5
0
def set_spm():

    spm.SPMCommand.set_mlab_paths(matlab_cmd='matlab -nodesktop -nosplash')

    if get_matlab_command() is None:
        print("could not find matlab, will try with mcr_spm version")

        try:
            print(os.environ)
            print(os.environ["SPM_DIR"])
            print(os.environ["SPM_VERSION"])
            print(os.environ["MCR_VERSION"])

            spm_dir = os.environ["SPM_DIR"]
            spm_ver = os.environ["SPM_VERSION"]
            mcr_version = os.environ["MCR_VERSION"]

            print("OK, SPM {} MCR version {} was found".format(
                spm_ver, mcr_version))

            spm_cmd = '{}/run_spm{}.sh /opt/mcr/{} script'.format(
                spm_dir, spm_ver, mcr_version)
            print(spm_cmd)

            spm.SPMCommand.set_mlab_paths(matlab_cmd=spm_cmd, use_mcr=True)
            return True

        except KeyError:
            print("Error, could not find SPM or MCR environement")

        print("Going for octave; still testing")

        assert os.path.exists('/opt/spm12')

        spm.SPMCommand.set_mlab_paths(
            matlab_cmd='octave --no-window-system --no-gui --braindead',
            use_mcr=True)

        return True

    else:
        print("OK, matlab was found")
        return True
Esempio n. 6
0
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
from tempfile import mkdtemp
from shutil import rmtree

import pytest
import nipype.interfaces.matlab as mlab

matlab_cmd = mlab.get_matlab_command()
no_matlab = matlab_cmd is None
if not no_matlab:
    mlab.MatlabCommand.set_default_matlab_cmd(matlab_cmd)


def clean_workspace_and_get_default_script_file():
    # Make sure things are clean.
    default_script_file = mlab.MatlabInputSpec().script_file
    if os.path.exists(default_script_file):
        os.remove(default_script_file)  # raise Exception('Default script file needed for tests; please remove %s!' % default_script_file)
    return default_script_file


@pytest.mark.skipif(no_matlab, reason="matlab is not available")
def test_cmdline():
    default_script_file = clean_workspace_and_get_default_script_file()

    mi = mlab.MatlabCommand(script='whos',
                            script_file='testscript', mfile=False)
Esempio n. 7
0
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
Esempio n. 8
0
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
Esempio n. 9
0
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os

import pytest
import nipype.interfaces.matlab as mlab

matlab_cmd = mlab.get_matlab_command()
no_matlab = matlab_cmd is None
if not no_matlab:
    mlab.MatlabCommand.set_default_matlab_cmd(matlab_cmd)


def clean_workspace_and_get_default_script_file():
    # Make sure things are clean.
    default_script_file = mlab.MatlabInputSpec().script_file
    if os.path.exists(default_script_file):
        os.remove(
            default_script_file
        )  # raise Exception('Default script file needed for tests; please remove %s!' % default_script_file)
    return default_script_file


@pytest.mark.skipif(no_matlab, reason="matlab is not available")
def test_cmdline():
    default_script_file = clean_workspace_and_get_default_script_file()

    mi = mlab.MatlabCommand(script='whos',
                            script_file='testscript',
                            mfile=False)