<commit_before># -*- 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:
"""The fsl module provides classes for interfacing with the `FSL
<http://www.fmrib.ox.ac.uk/fsl/index.html>`_ command line tools.  This
was written to work with FSL version 4.1.4.

These are the base tools for working with FSL.
Preprocessing tools are found in fsl/preprocess.py
Model tools are found in fsl/model.py
DTI tools are found in fsl/dti.py

XXX Make this doc current!

Currently these tools are supported:

* BET v2.1: brain extraction
* FAST v4.1: segmentation and bias correction
* FLIRT v5.5: linear registration
* MCFLIRT: motion correction
* FNIRT v1.0: non-linear warp

Examples
--------
See the docstrings of the individual classes for examples.

"""
from __future__ import print_function, division, unicode_literals, absolute_import
from builtins import open, object

from glob import glob
import os

from ... import logging
from ...utils.filemanip import fname_presuffix
from ..base import traits, isdefined, CommandLine, CommandLineInputSpec
from ...external.due import BibTeX

LOGGER = logging.getLogger('interface')


class Info(object):
    """Handle fsl output type and version information.

    version refers to the version of fsl on the system

    output type refers to the type of file fsl defaults to writing
    eg, NIFTI, NIFTI_GZ

    """

    ftypes = {'NIFTI': '.nii',
              'NIFTI_PAIR': '.img',
              'NIFTI_GZ': '.nii.gz',
              'NIFTI_PAIR_GZ': '.img.gz'}

    @staticmethod
    def version():
        """Check for fsl version on system

        Parameters
        ----------
        None

        Returns
        -------
        version : str
           Version number as string or None if FSL not found

        """
        # find which fsl being used....and get version from
        # /path/to/fsl/etc/fslversion
        try:
            basedir = os.environ['FSLDIR']
        except KeyError:
            return None
        out = open('%s/etc/fslversion' % (basedir)).read()
        return out.strip('\n')

    @classmethod
    def output_type_to_ext(cls, output_type):
        """Get the file extension for the given output type.

        Parameters
        ----------
        output_type : {'NIFTI', 'NIFTI_GZ', 'NIFTI_PAIR', 'NIFTI_PAIR_GZ'}
            String specifying the output type.

        Returns
        -------
        extension : str
            The file extension for the output type.
        """

        try:
            return cls.ftypes[output_type]
        except KeyError:
            msg = 'Invalid FSLOUTPUTTYPE: ', output_type
            raise KeyError(msg)

    @classmethod
    def output_type(cls):
        """Get the global FSL output file type FSLOUTPUTTYPE.

        This returns the value of the environment variable
        FSLOUTPUTTYPE.  An exception is raised if it is not defined.

        Returns
        -------
        fsl_ftype : string
            Represents the current environment setting of FSLOUTPUTTYPE
        """
        try:
            return os.environ['FSLOUTPUTTYPE']
        except KeyError:
            LOGGER.warn('FSLOUTPUTTYPE environment variable is not set. '
                        'Setting FSLOUTPUTTYPE=NIFTI')
            return 'NIFTI'

    @staticmethod
    def standard_image(img_name=None):
        '''Grab an image from the standard location.

        Returns a list of standard images if called without arguments.

        Could be made more fancy to allow for more relocatability'''
        try:
            fsldir = os.environ['FSLDIR']
        except KeyError:
            raise Exception('FSL environment variables not set')
        stdpath = os.path.join(fsldir, 'data', 'standard')
        if img_name is None:
            return [filename.replace(stdpath + '/', '')
                    for filename in glob(os.path.join(stdpath, '*nii*'))]
        return os.path.join(stdpath, img_name)


class FSLCommandInputSpec(CommandLineInputSpec):
    """
    Base Input Specification for all FSL Commands

    All command support specifying FSLOUTPUTTYPE dynamically
    via output_type.

    Example
    -------
    fsl.ExtractRoi(tmin=42, tsize=1, output_type='NIFTI')
    """
    output_type = traits.Enum('NIFTI', list(Info.ftypes.keys()),
                              desc='FSL output type')


class FSLCommand(CommandLine):
    """Base support for FSL commands.

    """

    input_spec = FSLCommandInputSpec
    _output_type = None

    references_ = [{'entry': BibTeX('@article{WoolrichJbabdiPatenaudeChappellMakniBehrens'
                                    'BeckmannJenkinsonSmith2009,'
                                    'author={<NAME>, <NAME>, <NAME>, <NAME>, '
                                    '<NAME>, <NAME>, <NAME>, <NAME>, and <NAME>},'
                                    'title={Bayesian analysis of neuroimaging data in FSL},'
                                    'journal={NeuroImage},'
                                    'volume={45},'
                                    'number={1},'
                                    'pages={S173-186},'
                                    'year={2009},'
                                    '}'),
                    'tags': ['implementation'],
                    },
                   {'entry': BibTeX('@article{SmithJenkinsonWoolrichBeckmannBehrensJohansen'
                                    'BergBannisterDeLucaDrobnjakFlitneyNiazySaundersVickers'
                                    'ZhangDeStefanoBradyMatthews2004,'
                                    'author={<NAME>, <NAME>, <NAME>, <NAME>, '
                                    '<NAME>, <NAME>, <NAME>, <NAME>, '
                                    '<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, '
                                    '<NAME>, <NAME>, <NAME>, and <NAME>},'
                                    'title={Advances in functional and structural MR image analysis '
                                    'and implementation as FSL},'
                                    'journal={NeuroImage},'
                                    'volume={23},'
                                    'number={S1},'
                                    'pages={208-219},'
                                    'year={2004},'
                                    '}'),
                    'tags': ['implementation'],
                    },
                   {'entry': BibTeX('@article{JenkinsonBeckmannBehrensWoolrichSmith2012,'
                                    'author={<NAME>, <NAME>, <NAME>, '
                                    '<NAME>, and <NAME>},'
                                    'title={FSL},'
                                    'journal={NeuroImage},'
                                    'volume={62},'
                                    'pages={782-790},'
                                    'year={2012},'
                                    '}'),
                    'tags': ['implementation'],
                    }]

    def __init__(self, **inputs):
        super(FSLCommand, self).__init__(**inputs)
        self.inputs.on_trait_change(self._output_update, 'output_type')

        if self._output_type is None:<commit_msg>Only include 2012 FSL paper in refs.<commit_after># -*- 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:
