3
dg'                 @   s   d Z ddlZddlmZ ddlmZ ddlmZmZ ddl	m
Z
mZ dd	lmZmZmZmZmZmZmZ dd
lmZ ejdZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZdd ZdS )z*Provide a base interface to AFNI commands.    N)platform)spawn   )loggingLooseVersion)split_filenamefname_presuffix   )CommandLinetraitsCommandLineInputSpec	isdefinedFileTraitedSpecPackageInfo)BibTeXznipype.interfacec               @   sT   e Zd ZdZdZddddZdZedd	 Ze	d
d Z
e	dd Zedd ZdS )Infoz0Handle afni output type and version information.AFNIz.nii z.nii.gz)ZNIFTIr   ZNIFTI_GZzafni --versionc             C   s   | j dd j dd }|jdr2|j dd }n(|jdrV|j dd j d	d }nd
S t|jddjd
d }|d dk r|d d |d< t|S )zCheck and parse AFNI's version.
r   zVersion    r   ZAFNI_ZDebianzDebian-~N_.r   i  i  )split
startswithr   replaceversiontuple)Zraw_infoZversion_stampr    r   =/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/afni/base.pyparse_version!   s    

zInfo.parse_versionc             C   sD   y
| j | S  tk
r> } zd|f}t||W Y dd}~X nX dS )a:  
        Get the file extension for the given output type.

        Parameters
        ----------
        outputtype : {'NIFTI', 'NIFTI_GZ', 'AFNI'}
            String specifying the output type.

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

        zInvalid AFNIOUTPUTTYPE: N)ftypesKeyError)cls
outputtypeemsgr   r   r    output_type_to_ext1   s
    
zInfo.output_type_to_extc             C   s   dS )z
        Set default output filetype.

        AFNI has no environment variables, Output filetypes get set in command line calls
        Nipype uses ``AFNI`` as default


        Returns
        -------
        None

        r   r   )r$   r   r   r    r%   G   s    zInfo.outputtypec             C   sJ   t dddddj }|jjdkr$dS |jj}tjj|d }tjj|| S )z
        Grab an image from the standard location.

        Could be made more fancy to allow for more relocatability

        z
which afniTFZ	allatonce)Zignore_exceptionZresource_monitorZterminal_outputr   N)	r
   runruntime
returncodestdoutospathr   join)Zimg_nameZcloutoutbasedirr   r   r    standard_imageW   s    zInfo.standard_imageN)__name__
__module____qualname____doc__Z_Info__outputtyper"   Zversion_cmdstaticmethodr!   classmethodr(   r%   r2   r   r   r   r    r      s   r   c                   s"   e Zd ZdZd fdd	Z  ZS )AFNICommandBasea  
    A base class to fix a linking problem in OSX and AFNI.

    See Also
    --------
    `This thread
    <http://afni.nimh.nih.gov/afni/community/board/read.php?1,145346,145347#msg-145347>`__
    about the particular environment variable that fixes this problem.

    r   c                s$   t dkrd|jd< tt| j||S )Ndarwinz/usr/local/afni/ZDYLD_FALLBACK_LIBRARY_PATH)r   environsuperr9   _run_interface)selfr*   Zcorrect_return_codes)	__class__r   r    r=   y   s    

zAFNICommandBase._run_interfacer   )r@   )r3   r4   r5   r6   r=   __classcell__r   r   )r?   r    r9   m   s   
r9   c               @   sJ   e Zd ZejdddddZejdeej	j
 ddZedd	d
dgdZdS )AFNICommandInputSpecr   Tzset number of threads)
usedefaultZnohashdescr   zAFNI output filetype)rD   z%s_afnizoutput image file namez
-prefix %sin_file)Zname_templaterD   Zargstrname_sourceN)r3   r4   r5   r   ZIntnum_threadsEnumlistr   r"   keysr%   r   out_filer   r   r   r    rB      s   rB   c               @   s   e Zd ZedddZdS )AFNICommandOutputSpeczoutput fileT)rD   existsN)r3   r4   r5   r   rK   r   r   r   r    rL      s   rL   c                   s   e Zd ZdZeZdZeddgdeddgdgZe	dd Z
e
jd	d Z
ed
d Z fddZdd Zdd ZdddZ fddZdddZ  ZS )AFNICommandz)Shared options for several AFNI commands.Nz@article{Cox1996,author={R.W. Cox},title={AFNI: software for analysis and visualization of functional magnetic resonance neuroimages},journal={Computers and Biomedical research},volume={29},number={3},pages={162-173},year={1996},}implementation)entrytagsz@article{CoxHyde1997,author={R.W. Cox and J.S. Hyde},title={Software tools for analysis and visualization of fMRI data},journal={NMR in Biomedicine},volume={10},number={45},pages={171-178},year={1997},}c             C   s   | j jS )zGet number of threads.)inputsrG   )r>   r   r   r    rG      s    zAFNICommand.num_threadsc             C   s   || j _d S )N)rR   rG   )r>   valuer   r   r    rG      s    c             C   s"   |t jkr|| _ntd| dS )a4  
        Set the default output type for AFNI classes.

        This method is used to set the default output type for all afni
        subclasses.  However, setting this will not update the output
        type for any existing instances.  For these, assign the
        <instance>.inputs.outputtype.
        zInvalid AFNI outputtype: %sN)r   r"   _outputtypeAttributeError)r$   r%   r   r   r    set_default_output_type   s    

