3
d?                 @   s  d dl Z d dlZddlmZmZmZmZ ddlm	Z	m
Z
mZmZmZmZ ddlmZmZmZm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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 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 d0d1 d1eZ'dS )2    N   )split_filenamefname_presuffixensure_listsimplify_list   )TraitedSpec	isdefinedFiletraitsOutputMultiPathInputMultiPath   )SPMCommandInputSpec
SPMCommandscans_for_fnamesscans_for_fnamec               @   s   e Zd ZedddZdS )Analyze2niiInputSpecT)exists	mandatoryN)__name__
__module____qualname__r
   analyze_file r   r   =/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/spm/utils.pyr      s   r   c               @   s   e Zd ZeddZdS )Analyze2niiOutputSpecT)r   N)r   r   r   r
   
nifti_filer   r   r   r   r      s   r   c               @   s$   e Zd ZeZeZdd Zdd ZdS )Analyze2niic             C   sX   d| j j }t| j j\}}}tjjtj |d | _|d7 }|d| j 7 }|d7 }|S )NzV = spm_vol('%s');
z.niiz[Y, XYZ] = spm_read_vols(V);
zV.fname = '%s';
zspm_write_vol(V, Y);
)inputsr   r   ospathjoingetcwdoutput_name)self_scriptnamer   r   r   _make_matlab_command   s    z Analyze2nii._make_matlab_commandc             C   s   | j  j }| j|d< |S )Nr   )_outputsgetr$   )r%   outputsr   r   r   _list_outputs)   s    
zAnalyze2nii._list_outputsN)	r   r   r   r   
input_specr   output_specr)   r-   r   r   r   r   r      s   
r   c               @   s>   e Zd ZeddddZedddddZeddZed	dZd
S )CalcCoregAffineInputSpecTz&target for generating affine transform)r   r   descFz7volume transform can be applied to register with target)r   r   copyfiler1   z$Filename used to store affine matrix)r1   z,Filename used to store inverse affine matrixN)r   r   r   r
   targetmovingmatinvmatr   r   r   r   r0   /   s   
r0   c               @   s"   e Zd ZedddZeddZdS )CalcCoregAffineOutputSpecTzMatlab file holding transform)r   r1   z%Matlab file holding inverse transform)r1   N)r   r   r   r
   r5   r6   r   r   r   r   r7   =   s   r7   c               @   s8   e Zd ZdZeZeZdd Zdd Z	dd Z
dd	 Zd
S )CalcCoregAffinea  Uses SPM (spm_coreg) to calculate the transform mapping
    moving to target. Saves Transform in mat (matlab binary file)
    Also saves inverse transform

    Examples
    --------

    >>> import nipype.interfaces.spm.utils as spmu
    >>> coreg = spmu.CalcCoregAffine(matlab_cmd='matlab-spm8')
    >>> coreg.inputs.target = 'structural.nii'
    >>> coreg.inputs.moving = 'functional.nii'
    >>> coreg.inputs.mat = 'func_to_struct.mat'
    >>> coreg.run() # doctest: +SKIP

    .. note::

     * the output file mat is saves as a matlab binary file
     * calculating the transforms does NOT change either input image
       it does not **move** the moving image, only calculates the transform
       that can be used to move it
    c             C   s   t | jjdd}|S )z9makes filename to hold inverse transform if not specifiedZinverse_)prefix)r   r   r5   )r%   r6   r   r   r   _make_inv_file\   s    zCalcCoregAffine._make_inv_filec             C   s>   t | jj\}}}t | jj\}}}tjj|d||f }|S )z%makes name for matfile if doesn existz%s_to_%s.mat)r   r   r4   r3   r    r!   r"   )r%   pthmvr&   Ztgtr5   r   r   r   _make_mat_filea   s    zCalcCoregAffine._make_mat_filec             C   sT   t | jjs| j | j_t | jjs0| j | j_d| jj| jj| jj| jjf }|S )z checks for SPM, generates scripta  
        target = '%s';
        moving = '%s';
        targetv = spm_vol(target);
        movingv = spm_vol(moving);
        x = spm_coreg(targetv, movingv);
        M = spm_matrix(x);
        save('%s' , 'M' );
        M = inv(M);
        save('%s','M')
        )r	   r   r5   r=   r6   r:   r3   r4   )r%   r&   r'   r   r   r   r)   h   s    z$CalcCoregAffine._make_matlab_commandc             C   s8   | j  j }tjj| jj|d< tjj| jj|d< |S )Nr5   r6   )r*   r+   r    r!   abspathr   r5   r6   )r%   r,   r   r   r   r-      s    zCalcCoregAffine._list_outputsN)r   r   r   __doc__r0   r.   r7   r/   r:   r=   r)   r-   r   r   r   r   r8   B   s   r8   c               @   s6   e Zd ZedddddZeddddZedddZdS )	ApplyTransformInputSpecTz1file to apply transform to, (only updates header))r   r   r2   r1   zfile holding transform to apply)r   r   r1   z%output file name for transformed data)r1   ZgenfileN)r   r   r   r
   in_filer5   out_filer   r   r   r   r@      s   r@   c               @   s   e Zd ZedddZdS )ApplyTransformOutputSpecTzTransformed image file)r   r1   N)r   r   r   r
   rB   r   r   r   r   rC      s   rC   c               @   s0   e Zd ZdZeZeZdd Zdd Z	dd Z
