3
d-                @   s  d Z ddlZddljZddlmZ ddlZddl	m
Z
 ddlmZ ddlmZ dd	lmZmZmZmZmZmZmZ d
dl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 d0d1 d1eZ,G d2d3 d3eZ-G d4d5 d5eZ.G d6d7 d7eZ/G d8d9 d9eZ0G d:d; d;eZ1G d<d= d=eZ2G d>d? d?eZ3G d@dA dAeZ4G dBdC dCeZ5G dDdE dEeZ6G dFdG dGeZ7G dHdI dIeZ8G dJdK dKeZ9G dLdM dMeZ:G dNdO dOeZ;G dPdQ dQeZ<dS )RzThe 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.
    N)warn)load   )LooseVersion)split_filename   )TraitedSpecFileInputMultiPathOutputMultiPath	Undefinedtraits	isdefined   )
FSLCommandFSLCommandInputSpecInfoc               @   s<  e Zd ZedddddddZedddddd	Zejd
ddZejdddZ	ejdddZ
ejdddZejdddZejdddZejddddZejejdddddd Zejd!d"dZejd#d$dZd=Zejd,d-ed.Zejd/d0ed.Zejd1d2ed.Zejd3d4ed.Zed5d6ed.Zejd7ed8d9Zejd:ed;d9Zd<S )>BETInputSpecTzinput file to skull stripz%sr   F)existsdescargstrposition	mandatorycopyfilez#name of output skull stripped imager   )r   r   r   genfile
hash_fileszcreate surface outline imagez-o)r   r   zcreate binary mask imagez-mzcreate skull imagez-sz-nzDon't generate segmented output)r   r   zfractional intensity thresholdz-f %.2fz-g %.2fz;vertical gradient in fractional intensity threshold (-1, 1)z-r %dmmzhead radius)r   unitsr   zcenter of gravity in voxelsz-c %sr   voxels)r   r   minlenmaxlenr   z-tz4apply thresholding to segmented brain image and maskz-ez!generate a vtk mesh brain surface
functionalreduce_biasrobustpaddingremove_eyessurfaces	t2_guidedz;robust brain centre estimation (iterates BET several times)z-R)r   r   xorzIimprove BET if FOV is very small in Z (by temporarily padding end slices)z-Zz2eye & optic nerve cleanup (can be useful in SIENA)z-Sz]run bet2 and then betsurf to get additional skull and scalp surfaces (includes registrations)z-Az_as with creating surfaces, when also feeding in non-brain-extracted T2 (includes registrations)z-A2 %sz-Fzapply to 4D fMRI data)r   r(   r   z-Bzbias field and neck cleanupN)r!   r"   r#   r$   r%   r&   r'   )__name__
__module____qualname__r	   in_fileout_filer   Booloutlinemaskskull	no_outputFloatfracZvertical_gradientIntZradiusListcenter	thresholdmeshZ_xor_inputsr#   r$   r%   r&   r'   r!   r"    r:   r:   B/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/fsl/preprocess.pyr      s|   
      r   c               @   s   e Zd ZeddZeddZeddZeddZeddZeddZ	eddZ
ed	dZed
dZeddZeddZeddZdS )BETOutputSpecz.path/name of skullstripped file (if generated))r   z-path/name of binary brain mask (if generated)z(path/name of outline file (if generated)z)path/name of vtk mesh file (if generated)z(path/name of inskull mask (if generated)z0path/name of inskull mesh outline (if generated)z)path/name of outskull mask (if generated)z1path/name of outskull mesh outline (if generated)z(path/name of outskin mask (if generated)z0path/name of outskin mesh outline (if generated)z&path/name of skull mask (if generated)z&path/name of skull file (if generated)N)r)   r*   r+   r	   r-   	mask_fileoutline_filemeshfileinskull_mask_fileinskull_mesh_fileoutskull_mask_fileoutskull_mesh_fileoutskin_mask_fileoutskin_mesh_fileskull_mask_file
skull_filer:   r:   r:   r;   r<   y   s   










r<   c                   sP   e Zd ZdZdZeZeZ fddZ	 fddZ
dd Zd	d
 Zdd Z  ZS )BETa  FSL BET wrapper for skull stripping

    For complete details, see the `BET Documentation.
    <https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/BET/UserGuide>`_

    Examples
    --------
    >>> from nipype.interfaces import fsl
    >>> btr = fsl.BET()
    >>> btr.inputs.in_file = 'structural.nii'
    >>> btr.inputs.frac = 0.7
    >>> btr.inputs.out_file = 'brain_anat.nii'
    >>> btr.cmdline
    'bet structural.nii brain_anat.nii -f 0.70'
    >>> res = btr.run() # doctest: +SKIP

    Zbetc                s$   t t| j|}|jr | j| |S )N)superrH   _run_interfacestderrZraise_exception)selfruntime)	__class__r:   r;   rJ      s    
zBET._run_interfacec                s2   t t| j|||}|dkr.tj|tj dS |S )Nr,   )start)rI   rH   _format_argoprelpathosgetcwd)rL   namespecvalue	formatted)rN   r:   r;   rP      s    zBET._format_argc             C   sF   | j j}t| rBt| j jrB| j| j jdd}tj|tj dS |S )NZ_brain)suffix)rO   )	inputsr-   r   r,   
_gen_fnamerQ   rR   rS   rT   )rL   r-   r:   r:   r;   _gen_outfilename   s
    zBET._gen_outfilenamec             C   s  | j  j }tjj| j |d< tjj|d }tjj|d }||d}t| j	j
