<commit_before># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""The spm module provides basic functions for interfacing with SPM  tools."""


from nipype.interfaces.traits import Directory
__docformat__ = 'restructuredtext'

# Standard library imports
import os
from copy import deepcopy
import re

# Third-party imports
import numpy as np
from scipy.io import savemat

# Local imports
from nipype.interfaces.base import BaseInterface, traits, TraitedSpec,\
    InputMultiPath, BaseInterfaceInputSpec
from nipype.utils.misc import isdefined
from nibabel import load
from nipype.interfaces.matlab import MatlabCommand

import nipype.utils.spm_docs as sd
                                    
import logging
logger = logging.getLogger('iflogger')

def func_is_3d(in_file):
    """Checks if input functional files are 3d."""
    
    if isinstance(in_file, list):
        return func_is_3d(in_file[0])
    else:
        img = load(in_file)
        shape = img.get_shape() 
        if len(shape) == 3 or (len(shape)==4 and shape[3]==1):
            return True
        else:
            return False
        
def get_first_3dfile(in_files):
    if not func_is_3d(in_files):
        return None
    if isinstance(in_files[0], list):
        return in_files[0]
    return in_files    

def scans_for_fname(fname):
    """Reads a nifti file and converts it to a numpy array storing
    individual nifti volumes.
    
    Opens images so will fail if they are not found.
    
    """
    if isinstance(fname,list):
        scans = np.zeros((len(fname),),dtype=object)
        for sno,f in enumerate(fname):
            scans[sno] = '%s,1'%f
        return scans
    img = load(fname)
    if len(img.get_shape()) == 3:
        return np.array(('%s,1'%fname,),dtype=object)
    else:
        n_scans = img.get_shape()[3]
        scans = np.zeros((n_scans,),dtype=object)
        for sno in range(n_scans):
            scans[sno] = '%s,%d'% (fname, sno+1)
        return scans

def scans_for_fnames(fnames,keep4d=False,separate_sessions=False):
    """Converts a list of files to a concatenated numpy array for each
    volume.

    keep4d : boolean
        keeps the entries of the numpy array as 4d files instead of
        extracting the individual volumes.
    separate_sessions: boolean
        if 4d nifti files are being used, then separate_sessions
        ensures a cell array per session is created in the structure.
        
    """
    flist = None
    if not isinstance(fnames[0], list):
        if func_is_3d(fnames[0]):
            fnames = [fnames]
    if separate_sessions or keep4d:
        flist = np.zeros((len(fnames),),dtype=object)
    for i,f in enumerate(fnames):
        if separate_sessions:
            if keep4d:
                if isinstance(f,list):
                    flist[i] = np.array(f, dtype=object)
                else:
                    flist[i] = np.array([f],dtype=object)
            else:
                flist[i] = scans_for_fname(f)
        else:
            if keep4d:
                flist[i] = f
            else:
                scans = scans_for_fname(f)
                if flist is None:
                    flist = scans
                else:
                    flist = np.concatenate((flist,scans))
    return flist

class Info(object):
    """Handles SPM version information
    """
    @staticmethod
    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');
        fprintf(1, 'NIPYPE  %s', spm_path);
        exit;
        """
        mlab.inputs.mfile = False
        try:
            out = mlab.run()
        except IOError, e:
            # if no Matlab at all -- exception could be raised
            # No Matlab -- no spm
            logger.debug(str(e))
            return None
        if out.runtime.returncode == 0:
            spm_path = sd._strip_header(out.runtime.stdout)
        else:
            logger.debug(out.runtime.stderr)
            return None
        return spm_path


def no_spm():
    """ Checks if SPM is NOT installed
    used with nosetests skipif to skip tests
    that will fail if spm is not installed"""

    if Info.version() == None:
        return True
    else:
        return False

    
class SPMCommandInputSpec(BaseInterfaceInputSpec):
    matlab_cmd = traits.Str(desc='matlab command to use')
    paths = InputMultiPath(Directory(), desc='Paths to add to matlabpath')
    mfile = traits.Bool(True, desc='Run m-code using m-file',
                          usedefault=True)
    use_mcr = traits.Bool(desc='Run m-code using SPM MCR')
<commit_msg>fixed spm version<commit_after># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""The spm module provides basic functions for interfacing with SPM  tools."""