dS )	ApplyTransformaK  Uses SPM to apply transform stored in a .mat file to given file

    Examples
    --------

    >>> import nipype.interfaces.spm.utils as spmu
    >>> applymat = spmu.ApplyTransform()
    >>> applymat.inputs.in_file = 'functional.nii'
    >>> applymat.inputs.mat = 'func_to_struct.mat'
    >>> applymat.run() # doctest: +SKIP

    c             C   s2   | j  }|d | j_d| jj| jj| jjf }|S )z checks for SPM, generates scriptrB   a&  
        infile = '%s';
        outfile = '%s'
        transform = load('%s');

        V = spm_vol(infile);
        X = spm_read_vols(V);
        [p n e v] = spm_fileparts(V.fname);
        V.mat = transform.M * V.mat;
        V.fname = fullfile(outfile);
        spm_write_vol(V,X);

        )r-   r   rB   rA   r5   )r%   r&   r,   r'   r   r   r   r)      s    z#ApplyTransform._make_matlab_commandc             C   sF   | j  j }t| jjs.tjj| j |d< ntjj| jj|d< |S )NrB   )	r/   r+   r	   r   rB   r    r!   r>   _gen_outfilename)r%   r,   r   r   r   r-      s
    zApplyTransform._list_outputsc             C   s   t | jj\}}}|d S )Nz
_trans.nii)r   r   rA   )r%   r&   r(   r   r   r   rE      s    zApplyTransform._gen_outfilenameN)r   r   r   r?   r@   r.   rC   r/   r)   r-   rE   r   r   r   r   rD      s   rD   c               @   sD   e Zd ZeddddZeddddZejdddddZed	d
Z	dS )ResliceInputSpecTz1file to apply transform to, (only updates header))r   r   r1   z+Volume defining space to slice in_file intor      zHdegree of b-spline used for interpolation0 is nearest neighbor (default))lowhigh
usedefaultr1   z%Optional file to save resliced volume)r1   N)
r   r   r   r
   rA   space_definingr   RangeinterprB   r   r   r   r   rF      s   rF   c               @   s   e Zd ZedddZdS )ResliceOutputSpecTzresliced volume)r   r1   N)r   r   r   r
   rB   r   r   r   r   rN      s   rN   c               @   s(   e Zd ZdZeZeZdd Zdd Z	dS )ReslicezBuses  spm_reslice to resample in_file into space of space_definingc             C   s>   t | jjs t| jjdd| j_d| jj| jj| jjf }|S )zgenerates scriptr)r9   z
        flags.mean = 0;
        flags.which = 1;
        flags.mask = 0;
        flags.interp = %d;
        infiles = strvcat('%s', '%s');
        invols = spm_vol(infiles);
        spm_reslice(invols, flags);
        )r	   r   rB   r   rA   rM   rK   )r%   r&   r'   r   r   r   r)      s    	zReslice._make_matlab_commandc             C   s$   | j  j }tjj| jj|d< |S )NrB   )r*   r+   r    r!   r>   r   rB   )r%   r,   r   r   r   r-      s    zReslice._list_outputsN)