r^| j	j
srt| j	jr| j	jr| jf ddd||d< t| j	jr| j	jst| j	jr| j	jr| jf ddi||d	< t| j	jr| j	jr| jf dd
i||d< t| j	jr| j	jr| jf ddi||d< | jf ddi||d< | jf ddi||d< | jf ddi||d< | jf ddi||d< | jf ddi||d< | jf ddi||d< t| j	jr| j	jr| jf ddi||d< t| j	jr| j	jrt|d< |S )Nr-   )basenamecwdz	_mesh.vtkF)rY   
change_extr?   rY   Z_maskr=   Z_overlayr>   Z_inskull_maskr@   Z_inskull_meshrA   Z_outskull_maskrB   Z_outskull_meshrC   Z_outskin_maskrD   Z_outskin_meshrE   Z_skull_maskrF   Z_skullrG   )output_specgetrS   pathabspathr\   r]   dirnamer   rZ   r9   r&   r[   r0   r"   r/   r1   r2   r   )rL   outputsr]   r^   kwargsr:   r:   r;   _list_outputs   sB    
zBET._list_outputsc             C   s   |dkr| j  S d S )Nr-   )r\   )rL   rU   r:   r:   r;   _gen_filename   s    zBET._gen_filename)r)   r*   r+   __doc___cmdr   
input_specr<   r`   rJ   rP   r\   rg   rh   __classcell__r:   r:   )rN   r;   rH      s   	
.rH   c               @   s|  e Zd ZdZeeddddddGddZed	d
dZej	dddddZ
ejdddZejdddZejdHd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ejd%d&dZedd'd(d)Zeedd*d+d,ddd-Zejd.d/dZejd0d1dZejd2d3dZej	dd4d5d6d$Zej	d7d8d9d:d$Zej	dd;d<d=d$Zej	d7d8d>d?d$Zejd@dAdZeddBdCd)ZejdDdEdZdFS )IFASTInputSpecz'Defines inputs (trait classes) for FASTT)r   Fz6image, or multi-channel set of images, to be segmentedz%sr   )r   r   r   r   r   zbase name of output filesz-o %s)r   r   
   z-n %dznumber of tissue-type classes)lowhighr   r   zoutput estimated bias fieldz-bz,output restored image (bias-corrected image)z-Br   r   z6int specifying type of image: (1 = T1, 2 = T2, 3 = PD)z-t %dz-I %dz8number of main-loop iterations during bias-field removal   (   z(bias field smoothing extent (FWHM) in mmz-l %dr   )ro   rp   r   r   r   g-C6?g?zFinitial segmentation spatial smoothness (during bias field estimation)z-f %.3f)ro   rp   r   r   z4outputs a separate binary image for each tissue typez-gz,<standard2input.mat> initialise using priorsz-a %s)r   r   r   )existzalternative prior imagesz-A %s)r   r   r   r    z(turn off PVE (partial volume estimation)z--nopvezdo not remove bias fieldz-Nzuse priors throughoutz-P2   z0number of segmentation-initialisation iterationsz-W %dg        g      ?z spatial smoothness for mixeltypez-R %.2f   z7number of main-loop iterations after bias-field removalz-O %dzsegmentation spatial smoothnessz-H %.2fzswitch on diagnostic messagesz-vzFilename containing intensitiesz-s %sz#outputs individual probability mapsz-pN)r   r   r   ) r)   r*   r+   ri   r
   r	   in_filesout_basenamer   ZRangenumber_classesr.   output_biasfieldoutput_biascorrectedEnumZimg_typeZ
bias_itersZbias_lowpassZinit_seg_smoothsegmentsZinit_transformZother_priorsno_pveZno_biasZ
use_priorsZsegment_itersZmixel_smoothZiters_afterbiasZhyperverboseZ
manual_segprobability_mapsr:   r:   r:   r;   rm      s   


rm   c               @   sv   e Zd ZdZedddZeeddZeeddZeddZ	ed	dZ
eed
dZeeddZeeddZdS )FASTOutputSpecz"Specify possible outputs from FASTTzFpath/name of binary segmented volume file one val for each class  _seg)r   r   zEpath/name of binary segmented volumes one file for each class  _seg_x)r   zWrestored images (one for each input image) named according to the input images _restorez-path/name of mixeltype volume file _mixeltypez(path/name of partial volume file _pvesegz=path/name of partial volumes files one for each class, _pve_xzEstimated bias field _biasz5filenames, one for each class, for each input, prob_xN)r)   r*   r+   ri   r	   tissue_class_mapr   tissue_class_filesrestored_image	mixeltypepartial_volume_mappartial_volume_files
bias_fieldr   r:   r:   r:   r;   r   L  s"   



r   c                   s4   e Zd ZdZdZeZeZ fddZ	dd Z
  ZS )FASTa  FSL FAST wrapper for segmentation and bias correction

    For complete details, see the `FAST Documentation.
    <https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FAST>`_

    Examples
    --------
    >>> from nipype.interfaces import fsl
    >>> fastr = fsl.FAST()
    >>> fastr.inputs.in_files = 'structural.nii'
    >>> fastr.inputs.out_basename = 'fast_'
    >>> fastr.cmdline
    'fast -o fast_ -S 1 structural.nii'
    >>> out = fastr.run()  # doctest: +SKIP

    fastc                s0   t t| j|||}|dkr,dt||f }|S )Nrw   z-S %d %s)rI   r   rP   len)rL   rU   rV   rW   rX   )rN   r:   r;   rP     s    zFAST._format_argc             C   s  | j  j }t| jjsd}n| jj}i }t| jjrP| jj|d< tj |d< n&| jjd |d< t	|d \|d< }}| j
f ddi||d< | jjrg |d< x2t|D ]&}|d j| j
f dd	| i| qW t| jjr\g |d
< t| jjdkr>x`t| jjD ]0\}}|d
 j| j
f dd|d  i| qW n|d
 j| j
f ddi| | j
f ddi||d< | jjs| j
f ddi||d< g |d< x4t|D ](}|d j| j
f dd| i| qW | jjrZg |d< t| jjdkr<x`t| jjD ]0\}}|d j| j
f dd|d  i| qW n|d j| j
f ddi| | jjrg |d< x4t|D ](}|d j| j
f dd| i| qvW |S )Nr   r]   r^   r   rY   Z_segr   r   z_seg_%dr   z_restore_%dZ_restoreZ
_mixeltyper   Z_pvesegr   r   z_pve_%dr   z_bias_%dZ_biasr   z_prob_%drv   )r`   ra   r   rZ   ry   rx   rS   rT   rw   r   r[   r}   rangeappendr{   r   	enumerater~   rz   r   )rL   re   ZnclassesZ_gen_fname_opts_ivalfr:   r:   r;   rg     s`    
 

 zFAST._list_outputs)r)   r*   r+   ri   rj   rm   rk   r   r`   rP   rg   rl   r:   r:   )rN   r;   r   r  s   	r   c               @   s0  e Zd ZeddddddZeddddddZed	d