z#AFNICommand.set_default_output_typec                sv   t t| jf | | jj| jd t| jdr>| jj| jd | jdkrRt	j
 | _t| jj
sj| j| j_
n| j  dS )z)Instantiate an AFNI command tool wrapper.r%   rG   N)r<   rN   __init__rR   Zon_trait_change_output_updatehasattr_nthreads_updaterT   r   r%   r   )r>   rR   )r?   r   r    rW      s    

zAFNICommand.__init__c             C   s   d| j j | j jd< dS )z.Update environment with new number of threads.z%dZOMP_NUM_THREADSN)rR   rG   r;   )r>   r   r   r    rZ      s    zAFNICommand._nthreads_updatec             C   s   | j j| _dS )z
        Update the internal property with the provided input.

        i think? updates class private attribute based on instance input
        in fsl also updates ENVIRON variable....not valid in afni
        as it uses no environment variables
        N)rR   r%   rT   )r>   r   r   r    rX      s    zAFNICommand._output_updatec             C   s*   t |\}}}tjj||tj| jj S )N)r   r-   r.   r/   r   r(   rR   r%   )r>   rS   namer.   baser   r   r   r    _overload_extension   s    zAFNICommand._overload_extensionc                sz   t t| j }tdd d}t| jjf |j }|rvx>|D ]6}|| r<t|| \}}}|dkr<|| d ||< q<W |S )Nc             S   s   | d k	S )Nr   )tr   r   r    <lambda>   s    z+AFNICommand._list_outputs.<locals>.<lambda>)rF   r   z
+orig.BRIK)	r<   rN   _list_outputsdictrI   rR   r   rJ   r   )r>   outputsmetadataZ	out_namesr[   r   ext)r?   r   r    r`      s    
zAFNICommand._list_outputsTc             C   s~   |sd| j  }|d7 }t||dkr.tj }|dkrDtj| jj}|r^|rZdj||fn|}|dkrjd}t	||d|d}|S )a   
        Generate a filename based on the given parameters.

        The filename will take the form: cwd/basename<suffix><ext>.
        If change_ext is True, it will use the extentions specified in
        <instance>intputs.output_type.

        Parameters
        ----------
        basename : str
            Filename to base the new filename on.
        cwd : str
            Path to prefix to the new filename. (default is os.getcwd())
        suffix : str
            Suffix to add to the `basename`.  (defaults is '' )
        change_ext : bool
            Flag to change the filename extension to the FSL output type.
            (default True)

        Returns
        -------
        fname : str
            New filename based on given parameters.

        z,Unable to generate filename for command %s. zbasename is not set!Nr   F)suffixZuse_extnewpath)
cmd
ValueErrorr-   getcwdr   r(   rR   r%   r/   r   )r>   basenamecwdre   Z
change_extrd   r'   fnamer   r   r    
_gen_fname  s    
zAFNICommand._gen_fname)N)NNTN)r3   r4   r5   r6   rB   Z
input_specrT   r   Z_referencespropertyrG   setterr8   rV   rW   rZ   rX   r]   r`   rm   rA   r   r   )r?   r    rN      s$   

rN   c               @   s>   e Zd Zejdeejj ddZ	ej
dedddddZdS )	AFNIPythonCommandInputSpecr   zAFNI output filetype)rD   Zpython2T)rM   )rC   defaultN)r3   r4   r5   r   rH   rI   r   r"   rJ   r%   ZEitherr   	py27_pathr   r   r   r    rp   0  s   rp   c                   s0   e Zd ZdZe fddZedd Z  ZS )AFNIPythonCommandz2A subtype of AFNI command line for Python scripts.c                s&   t t| j}tj|}|dk	r"|S |S )zRevise the command path.N)r<   rs   rg   r   find_executable)r>   Zorig_cmdfound)r?   r   r    rg   <  s    
zAFNIPythonCommand.cmdc             C   s   dj | jjS )Nz{} )formatrR   rr   )r>   r   r   r    _cmd_prefixC  s    zAFNIPythonCommand._cmd_prefix)r3   r4   r5   r6   rn   rg   rw   rA   r   r   )r?   r    rs   9  s   rs   c               C   s   t j dkrdS dS )z$Check whether AFNI is not available.NTF)r   r   r   r   r   r    no_afniH  s    rx   ) r6   r-   sysr   	distutilsr   r   r   r   Zutils.filemanipr   r   r\   r
   r   r   r   r   r   r   Zexternal.duer   	getLoggerZIFLOGGERr   r9   rB   rL   rN   rp   rs   rx   r   r   r   r    <module>   s"   $	
S 	