r   r   r   r?   rF   r.   rN   r/   r)   r-   r   r   r   r   rO      s
   rO   c               @   s   e Zd ZeeddddddZeddddZedd	d
dgdZeddd
dgdZe	j
dddddZe	je	j dddddZe	je	j dddddZdS )ApplyInverseDeformationInputT)r   fnamesz%Files on which deformation is applied)r   fieldr1   zcomp{1}.inv.spacezFile defining target space)r   rS   r1   z"comp{1}.inv.comp{1}.sn2def.matnamezSN SPM deformation filedeformation_field)r   rS   r1   xorzcomp{1}.inv.comp{1}.defdeformationr   rG   rM   z)degree of b-spline used for interpolation)rH   rI   rS   r1   zcomp{1}.inv.comp{1}.sn2def.bb   z6-element list (opt))rS   minlenmaxlenr1   zcomp{1}.inv.comp{1}.sn2def.voxr   z3-element list (opt)N)r   r   r   r   r
   in_filesr3   rV   rT   r   rL   interpolationListFloatbounding_boxvoxel_sizesr   r   r   r   rQ     s>   

rQ   c               @   s   e Zd ZeeddddZdS )ApplyInverseDeformationOutputT)r   zTransformed files)r1   N)r   r   r   r   r
   	out_filesr   r   r   r   r`   /  s   r`   c               @   s0   e Zd ZdZeZeZdZdZ	dd Z