dgddddZeddgddddddZedgddgdddZedddZ	e
jdddZe
jddgd d!Ze
jd"d#d$d%d&d'd(dZe
jd)d*d+d,d-d.d/d0d1d	Ze
jd)d*d+d,d-d.d/d2d1d	Ze
jd3d4dZe
jd5d6dZe
jd7d8d9d:dZe
jd;d<d=d>d?d@dZe
jdAdBdCdDZe
jdEdFdGdHdIdZe
jdJdKdZe
jdLdMdZe
jdNdOdZe
jdPdQdZe
jdRdSdTdDZe
jdUdBdVdDZe
j e
jdddWdXdYdZZ!e
j e
jdddWd[d\dZZ"e
j e
jdddWd]d^dZZ#e
jd_d`dZ$e
jdadWdbdDZ%e
jdcdWdddDZ&eddedfdgZ'eddhdidgZ(eddjdkdgZ)e
jdldmdZ*e
jdndodZ+e
jdpdqdZ,e
jdrdsZ-e
jdtdudZ.e
jddvdwdZ/edxdydzd{Z0ed|dyd}d{Z1ed~dydd{Z2eddydd{Z3eddydd{Z4e
jddydd{Z5e
jddydd{Z6e
jdddddydd{Z7e
jddydd{Z8dS )FLIRTInputSpecTz-in %sr   z
input file)r   r   r   r   r   z-ref %sr   zreference filez-out %szregistered output filer,   z%s_flirtr   F)r   r   name_sourcename_templater   r   z-omat %sz%s_flirt.matz)output affine matrix in 4x4 asciii formatr   )r   r   keep_extensionr   r   r   r   save_logz%s_flirt.logz
output log)r   r   requiresr   r   z-init %szinput 4x4 affine matrix)r   r   z	-applyxfmzuapply transformation supplied by in_matrix_file or uses_qform to use the affine matrix stored in the reference headerz-applyisoxfm %f	apply_xfmz+as applyxfm but forces isotropic resampling)r   r(   r   charshortintfloatdoublez-datatype %szforce output data type
mutualinfocorrationormcorrnormmiZleastsqZ	labeldiffZbbrz-cost %szcost functionz-searchcost %sz
-usesqformzinitialize using sform or qformz-displayinitzdisplay initial matrixZ
quaternionZeulerz-anglerep %sz!representation of rotation angles	trilinearZnearestneighboursincsplinez
-interp %sz,final interpolation method used in reslicingz-sincwidth %dr   zfull-width in voxels)r   r   r   ZrectangularZhanningZblackmanz-sincwindow %szsinc windowz-bins %dznumber of histogram binsz-dof %dz&number of transform degrees of freedomz-noresamplezdo not change input samplingz-forcescalingz'force rescaling even for low-res imagesz-minsampling %fr   z(set minimum voxel dimension for samplingz-paddingsize %dz0for applyxfm: interpolates outside image by sizedegreesz-searchrx %sz&search angles along x-axis, in degrees)r   r    r   r   r   z-searchry %sz&search angles along y-axis, in degreesz-searchrz %sz&search angles along z-axis, in degreesz	-nosearchz)set all angular searches to ranges 0 to 0z-coarsesearch %dzcoarse search delta anglez-finesearch %dzfine search delta anglez-schedule %szreplaces default schedule)r   r   r   z-refweight %sz#File for reference weighting volumez-inweight %szFile for input weighting volumez-noclampzdo not use intensity clampingz-noresampblurz#do not use blurring on downsamplingz-2Dz$use 2D rigid body mode - ignores dofzsave to log file)r   z-verbose %dzverbose mode, 0 is leastz-setbackground %fz5use specified background value for points outside FOVz	-wmseg %sz5.0.0z<white matter segmentation volume needed by BBR cost function)r   Zmin_verr   z-wmcoords %sz7white matter boundary coordinates for BBR cost functionz-wmnorms %sz3white matter boundary normals for BBR cost functionz-fieldmap %szLfieldmap image in rads/s - must be already registered to the reference imagez-fieldmapmask %szmask for fieldmap imagez	-pedir %dz?phase encode direction of EPI - 1/2/3=x/y/z & -1/-2/-3=-x/-y/-zz-echospacing %fz,value of EPI echo spacing - units of secondssignedZ
global_absZ	local_absz-bbrtype %szBtype of bbr cost function: signed [default], global_abs, local_absz-bbrslope %fzvalue of bbr slopeN)9r)   r*   r+   r	   r,   	referencer-   out_matrix_fileout_login_matrix_filer   r.   r   r3   Zapply_isoxfmr|   datatypecostZ	cost_func
uses_qformZdisplay_initZ	angle_repinterpr5   Z
sinc_widthZsinc_windowbinsdofZno_resampleZforce_scalingZmin_samplingZpadding_sizer6   Z	searchr_xZ	searchr_yZ	searchr_zZ	no_searchZcoarse_searchZfine_searchscheduleZ
ref_weightZ	in_weightZno_clampZno_resample_blurZrigid2Dr   r   ZbgvalueZwm_segZwmcoordsZwmnormsZfieldmapZfieldmapmaskZpedirZechospacingZbbrtypeZbbrsloper:   r:   r:   r;   r     s^  



r   c               @   s.   e Zd ZedddZedddZeddZdS )FLIRTOutputSpecTz+path/name of registered file (if generated))r   r   z7path/name of calculated affine transform (if generated)z&path/name of output log (if generated))r   N)r)   r*   r+   r	   r-   r   r   r:   r:   r:   r;   r     s   
r   c                   s@   e Zd ZdZdZeZeZdZ	d	 fdd	Z
d
 fdd	Z  ZS )FLIRTa  FSL FLIRT wrapper for coregistration

    For complete details, see the `FLIRT Documentation.
    <https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FLIRT>`_

    To print out the command line help, use:
        fsl.FLIRT().inputs_help()

    Examples
    --------
    >>> from nipype.interfaces import fsl
    >>> from nipype.testing import example_data
    >>> flt = fsl.FLIRT(bins=640, cost_func='mutualinfo')
    >>> flt.inputs.in_file = 'structural.nii'
    >>> flt.inputs.reference = 'mni.nii'
    >>> flt.inputs.output_type = "NIFTI_GZ"
    >>> flt.cmdline # doctest: +ELLIPSIS
    'flirt -in structural.nii -ref mni.nii -out structural_flirt.nii.gz -omat structural_flirt.mat -bins 640 -searchcost mutualinfo'
    >>> res = flt.run() #doctest: +SKIP

    ZflirtFNc          
      sV   t t| j||d}| jjrR| j rRt|jd}|j|j	d  W d Q R X d| _|S )N)rM   needed_outputsa
T)
rI   r   aggregate_outputsrZ   r   _log_writtenopenr   writestdout)rL   rM   r   re   Z	text_file)rN   r:   r;   r     s    

zFLIRT.aggregate_outputsc                sd   |d krg }| j jr&| j j r&d| j _| j jrH| j jp<| j j rHtd|jd tt	| j
|dS )Nr   zIArgument apply_xfm requires in_matrix_file or uses_qform arguments to runr   )skip)rZ   r   r   r   r   r   RuntimeErrorr   rI   r   _parse_inputs)rL   r   )rN   r:   r;   r     s    
zFLIRT._parse_inputs)NN)N)r)   r*   r+   ri   rj   r   rk   r   r`   r   r   r   rl   r:   r:   )rN   r;   r     s   
r   c               @   s   e Zd ZejdddddZdS )ApplyXFMInputSpecTz	-applyxfmzuapply transformation supplied by in_matrix_file or uses_qform to use the affine matrix stored in the reference header)r   r   
usedefaultN)r)   r*   r+   r   r.   r   r:   r:   r:   r;   r     s
   r   c               @   s   e Zd ZdZeZdS )ApplyXFMa}  Currently just a light wrapper around FLIRT,
    with no modifications

    ApplyXFM is used to apply an existing tranform to an image


    Examples
    --------

    >>> import nipype.interfaces.fsl as fsl
    >>> from nipype.testing import example_data
    >>> applyxfm = fsl.preprocess.ApplyXFM()
    >>> applyxfm.inputs.in_file = example_data('structural.nii')
    >>> applyxfm.inputs.in_matrix_file = example_data('trans.mat')
    >>> applyxfm.inputs.out_file = 'newfile.nii'
    >>> applyxfm.inputs.reference = example_data('mni.nii')
    >>> applyxfm.inputs.apply_xfm = True
    >>> result = applyxfm.run() # doctest: +SKIP

    N)r)   r*   r+   ri   r   rk   r:   r:   r:   r;   r     s   r   c            
   @   s<  e Zd ZeddddddZeddddd	Zejd
ddddddddZej	dddZ
ej	dddZej	dddZejdddZejdddZej	dddZej	dd dZedd!d"d#Zejd$d%d&d'd(dZejd)d*dZejd+d,dZejd-d.dZejd/d0dZejd1d2dZejd3d4dZejd5d6dZedd7d8d#Zd9S ):MCFLIRTInputSpecTr   z-in %sztimeseries to motion-correct)r   r   r   r   r   z-out %szfile to writeF)r   r   r   r   r   Zwoodsr   r   r   Zleastsquaresz-cost %szcost function to optimize)r   r   z-bins %dznumber of histogram binsz-dof %dz)degrees of freedom for the transformationz
-refvol %dzvolume to align frames toz-scaling %.2fzscaling factor to usez-smooth %.2fz&smoothing factor for the cost functionz-rotation %dz&scaling factor for rotation tolerancesz
-stages %dz:stages (if 4, perform final search with sinc interpolationz-init %szinital transformation matrix)r   r   r   r   nnr   z	-%s_finalz'interpolation method for transformationz-gdtzrun search on gradient imagesz-edgezrun search on contour imagesz-meanvolzregister to mean volumez-statsz%produce variance and std. dev. imagesz-matszsave transformation matricesz-plotszsave transformation parametersz-rmsabs -rmsrelz save rms displacement parametersz-reffile %sz"target image for motion correctionN)r)   r*   r+   r	   r,   r-   r   r|   r   r5   r   r   Zref_volr3   ZscalingZsmoothZrotationZstagesinitinterpolationr.   Zuse_gradientZuse_contourmean_vol
stats_imgs	save_mats
save_plotssave_rmsref_filer:   r:   r:   r;   r   $  s\   