from nipype.interfaces.traits import Directory
__docformat__ = 'restructuredtext'

# Standard library imports
import os
from copy import deepcopy
import re

# Third-party imports
import numpy as np
from scipy.io import savemat

# Local imports
from nipype.interfaces.base import BaseInterface, traits, TraitedSpec,\
    InputMultiPath, BaseInterfaceInputSpec
from nipype.utils.misc import isdefined
from nibabel import load
from nipype.interfaces.matlab import MatlabCommand

import nipype.utils.spm_docs as sd
                                    
import logging
logger = logging.getLogger('iflogger')

def func_is_3d(in_file):
    """Checks if input functional files are 3d."""
    
    if isinstance(in_file, list):
        return func_is_3d(in_file[0])
    else:
        img = load(in_file)
        shape = img.get_shape() 
        if len(shape) == 3 or (len(shape)==4 and shape[3]==1):
            return True
        else:
            return False
        
def get_first_3dfile(in_files):
    if not func_is_3d(in_files):
        return None
    if isinstance(in_files[0], list):
        return in_files[0]
    return in_files    

def scans_for_fname(fname):
    """Reads a nifti file and converts it to a numpy array storing
    individual nifti volumes.
    
    Opens images so will fail if they are not found.
    
    """
    if isinstance(fname,list):
        scans = np.zeros((len(fname),),dtype=object)
        for sno,f in enumerate(fname):
            scans[sno] = '%s,1'%f
        return scans
    img = load(fname)
    if len(img.get_shape()) == 3:
        return np.array(('%s,1'%fname,),dtype=object)
    else:
        n_scans = img.get_shape()[3]
        scans = np.zeros((n_scans,),dtype=object)
        for sno in range(n_scans):
            scans[sno] = '%s,%d'% (fname, sno+1)
        return scans

def scans_for_fnames(fnames,keep4d=False,separate_sessions=False):
    """Converts a list of files to a concatenated numpy array for each
    volume.

    keep4d : boolean
        keeps the entries of the numpy array as 4d files instead of
        extracting the individual volumes.
    separate_sessions: boolean
        if 4d nifti files are being used, then separate_sessions
        ensures a cell array per session is created in the structure.
        
    """
    flist = None
    if not isinstance(fnames[0], list):
        if func_is_3d(fnames[0]):
            fnames = [fnames]
    if separate_sessions or keep4d:
        flist = np.zeros((len(fnames),),dtype=object)
    for i,f in enumerate(fnames):
        if separate_sessions:
            if keep4d:
                if isinstance(f,list):
                    flist[i] = np.array(f, dtype=object)
                else:
                    flist[i] = np.array([f],dtype=object)
            else:
                flist[i] = scans_for_fname(f)
        else:
            if keep4d:
                flist[i] = f
            else:
                scans = scans_for_fname(f)
                if flist is None:
                    flist = scans
                else:
                    flist = np.concatenate((flist,scans))
    return flist

class Info(object):
    """Handles SPM version information
    """
    @staticmethod
    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');
        fprintf(1, 'NIPYPE  %s', spm_path);
        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
        else:
            return sd._strip_header(out.runtime.stdout)

def no_spm():
    """ Checks if SPM is NOT installed
    used with nosetests skipif to skip tests
    that will fail if spm is not installed"""

    if Info.version() == None:
        return True
    else:
        return False

    
class SPMCommandInputSpec(BaseInterfaceInputSpec):
    matlab_cmd = traits.Str(desc='matlab command to use')
    paths = InputMultiPath(Directory(), desc='Paths to add to matlabpath')
    mfile = traits.Bool(True, desc='Run m-code using m-file',
                          usedefault=True)
    use_mcr = traits.Bool(desc='Run m-code using SPM MCR')

{'fraction_non_alphanumeric': 0.09268514311676511, 'fraction_numerical': 0.005906406179009541, 'mean_word_length': 2.054676658340272, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5805464', 'n_tokens_mistral': 3371, 'n_tokens_neox': 3290, 'n_words': 980}