dd ZdS )	ApplyInverseDeformationa  Uses spm to apply inverse deformation stored in a .mat file or a
    deformation field to a given file

    Examples
    --------

    >>> import nipype.interfaces.spm.utils as spmu
    >>> inv = spmu.ApplyInverseDeformation()
    >>> inv.inputs.in_files = 'functional.nii'
    >>> inv.inputs.deformation = 'struct_to_func.mat'
    >>> inv.inputs.target = 'structural.nii'
    >>> inv.run() # doctest: +SKIP
    utildefsc             C   sd   |dkrt t|S |dkr(tt|S |dkrDtjt|gtdS |dkr`tjt|gtdS |S )z+Convert input to appropriate format for spmrZ   r3   rV   )dtyperT   )r   r   r   nparrayr   object)r%   optspecvalr   r   r   _format_argH  s    z#ApplyInverseDeformation._format_argc             C   sT   | j  j }g |d< x:| jjD ].}tjj|\}}|d jtjjd|  qW |S )Nra   zw%s)	r*   r+   r   rZ   r    r!   splitappendrealpath)r%   r,   filenamer&   fnamer   r   r   r-   T  s    z%ApplyInverseDeformation._list_outputsN)r   r   r   r?   rQ   r.   r`   r/   _jobtype_jobnamerl   r-   r   r   r   r   rb   3  s   rb   c               @   sr   e Zd ZeeddddddZeddddZejd	d
dddZ	ej
ej dddddZej
ej dddddZdS )ResliceToReferenceInputT)r   rR   z%Files on which deformation is applied)r   rS   r1   zcomp{1}.id.spacezFile defining target space)r   rS   r1   r   rG   rM   z)degree of b-spline used for interpolation)rH   rI   rS   r1   zcomp{2}.idbbvox.bbrW   z6-element list (opt))rS   rX   rY   r1   zcomp{2}.idbbvox.voxr   z3-element list (opt)N)r   r   r   r   r
   rZ   r3   r   rL   r[   r\   r]   r^   r_   r   r   r   r   rt   ]  s*   rt   c               @   s   e Zd ZeeddddZdS )ResliceToReferenceOutputT)r   zTransformed files)r1   N)r   r   r   r   r
   ra   r   r   r   r   ru   {  s   ru   c               @   s0   e Zd ZdZeZeZdZdZ	dd Z
dd ZdS )	ResliceToReferenceah  Uses spm to reslice a volume to a target image space or to a provided
    voxel size and bounding box

    Examples
    --------

    >>> import nipype.interfaces.spm.utils as spmu
    >>> r2ref = spmu.ResliceToReference()
    >>> r2ref.inputs.in_files = 'functional.nii'
    >>> r2ref.inputs.target = 'structural.nii'
    >>> r2ref.run() # doctest: +SKIP
    rc   rd   c             C   sd   |dkrt t|S |dkr(tt|S |dkrDtjt|gtdS |dkr`tjt|gtdS |S )z+Convert input to appropriate format for spmrZ   r3   rV   )re   rT   )r   r   r   rf   rg   r   rh   )r%   ri   rj   rk   r   r   r   rl     s    zResliceToReference._format_argc             C   sT   | j  j }g |d< x:| jjD ].}tjj|\}}|d jtjjd|  qW |S )Nra   zw%s)	r*   r+   r   rZ   r    r!   rm   rn   ro   )r%   r,   rp   r&   rq   r   r   r   r-     s    z ResliceToReference._list_outputsN)r   r   r   r?   rt   r.   ru   r/   rr   rs   rl   r-   r   r   r   r   rv     s   rv   c               @   sv   e Zd ZeeddddddZejdddd	d
ddddd	Zej	dddddZ
ejddddddZejdddddZdS )DicomImportInputSpecT)r   datazdicom files to be converted)r   rS   r1   flatseriespatname
patid_datepatid	date_timerootz#directory structure for the output.)rS   rJ   r1   z./converted_dicomoutdirzoutput directory.Zniiimgzconvopts.formatzoutput format.Fzconvopts.icedimszIf image sorting fails, one can try using the additional SIEMENS ICEDims information to create unique filenames. Use this only if there would be multiple volumes with exactly the same file names.N)r   r   r   r   r
   rZ   r   Enumoutput_dir_structStr
output_dirformatZBoolicedimsr   r   r   r   rw     s0   rw   c               @   s   e Zd ZeeddddZdS )DicomImportOutputSpecT)r   zconverted files)r1   N)r   r   r   r   r
   ra   r   r   r   r   r     s   r   c                   sD   e Zd ZdZeZeZdZdZ	 fddZ
 fddZdd	 Z  ZS )
DicomImporta  Uses spm to convert DICOM files to nii or img+hdr.

    Examples
    --------

    >>> import nipype.interfaces.spm.utils as spmu
    >>> di = spmu.DicomImport()
    >>> di.inputs.in_files = ['functional_1.dcm', 'functional_2.dcm']
    >>> di.run() # doctest: +SKIP
    rc   Zdicomc                sj   |dkrt j|tdS |dkr.t j|gtdS |dkrBtjj|S |dkrV|rRdS dS tt| j|||S )z+Convert input to appropriate format for spmrZ   )re   r   r   r   r   )	rf   rg   rh   r    r!   r>   superr   rl   )r%   ri   rj   rk   )	__class__r   r   rl     s    zDicomImport._format_argc                s6   t jj| jj}t jj|s&t j| tt| j	|S )N)
r    r!   r>   r   r   isdirmkdirr   r   _run_interface)r%   Zruntimeod)r   r   r   r     s    
zDicomImport._run_interfacec          	   C   s   ddl m } | j j }tjj| jj}| jj}| jj	dkrX|tjj
|d| |d< n| jj	dkr|tjj
|tjj
dd| |d< nh| jj	dkr|tjj
|tjj
ddd| |d< n4| jj	dkr|tjj
|tjj
dddd| |d< |S )Nr   )globry   z*.%sra   rz   *r}   r~   r{   r|   )r}   r~   r{   )r   r*   r+   r    r!   r>   r   r   r   r   r"   )r%   r   r,   r   extr   r   r   r-     s     $&&zDicomImport._list_outputs)r   r   r   r?   rw   r.   r   r/   rr   rs   rl   r   r-   __classcell__r   r   )r   r   r     s   
r   )(r    numpyrf   Zutils.filemanipr   r   r   r   baser   r	   r
   r   r   r   r   r   r   r   r   r   r   r0   r7   r8   r@   rC   rD   rF   rN   rO   rQ   r`   rb   rt   ru   rv   rw   r   r   r   r   r   r   <module>   s2    E7**)&