r   c               @   sl   e Zd ZedddZedddZedddZedddZedddZe	eddd	d
Z
e	edddd
ZdS )MCFLIRTOutputSpecTzmotion-corrected timeseries)r   r   zvariance imagezstandard deviation imagez(mean timeseries image (if mean_vol=True)z text-file with motion parameters)r   ztransformation matrices)r   z-absolute and relative displacement parametersN)r)   r*   r+   r	   r-   variance_imgstd_imgmean_imgpar_filer   mat_file	rms_filesr:   r:   r:   r;   r   _  s   r   c                   sD   e Zd ZdZdZeZeZ fddZ	dd Z
dd Zd	d
 Z  ZS )MCFLIRTa  FSL MCFLIRT wrapper for within-modality motion correction

    For complete details, see the `MCFLIRT Documentation.
    <https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/MCFLIRT>`_

    Examples
    --------
    >>> from nipype.interfaces import fsl
    >>> mcflt = fsl.MCFLIRT()
    >>> mcflt.inputs.in_file = 'functional.nii'
    >>> mcflt.inputs.cost = 'mutualinfo'
    >>> mcflt.inputs.out_file = 'moco.nii'
    >>> mcflt.cmdline
    'mcflirt -in functional.nii -cost mutualinfo -out moco.nii'
    >>> res = mcflt.run()  # doctest: +SKIP

    Zmcflirtc                s2   |dkr|dkrdS |j | S tt| j|||S )Nr   r    )r   rI   r   rP   )rL   rU   rV   rW   )rN   r:   r;   rP     s
    
zMCFLIRT._format_argc       	      C   s   | j  j }| j |d< tjj|d }t| jjr| jjrt	t
j t	dk r| j|d d |d|d< | j|d d |d|d< n0| j|d d|d	|d< | j|d d
|d	|d< t| jjo| jjrt	t
j t	dk r| j|d d |d|d< n| j|d d|d	|d< t| jjr| jjrtjj|d \}}tjj||d }t| jjj\}}}}g |d< x.t|D ]"}|d jtjj|d|  qzW t| jjr| jjr|d d |d< t| jjr| jjr|d }|d |d g|d< |S )Nr-   z6.0.0z_variance.ext)r^   r   z
_sigma.extr   Z	_variance)rY   r^   Z_sigmaz_mean_reg.extr   Z	_mean_regz.matr   zMAT_%04dz.parr   z_abs.rmsz_rel.rmsr   )_outputsra   r\   rS   rb   rd   r   rZ   r   r   r   versionr[   r   r   splitjoinr   r,   shaper   r   r   r   )	rL   re   
output_dirr   filenameZmatpathnameZ
timepointstoutfiler:   r:   r;   rg     s@    	"zMCFLIRT._list_outputsc             C   s   |dkr| j  S d S )Nr-   )r\   )rL   rU   r:   r:   r;   rh     s    zMCFLIRT._gen_filenamec             C   sP   | j j}t|rtjj|}t| rDt| j jrD| j| j jdd}tjj|S )NZ_mcf)rY   )	rZ   r-   r   rS   rb   realpathr,   r[   rc   )rL   r-   r:   r:   r;   r\     s    zMCFLIRT._gen_outfilename)r)   r*   r+   ri   rj   r   rk   r   r`   rP   rg   rh   r\   rl   r:   r:   )rN   r;   r   k  s   8r   c            
   @   s&  e Zd ZedddddZedddddZedddd	Zedd
dd	Zej	eddddddddZ
ejejedddZedddddZejejeddddZejejeddddZejejeddddZejejed d!ddZed"d#dddZejejd$d%eddd&d'dZedd(d)d	Zedd*d+d	Zejd,d-gd.d/Zejd0d1gd2d/Zej	ejd3dd4d5gd6d7d8Zej	ejd3dd9d:gd;d7d8Zejd<d=dZejd>d?dZejd@dAdZejdBdCdZ ej	ej!dDdEd7dFZ"ej	ej!dGdHd7dFZ#ej$ej!ej!ej!dIdJdZ%ej!dKdLdZ&ej	ej!dMdNd7dFZ'ej	ej!dOdPd7dFZ(ejdQdRdSdTdZ)ej	ejdUdVd7dFZ*ejdWdXdZ+ej$ejejdYdZdZ,ejd[d\dZ-ejd]d^d_d`dadbdcdddZ.ej!dedfdZ/ej$ej!ej!ej!dgdhdZ0ejdidjdZ1ejdkdlgdmd/Z2ej	ejd3ddndogdpd7d8Z3ejdqdrdsdtdZ4duS )vFNIRTInputSpecTz--ref=%szname of reference image)r   r   r   r   z--in=%szname of input imagez--aff=%sz(name of file containing affine transform)r   r   r   z--inwarp=%sz0name of file containing initial non-linear warps)r   z
--intin=%sFr   r   z_name of file/files containing initial intensity mapping usually generated by previous fnirt run)r   r   r   r    r   z	--cout=%sz3name of output file with field coefficients or true)r   r   z	--iout=%szname of output image)r   r   r   r   z	--fout=%sz&name of output file with field or true)r   r   r   z	--jout=%szWname of file for writing out the Jacobian of the field (for diagnostic or VBM purposes)z--refout=%szPname of file for writing out intensity modulated --ref (for diagnostic purposes)z--intout=%szEname of files for writing information pertaining to intensity mappingz--logout=%szName of log-fileZT1_2_MNI152_2mmZFA_2_FMRIB58_1mmz--config=%sz5Name of config file specifying command line argumentsz--refmask=%sz)name of file with mask in reference spacez--inmask=%sz+name of file with mask in input image spacez--applyrefmask=0apply_refmaskz,Skip specified refmask if set, default false)r   r(   r   z--applyinmask=0apply_inmaskz+skip specified inmask if set, default falser   z--applyrefmask=%sskip_refmaskzAlist of iterations to use reference mask on (1 to use, 0 to skip),)r   r(   r   sepz--applyinmask=%sskip_inmaskz=list of iterations to use input mask on (1 to use, 0 to skip)z--imprefm=0zAskip implicit masking  based on value in --ref image. Default = 0z
--impinm=0z@skip implicit masking  based on value in --in image. Default = 0z--imprefval=%fz.Value to mask out in --ref image. Default =0.0z--impinval=%fz-Value to mask out in --in image. Default =0.0z
--miter=%sz9Max # of non-linear iterations list, default [5, 5, 5, 5])r   r   r   z--subsamp=%sz/sub-sampling scheme, list, default [4, 2, 1, 1]z--warpres=%d,%d,%dz\(approximate) resolution (in mm) of warp basis in x-, y- and z-direction, default 10, 10, 10z--splineorder=%dz?Order of spline, 2->Qadratic spline, 3->Cubic spline. Default=3z--infwhm=%szPFWHM (in mm) of gaussian smoothing kernel for input volume, default [6, 4, 2, 2]z--reffwhm=%szNFWHM (in mm) of gaussian smoothing kernel for ref volume, default [4, 2, 0, 0]Zmembrane_energyZbending_energyz--regmod=%sz_Model for regularisation of warp-field [membrane_energy bending_energy], default bending_energyz--lambda=%szhWeight of regularisation, default depending on --ssqlambda and --regmod switches. See user documetation.z--ssqlambda=0z=If true, lambda is not weighted by current ssq, default falsez--jacrange=%f,%fz;Allowed range of Jacobian determinants, default 0.01, 100.0z
--refderivzBIf true, ref image is used to calculate derivatives. Default falsenoneZglobal_linearZglobal_non_linearZlocal_linearZglobal_non_linear_with_biasZlocal_non_linearz--intmod=%szModel for intensity-mappingz--intorder=%dz5Order of poynomial for mapping intensities, default 5z--biasres=%d,%d,%dzPResolution (in mm) of bias-field modelling local intensities, default 50, 50, 50z--biaslambda=%fz6Weight of regularisation for bias-field, default 10000z
--estint=0apply_intensity_mappingz-Skip estimate intensity-mapping default falsez--estint=%sskip_intensity_mappingzQList of subsampling levels to apply intensity mapping for (0 to skip, 1 to apply)r   r   z--numprec=%szCPrecision for representing Hessian, double or float. Default doubleN)5r)   r*   r+   r	   r   r,   affine_fileZinwarp_filer   r6   in_intensitymap_fileEitherr.   fieldcoeff_filewarped_file
field_filejacobian_filemodulatedref_fileout_intensitymap_filelog_filer|   config_fileZrefmask_fileZinmask_filer   r   r   r   Zskip_implicit_ref_maskingZskip_implicit_in_maskingr3   Zrefmask_valZ
inmask_valr5   Zmax_nonlin_iterZsubsampling_schemeTupleZwarp_resolutionZspline_orderZin_fwhmZref_fwhmZregularization_modelZregularization_lambdaZskip_lambda_ssqZjacobian_rangeZderive_from_refZintensity_mapping_modelZintensity_mapping_orderZbiasfield_resolutionZbias_regularization_lambdar   r   Zhessian_precisionr:   r:   r:   r;   r     sf  