"""The fsl module provides classes for interfacing with the `FSL
<http://www.fmrib.ox.ac.uk/fsl/index.html>`_ command line tools.  This
was written to work with FSL version 4.1.4.

These are the base tools for working with FSL.
Preprocessing tools are found in fsl/preprocess.py
Model tools are found in fsl/model.py
DTI tools are found in fsl/dti.py

XXX Make this doc current!

Currently these tools are supported:

* BET v2.1: brain extraction
* FAST v4.1: segmentation and bias correction
* FLIRT v5.5: linear registration
* MCFLIRT: motion correction
* FNIRT v1.0: non-linear warp

Examples
--------
See the docstrings of the individual classes for examples.

"""
from __future__ import print_function, division, unicode_literals, absolute_import
from builtins import open, object

from glob import glob
import os

from ... import logging
from ...utils.filemanip import fname_presuffix
from ..base import traits, isdefined, CommandLine, CommandLineInputSpec
from ...external.due import BibTeX

LOGGER = logging.getLogger('interface')


class Info(object):
    """Handle fsl output type and version information.

    version refers to the version of fsl on the system

    output type refers to the type of file fsl defaults to writing
    eg, NIFTI, NIFTI_GZ

    """

    ftypes = {'NIFTI': '.nii',
              'NIFTI_PAIR': '.img',
              'NIFTI_GZ': '.nii.gz',
              'NIFTI_PAIR_GZ': '.img.gz'}

    @staticmethod
    def version():
        """Check for fsl version on system

        Parameters
        ----------
        None

        Returns
        -------
        version : str
           Version number as string or None if FSL not found

        """
        # find which fsl being used....and get version from
        # /path/to/fsl/etc/fslversion
        try:
            basedir = os.environ['FSLDIR']
        except KeyError:
            return None
        out = open('%s/etc/fslversion' % (basedir)).read()
        return out.strip('\n')

    @classmethod
    def output_type_to_ext(cls, output_type):
        """Get the file extension for the given output type.

        Parameters
        ----------
        output_type : {'NIFTI', 'NIFTI_GZ', 'NIFTI_PAIR', 'NIFTI_PAIR_GZ'}
            String specifying the output type.

        Returns
        -------
        extension : str
            The file extension for the output type.
        """

        try:
            return cls.ftypes[output_type]
        except KeyError:
            msg = 'Invalid FSLOUTPUTTYPE: ', output_type
            raise KeyError(msg)

    @classmethod
    def output_type(cls):
        """Get the global FSL output file type FSLOUTPUTTYPE.

        This returns the value of the environment variable
        FSLOUTPUTTYPE.  An exception is raised if it is not defined.

        Returns
        -------
        fsl_ftype : string
            Represents the current environment setting of FSLOUTPUTTYPE
        """
        try:
            return os.environ['FSLOUTPUTTYPE']
        except KeyError:
            LOGGER.warn('FSLOUTPUTTYPE environment variable is not set. '
                        'Setting FSLOUTPUTTYPE=NIFTI')
            return 'NIFTI'

    @staticmethod
    def standard_image(img_name=None):
        '''Grab an image from the standard location.

        Returns a list of standard images if called without arguments.

        Could be made more fancy to allow for more relocatability'''
        try:
            fsldir = os.environ['FSLDIR']
        except KeyError:
            raise Exception('FSL environment variables not set')
        stdpath = os.path.join(fsldir, 'data', 'standard')
        if img_name is None:
            return [filename.replace(stdpath + '/', '')
                    for filename in glob(os.path.join(stdpath, '*nii*'))]
        return os.path.join(stdpath, img_name)


class FSLCommandInputSpec(CommandLineInputSpec):
    """
    Base Input Specification for all FSL Commands

    All command support specifying FSLOUTPUTTYPE dynamically
    via output_type.

    Example
    -------
    fsl.ExtractRoi(tmin=42, tsize=1, output_type='NIFTI')
    """
    output_type = traits.Enum('NIFTI', list(Info.ftypes.keys()),
                              desc='FSL output type')


class FSLCommand(CommandLine):
    """Base support for FSL commands.

    """

    input_spec = FSLCommandInputSpec
    _output_type = None

    references_ = [{'entry': BibTeX('@article{JenkinsonBeckmannBehrensWoolrichSmith2012,'
                                    'author={<NAME>, <NAME>, <NAME>, '
                                    '<NAME>, and <NAME>},'
                                    'title={FSL},'
                                    'journal={NeuroImage},'
                                    'volume={62},'
                                    'pages={782-790},'
                                    'year={2012},'
                                    '}'),
                    'tags': ['implementation'],
                    }]

    def __init__(self, **inputs):
        super(FSLCommand, self).__init__(**inputs)
        self.inputs.on_trait_change(self._output_update, 'output_type')

        if self._output_type is None:
{'fraction_non_alphanumeric': 0.1056929908024104, 'fraction_numerical': 0.008563273073263558, 'mean_word_length': 1.6945097201452681, 'pattern_counts': {'":': 0, '<': 41, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 41, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6412312', 'n_tokens_mistral': 3594, 'n_tokens_neox': 3343, 'n_words': 987}