r   c               @   s^   e Zd ZedddZedddZeddZeddZeddZe	j
ed	d	d
dZeddZdS )FNIRTOutputSpecTzfile with field coefficients)r   r   zwarped imagezfile with warp field)r   z%file containing Jacobian of the fieldz)file containing intensity modulated --refr   z5files containing info pertaining to intensity mapping)r   r    r   zName of log-fileN)r)   r*   r+   r	   r   r   r   r   r   r   r6   r   r   r:   r:   r:   r;   r     s   


r   c                   sd   e Zd ZdZdZeZeZddddddd	d
Z	dd Z
 fddZdd Zdd Zedd Z  ZS )FNIRTa  FSL FNIRT wrapper for non-linear registration

    For complete details, see the `FNIRT Documentation.
    <https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FNIRT>`_

    Examples
    --------
    >>> from nipype.interfaces import fsl
    >>> from nipype.testing import example_data
    >>> fnt = fsl.FNIRT(affine_file=example_data('trans.mat'))
    >>> res = fnt.run(ref_file=example_data('mni.nii', in_file=example_data('structural.nii')) #doctest: +SKIP

    T1 -> Mni153

    >>> from nipype.interfaces import fsl
    >>> fnirt_mprage = fsl.FNIRT()
    >>> fnirt_mprage.inputs.in_fwhm = [8, 4, 2, 2]
    >>> fnirt_mprage.inputs.subsampling_scheme = [4, 2, 1, 1]

    Specify the resolution of the warps

    >>> fnirt_mprage.inputs.warp_resolution = (6, 6, 6)
    >>> res = fnirt_mprage.run(in_file='structural.nii', ref_file='mni.nii', warped_file='warped.nii', fieldcoeff_file='fieldcoeff.nii')#doctest: +SKIP

    We can check the command line and confirm that it's what we expect.

    >>> fnirt_mprage.cmdline  #doctest: +SKIP
    'fnirt --cout=fieldcoeff.nii --in=structural.nii --infwhm=8,4,2,2 --ref=mni.nii --subsamp=4,2,1,1 --warpres=6,6,6 --iout=warped.nii'

    ZfnirtZwarpedfieldZfield_jacobianZ	modulatedZintmapzlog.txtZ	fieldwarp)r   r   r   r   r   r   r   c             C   s  | j  j }xt| jj D ]\}}t| j|}d}|d
kr|jdrJd}t|rdt	j
j|||< q| j| jjd| |d||< nDt|rt|tr|r| j| jjd| |d||< nt	j
j|||< |dkot|| rtj|| }|| d	| g||< qW |S )NTr   r   z.txtFr   )rY   r_   r   z%s.txt)r   r   )r`   ra   listfilemapitemsgetattrrZ   endswithr   rS   rb   rc   r[   r,   
isinstanceboolr   intensitymap_file_basename)rL   re   keyrY   Zinvalr_   r]   r:   r:   r;   rg     s.    

zFNIRT._list_outputsc                s   |dkrX|dkr| j  | }dd |D }tt|dksJtdj|||j|d  S |t| jj kr||j| j  |  S t	t
| j|||S )	Nr   r   c             S   s   g | ]}t j|qS r:   )r   r   ).0vr:   r:   r;   
<listcomp>4  s    z%FNIRT._format_arg.<locals>.<listcomp>r   z$Found different basenames for {}: {}r   )r   r   )rg   r   setAssertionErrorformatr   r   r   keysrI   r   rP   )rL   rU   rV   rW   )rN   r:   r;   rP   0  s    
zFNIRT._format_argc             C   s   |dkr| j  | S d S )Nr   r   )r   r   )rg   )rL   rU   r:   r:   r;   rh   =  s    zFNIRT._gen_filenamec             C   sf   yt |d}W n  tk
r.   td|  Y nX x(t| jj j D ]}|jd|  qDW |j  dS )zWrites out currently set options to specified config file

        XX TODO : need to figure out how the config file is written

        Parameters
        ----------
        configfile : /path/to/configfile
        zw+zunable to create config_file %sz%s
N)	r   IOErrorprintr   rZ   ra   r   r   close)rL   Z
configfileZfiditemr:   r:   r;   write_configB  s    	zFNIRT.write_configc             C   s>   x8t tjj dg D ] }|j|r|dt|  S qW |S )zRemoves valid intensitymap extensions from `f`, returning a basename
        that can refer to both intensitymap files.
        z.txtN)r   r   Zftypesvaluesr   r   )clsr   extr:   r:   r;   r   T  s    
z FNIRT.intensitymap_file_basename)r)   r*   r+   ri   rj   r   rk   r   r`   r   rg   rP   rh   r  classmethodr   rl   r:   r:   )rN   r;   r     s    r   c            	   @   s   e Zd ZeddddddZeddddd	d
ZeddddddZeddddZej	ddgddZ
ej	ddgd4ddZejdddddddd Zej	d!d"d Zejejd#ejd$d%d Zedd&d'dZedd(d)dZedd*d+dZejd,d-d.d/d0d5d1d2Zd3S )6ApplyWarpInputSpecTz--in=%sr   zimage to be warped)r   r   r   r   r   z--out=%sr   zoutput filenameF)r   r   r   r   r   z--ref=%sr   zreference imagez	--warp=%szfile containing warp field)r   r   r   z--absrelwarpz'treat warp field as absolute: x' = w(x))r   r(   r   z--relabswarpz+treat warp field as relative: x' = x + w(x))r   r(   r   r   r   r   r   r   r   z--datatype=%sz5Force output data type [char short int float double].)r   r   z--superz4intermediary supersampling of output, default is offr   z--superlevel=%szTlevel of intermediary supersampling, a for 'automatic' or integer level. Default = 2z--premat=%sz*filename for pre-transform (affine matrix)z--postmat=%sz+filename for post-transform (affine matrix)z	--mask=%sz,filename for mask image (in reference space)r   r   r   r   z--interp=%szinterpolation method)r   r   r   Nrv   )r)   r*   r+   r	   r,   r-   r   r   r   r.   r  r  r|   r   Zsupersampler   r5   
superlevelZprematZpostmatr=   r   r:   r:   r:   r;   r  `  s|   
r  c               @   s   e Zd ZedddZdS )ApplyWarpOutputSpecTzWarped output file)r   r   N)r)   r*   r+   r	   r-   r:   r:   r:   r;   r    s   r  c                   s<   e Zd ZdZdZeZeZ fddZ	dd Z
dd Z  ZS )		ApplyWarpa  FSL's applywarp wrapper to apply the results of a FNIRT registration

    Examples
    --------
    >>> from nipype.interfaces import fsl
    >>> from nipype.testing import example_data
    >>> aw = fsl.ApplyWarp()
    >>> aw.inputs.in_file = example_data('structural.nii')
    >>> aw.inputs.ref_file = example_data('mni.nii')
    >>> aw.inputs.field_file = 'my_coefficients_filed.nii' #doctest: +SKIP
    >>> res = aw.run() #doctest: +SKIP


    Z	applywarpc                s*   |dkr|j t| S tt| j|||S )Nr  )r   strrI   r  rP   )rL   rU   rV   rW   )rN   r:   r;   rP     s    zApplyWarp._format_argc             C   sH   | j  j }t| jjs0| j| jjdd|d< ntjj	| jj|d< |S )NZ_warp)rY   r-   )
r   ra   r   rZ   r-   r[   r,   rS   rb   rc   )rL   re   r:   r:   r;   rg     s
    zApplyWarp._list_outputsc             C   s   |dkr| j  | S d S )Nr-   )rg   )rL   rU   r:   r:   r;   rh     s    zApplyWarp._gen_filename)r)   r*   r+   ri   rj   r  rk   r  r`   rP   rg   rh   rl   r:   r:   )rN   r;   r    s   r  c               @   s   e Zd ZeddddddZeddddd	Zejd
ddZej	dddZ
ejddddddZejdddZeddddZej	dddZeddddZdS )SliceTimerInputSpecTz--in=%sr   zfilename of input timeseries)r   r   r   r   r   z--out=%szfilename of output timeseriesF)r   r   r   r   z--downz!slice indexing from top to bottom)r   r   z--repeat=%fz"Specify TR of data - default is 3sr   r   r   z--direction=%dz=direction of slice acquisition (x=1, y=2, z=3) - default is zz--oddzuse interleaved acquisitionz--tcustom=%szHslice timings, in fractions of TR, range 0:1 (default is 0.5 = no shift))r   r   r   z	--tglobalz>shift in fraction of TR, range 0:1 (default is 0.5 = no shift)z--ocustom=%sz^filename of single-column custom interleave order file (first slice is referred to as 1 not 0)N)r)   r*   r+   r	   r,   r-   r   r.   Z	index_dirr3   Ztime_repetitionr|   Zslice_directionZinterleavedZcustom_timingsZglobal_shiftZcustom_orderr:   r:   r:   r;   r    s@   
r  c               @   s   e Zd ZedddZdS )SliceTimerOutputSpecTzslice time corrected file)r   r   N)r)   r*   r+   r	   slice_time_corrected_filer:   r:   r:   r;   r    s   r  c               @   s,   e Zd ZdZdZeZeZdd Z	dd Z
dS )
SliceTimera\  FSL slicetimer wrapper to perform slice timing correction

    Examples
    --------
    >>> from nipype.interfaces import fsl
    >>> from nipype.testing import example_data
    >>> st = fsl.SliceTimer()
    >>> st.inputs.in_file = example_data('functional.nii')
    >>> st.inputs.interleaved = True
    >>> result = st.run() #doctest: +SKIP

    Z
slicetimerc             C   sB   | j  j }| jj}t|s.| j| jjdd}tjj	||d< |S )NZ_st)rY   r  )
r   ra   rZ   r-   r   r[   r,   rS   rb   rc   )rL   re   r-   r:   r:   r;   rg   "  s    zSliceTimer._list_outputsc             C   s   |dkr| j  d S d S )Nr-   r  )rg   )rL   rU   r:   r:   r;   rh   *  s    zSliceTimer._gen_filenameN)r)   r*   r+   ri   rj   r  rk   r  r`   rg   rh   r:   r:   r:   r;   r    s   r  c               @   s   e Zd ZeddddddZejddddd	Zejdd
ddd	Zej	d
ddddddZ
ej	dddddddZejejeddejddddddZeddddddZdS )SUSANInputSpecTz%sr   zfilename of input timeseries)r   r   r   r   r   z%.10fr   zlbrightness threshold and should be greater than noise level and less than contrast of edges to be preserved.)r   r   r   r   r   z=fwhm of smoothing, in mm, gets converted using sqrt(8*log(2))z%drq   z within-plane (2) or fully 3D (3))r   r   r   r   r      zVwhether to use a local median filter in the cases where single-point noise is detected)r   r      zdetermines whether the smoothing area (USAN) is to be found from secondary images (0, 1 or 2). A negative value for any brightness threshold will auto-set the threshold at 10% of the robust range)r    r   r   r   r   zoutput file nameF)r   r   r   r   r   Nrv   )r)   r*   r+   r	   r,   r   r3   Zbrightness_thresholdfwhmr|   Z	dimensionZ
use_medianr6   r   usansr-   r:   r:   r:   r;   r  0  sV   r  c               @   s   e Zd ZedddZdS )SUSANOutputSpecTzsmoothed output file)r   r   N)r)   r*   r+   r	   smoothed_filer:   r:   r:   r;   r#  n  s   r#  c                   s<   e Zd ZdZdZeZeZ fddZ	dd Z
dd Z  ZS )	SUSANa)  FSL SUSAN wrapper to perform smoothing

    For complete details, see the `SUSAN Documentation.
    <https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/SUSAN>`_

    Examples
    --------

    >>> from nipype.interfaces import fsl
    >>> from nipype.testing import example_data
    >>> anatfile  # doctest: +SKIP
    anatomical.nii  # doctest: +SKIP
    >>> sus = fsl.SUSAN()
    >>> sus.inputs.in_file = example_data('structural.nii')
    >>> sus.inputs.brightness_threshold = 2000.0
    >>> sus.inputs.fwhm = 8.0
    >>> result = sus.run()  # doctest: +SKIP
    Zsusanc                s   |dkr*|j t|tjdtjd   S |dkrv|s:dS tt|g}x"|D ]\}}|j|d| g qNW dj|S t	t
| j|||S )Nr!     r   r"  0z%.10f )r   r   npsqrtlogr  r   extendr   rI   r%  rP   )rL   rU   rV   rW   Zarglistr   Zthresh)rN   r:   r;   rP     s    "
zSUSAN._format_argc             C   sB   | j  j }| jj}t|s.| j| jjdd}tjj	||d< |S )NZ_smooth)rY   r$  )
r   ra   rZ   r-   r   r[   r,   rS   rb   rc   )rL   re   r-   r:   r:   r;   rg     s    zSUSAN._list_outputsc             C   s   |dkr| j  d S d S )Nr-   r$  )rg   )rL   rU   r:   r:   r;   rh     s    zSUSAN._gen_filename)r)   r*   r+   ri   rj   r  rk   r#  r`   rP   rg   rh   rl   r:   r:   )rN   r;   r%  r  s   r%  c            
   @   s  e Zd ZeddddZeddddZeddddZedd	d
dZedddgdgdZedddgdgdZ	e
jddddZe
jdddZe
jdddZe
jdddZe
jdddZe
jdd dZe
jd!d"dZe
jd#d$dZe
jd%d&dZe
jd'd(dZe
jd)d*dZe
jd+d,dZe
jd-d.dZe
jd/d0dZe
jd1d2d3d4d5d6d7d8dZe
jd9d:dZe
jd;d<gd=d>Ze
jd?dgd@d>Z eddAdBdZ!e
jddCdDdZ"e
jddEgdFdGZ#edHdIdZ$e
jdJdKgdLdMZ%e
jddNgdOdGZ&edPdQdZ'e
jddRdSgdTdMZ(dUS )VFUGUEInputSpecTz--in=%szfilename of input volume)r   r   r   z--loadshift=%sz'filename for reading pixel shift volumez--phasemap=%szfilename for input phase imagez--loadfmap=%sz%filename for loading fieldmap (rad/s)z--unwarp=%sz$apply unwarping and save as filenamer   r,   )r   r   r(   r   z	--warp=%sz*apply forward warping and save as filenameunwarped_fileFz*apply forward warping instead of unwarping)r   r   z--dwelltoasym=%.10fz set the dwell to asym time ratio)r   r   z--dwell=%.10fzKset the EPI dwell time per phase-encode line - same as echo spacing - (sec)z--asym=%.10fz0set the fieldmap asymmetric spin echo time (sec)z--medianzapply 2D median filteringz	--despikezapply a 2D de-spiking filterz--nofillz0do not apply gap-filling measure to the fieldmapz
--noextendz5do not apply rigid-body extrapolation to the fieldmapz--smooth2=%.2fz.apply 2D Gaussian smoothing of sigma N (in mm)z--smooth3=%.2fz.apply 3D Gaussian smoothing of sigma N (in mm)z	--poly=%dz#apply polynomial fitting of order Nz--fourier=%dz-apply Fourier (sinusoidal) fitting of order Nz--pavaz$apply monotonic enforcement via PAVAz--despikethreshold=%sz2specify the threshold for de-spiking (default=3.0)xyzzx-zy-zz-z--unwarpdir=%sz*specifies direction of warping (default y)z--phaseconjz)apply phase conjugate method of unwarpingz--icorrshift_in_filezAapply intensity correction to unwarping (pixel shift method only))r   r   r   z--icorronlyzapply intensity correction onlyz	--mask=%szfilename for loading valid maskz
--nokspacez"do not use k-space forward warpingsave_unmasked_shiftzwrite pixel shift volume)r(   r   z--saveshift=%sz&filename for saving pixel shift volumez--unmaskshift
save_shiftz2saves the unmasked shiftmap when using --saveshift)r   r(   r   save_unmasked_fmapzwrite field map volumez--savefmap=%sz$filename for saving fieldmap (rad/s)z--unmaskfmap	save_fmapz1saves the unmasked fieldmap when using --savefmapN))r)   r*   r+   r	   r,   r2  phasemap_in_filefmap_in_filer.  r   r   r.   forward_warpingr3   Zdwell_to_asym_ratioZ
dwell_timeZasym_se_timeZmedian_2dfilterZdespike_2dfilterZno_gap_fillZ	no_extendZsmooth2dZsmooth3dr5   Z
poly_orderZfourier_orderZpavaZdespike_thresholdr|   Zunwarp_directionZphase_conjugateZicorrZ
icorr_onlyr=   Znokspacer4  shift_out_filer3  r6  fmap_out_filer5  r:   r:   r:   r;   r-    s   












r-  c               @   s4   e Zd ZeddZeddZeddZeddZdS )FUGUEOutputSpeczunwarped file)r   zforward warped filezvoxel shift map filezfieldmap fileN)r)   r*   r+   r	   r.  r   r:  r;  r:   r:   r:   r;   r<  %  s   


r<  c                   s.   e Zd ZdZdZeZeZd fdd	Z	  Z
S )FUGUEaA	  FSL FUGUE set of tools for EPI distortion correction

    `FUGUE <http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FUGUE>`_ is, most generally,
    a set of tools for EPI distortion correction.

    Distortions may be corrected for
        1. improving registration with non-distorted images (e.g. structurals),
           or
        2. dealing with motion-dependent changes.

    FUGUE is designed to deal only with the first case -
    improving registration.


    Examples
    --------


    Unwarping an input image (shift map is known):

    >>> from nipype.interfaces.fsl.preprocess import FUGUE
    >>> fugue = FUGUE()
    >>> fugue.inputs.in_file = 'epi.nii'
    >>> fugue.inputs.mask_file = 'epi_mask.nii'
    >>> fugue.inputs.shift_in_file = 'vsm.nii'  # Previously computed with fugue as well
    >>> fugue.inputs.unwarp_direction = 'y'
    >>> fugue.inputs.output_type = "NIFTI_GZ"
    >>> fugue.cmdline # doctest: +ELLIPSIS
    'fugue --in=epi.nii --mask=epi_mask.nii --loadshift=vsm.nii --unwarpdir=y --unwarp=epi_unwarped.nii.gz'
    >>> fugue.run() #doctest: +SKIP


    Warping an input image (shift map is known):

    >>> from nipype.interfaces.fsl.preprocess import FUGUE
    >>> fugue = FUGUE()
    >>> fugue.inputs.in_file = 'epi.nii'
    >>> fugue.inputs.forward_warping = True
    >>> fugue.inputs.mask_file = 'epi_mask.nii'
    >>> fugue.inputs.shift_in_file = 'vsm.nii'  # Previously computed with fugue as well
    >>> fugue.inputs.unwarp_direction = 'y'
    >>> fugue.inputs.output_type = "NIFTI_GZ"
    >>> fugue.cmdline # doctest: +ELLIPSIS
    'fugue --in=epi.nii --mask=epi_mask.nii --loadshift=vsm.nii --unwarpdir=y --warp=epi_warped.nii.gz'
    >>> fugue.run() #doctest: +SKIP


    Computing the vsm (unwrapped phase map is known):

    >>> from nipype.interfaces.fsl.preprocess import FUGUE
    >>> fugue = FUGUE()
    >>> fugue.inputs.phasemap_in_file = 'epi_phasediff.nii'
    >>> fugue.inputs.mask_file = 'epi_mask.nii'
    >>> fugue.inputs.dwell_to_asym_ratio = (0.77e-3 * 3) / 2.46e-3
    >>> fugue.inputs.unwarp_direction = 'y'
    >>> fugue.inputs.save_shift = True
    >>> fugue.inputs.output_type = "NIFTI_GZ"
    >>> fugue.cmdline # doctest: +ELLIPSIS
    'fugue --dwelltoasym=0.9390243902 --mask=epi_mask.nii --phasemap=epi_phasediff.nii --saveshift=epi_phasediff_vsm.nii.gz --unwarpdir=y'
    >>> fugue.run() #doctest: +SKIP


    ZfugueNc       
         s&  |d krg }t | jj}t | jj}t | jj}| rJ| rJ| rJtdt | jjsd|ddg7 }nZ| jjr|dg7 }| jjd}d|_	d|_
d|_n(|dg7 }| jjd}d|_	d|_
d|_t | jjsft | jjo| jj}t | jjo| jj}|p|rX| jjd}d|_|rd|_
n$|r,d	|_
n|r:d
|_
ntd|rPd|_	nd|_	n|dddg7 }t | jjst | jjo| jj}t | jjo| jj}	|s|	r| jjd}d|_|rd
|_
n$|rd	|_
n|rd|_
ntd|	rd|_	nd|_	n|dddg7 }tt| j|dS )NzCEither phasemap_in_file, shift_in_file or fmap_in_file must be set.r.  r   z	%s_warpedr,   z%s_unwarpedr:  r8  r7  r2  z%s_vsm_unmaskedz%s_vsmr4  r3  r;  z%s_fieldmap_unmaskedz%s_fieldmapr6  r5  )r   )r   rZ   r7  r2  r8  r   r,   r9  Ztraitr   r   Zoutput_namer:  r4  r3  r;  r6  r5  rI   r=  r   )
rL   r   Zinput_phaseZ	input_vsmZ
input_fmapZ
trait_specZvsm_save_maskedZvsm_save_unmaskedZfmap_save_maskedZfmap_save_unmasked)rN   r:   r;   r   q  sx    


zFUGUE._parse_inputs)N)r)   r*   r+   ri   rj   r-  rk   r<  r`   r   rl   r:   r:   )rN   r;   r=  ,  s
   ?r=  c               @   s  e Zd ZedddddgddZeddddgd	dZedd
ddgddZedddddZej	dddZ
ejdddZejddgddZejdddgddZejdddZedddd Zej	d!d"dZej	d#d$dZed%d&dd'Zed(d)dd'Zed*d+dd'Zejd,d-dZd.S )/PRELUDEInputSpecTz--complex=%smagnitude_file
phase_filezcomplex phase input volume)r   r   r   r(   r   z--abs=%scomplex_phase_filezfile containing magnitude imagez
--phase=%szraw phase filez--unwrap=%szfile containing unwrapepd phaseF)r   r   r   r   z--numphasesplit=%dz!number of phase partitions to use)r   r   z--labelslicesz-does label processing in 2D (slice at a time)z--sliceslabelprocess2dz+does all processing in 2D (slice at a time))r   r(   r   z	--force3D	process2dz#forces all processing to be full 3Dz--thresh=%.10fzintensity threshold for maskingz	--mask=%szfilename of mask input volume)r   r   r   z
--start=%dz)first image number to process (default 0)z--end=%dz+final image number to process (default Inf)z--savemask=%szsaving the mask volume)r   r   r   z--rawphase=%szsaving the raw phase outputz--labels=%szsaving the area labels outputz--removerampsz$remove phase ramps during unwrappingN)r)   r*   r+   r	   rA  r?  r@  unwrapped_phase_filer   r5   Znum_partitionsr.   rB  rC  Z	process3dr3   r8   r=   rO   endZsavemask_fileZrawphase_fileZ
label_fileZremoverampsr:   r:   r:   r;   r>    sf   




r>  c               @   s   e Zd ZedddZdS )PRELUDEOutputSpecTzunwrapped phase file)r   r   N)r)   r*   r+   r	   rD  r:   r:   r:   r;   rF     s   rF  c                   s<   e Zd ZdZeZeZdZ fddZ	dd Z
dd Z  ZS )	PRELUDEz}FSL prelude wrapper for phase unwrapping

    Examples
    --------

    Please insert examples for use of this command

    Zpreludec                s   t t| jf | td d S )Nz;This has not been fully tested. Please report any failures.)rI   rG  __init__r   )rL   rf   )rN   r:   r;   rH  2  s    zPRELUDE.__init__c             C   sn   | j  j }| jj}t|sZt| jjr<| j| jjdd}nt| jjrZ| j| jjdd}tj	j
||d< |S )NZ
_unwrapped)rY   Z_phase_unwrappedrD  )r   ra   rZ   rD  r   r@  r[   rA  rS   rb   rc   )rL   re   r-   r:   r:   r;   rg   6  s    zPRELUDE._list_outputsc             C   s   |dkr| j  d S d S )NrD  )rg   )rL   rU   r:   r:   r;   rh   C  s    zPRELUDE._gen_filename)r)   r*   r+   ri   r>  rk   rF  r`   rj   rH  rg   rh   rl   r:   r:   )rN   r;   rG  $  s   rG  c            
   @   s   e Zd Zeddd'ddddZedddd(d	d
ddZejddddZejddddZ	ejddddZ
ejddddgdddddZejddddZejejddddd d!Zedd"d#d$d%Zd&S ))FIRSTInputSpecTr   Fz-i %szinput data file)r   r   r   r   r   r   Z	segmentedr   z-o %szoutput data file)r   r   r   r   r   r   z-vzUse verbose logging.)r   r   r   z-bz1Input structural image is already brain-extractedz-dr   autor   r   method_as_numerical_thresholdz-m %srq   zlMethod must be one of auto, fast, none, or it can be entered using the 'method_as_numerical_threshold' input)r(   r   r   r   r   z-m %.4fz[Specify a numerical threshold value or use the 'method' input to choose auto, fast, or nonez-s %sr   r  zRuns only on the specified structures (e.g. L_Hipp, R_HippL_Accu, R_Accu, L_Amyg, R_AmygL_Caud, R_Caud, L_Pall, R_PallL_Puta, R_Puta, L_Thal, R_Thal, BrStem)r   r   r   r   r   r   z-a %szFAffine matrix to use (e.g. img2std.mat) (does not re-run registration))r   r   r   r   Nr  rv   )r)   r*   r+   r	   r,   r-   r   r.   r   Zbrain_extractedZ
no_cleanupr|   methodr3   rK  r6   Strlist_of_specific_structuresr   r:   r:   r:   r;   rI  I  sb   rI  c               @   sH   e Zd ZeeddddZeeddddZedddZedddZd	S )
FIRSTOutputSpecT)r   z-VTK format meshes for each subcortical region)r   z!bvars for each subcortical regionzT3D image file containing the segmented regions as integer values. Uses CMA labelling)r   r   z=4D image file containing a single volume per segmented regionN)	r)   r*   r+   r   r	   vtk_surfacesbvarsoriginal_segmentationssegmentation_filer:   r:   r:   r;   rO    s   rO  c               @   s4   e Zd ZdZdZeZeZdd Z	dd Z
dd Zd	S )
FIRSTag  FSL run_first_all wrapper for segmentation of subcortical volumes

    http://www.fmrib.ox.ac.uk/fsl/first/index.html

    Examples
    --------

    >>> from nipype.interfaces import fsl
    >>> first = fsl.FIRST()
    >>> first.inputs.in_file = 'structural.nii'
    >>> first.inputs.out_file = 'segmented.nii'
    >>> res = first.run() #doctest: +SKIP

    Zrun_first_allc             C   s   | j  j }t| jjr"| jj}n"ddddddddd	d
dddddg}| jd|d< | jd|d< | jd||d< | jd||d< |S )NZL_HippZR_HippZL_AccuZR_AccuZL_AmygZR_AmygZL_CaudZR_CaudZL_PallZR_PallZL_PutaZR_PutaZL_ThalZR_ThalZBrStemrR  rS  rP  rQ  )r`   ra   r   rZ   rN  r[   _gen_mesh_names)rL   re   
structuresr:   r:   r;   rg     s.    
zFIRST._list_outputsc             C   s   t | jj\}}}d}t| jjrJ| jjdkrJd}| jjrJ| jjdkrJd}t| jjrnd| jj }|jdd}|dkrtj	d||f S |d	krtj	d
||f S d S )Nr   r   rJ  z%.4f.r   rR  z%s_all_%s_origsegs.nii.gzrS  z%s_all_%s_firstseg.nii.gz)
r   rZ   r-   r   rL  rN  rK  replacerQ   rc   )rL   r]   rb   outnamer  rL  Zthresr:   r:   r;   r[     s    zFIRST._gen_fnamec             C   s   t | jj\}}}|dkrRt }x,|D ]$}|d | d }|jtj| q&W |S |dkrt }	x,|D ]$}|d | d }
|	jtj|
 qfW |	S d S )NrP  -z
_first.vtkrQ  z_first.bvars)r   rZ   r-   r   r   rQ   rc   )rL   rU   rV  rb   prefixr  ZvtksstructZvtkrQ  Zbvarr:   r:   r;   rU    s    

zFIRST._gen_mesh_namesN)r)   r*   r+   ri   rj   rI  rk   rO  r`   rg   r[   rU  r:   r:   r:   r;   rT    s   rT  )=ri   rS   os.pathrb   rQ   warningsr   numpyr)  Znibabelr   r   r   Zutils.filemanipr   baser   r	   r
   r   r   r   r   r   r   r   r   r<   rH   rm   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r  r#  r%  r-  r<  r=  r>  rF  rG  rI  rO  rT  r:   r:   r:   r;   <module>   sb   
$	\f^&m c6;e  |Q'0 >2  /F%G