3
da                 @   s  d Z ddlZddlZddlZddlZddlmZm	Z	 ddl
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 d-d. d.eZ%G d/d0 d0eZ&G d1d2 d2eZ'G d3d4 d4eZ(G d5d6 d6eZ)G d7d8 d8eZ*G d9d: d:eZ+G d;d< d<eZ,G d=d> d>eZ-dS )?zThe 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 5.0.4.
    N   )split_filenamefname_presuffix   )traitsTraitedSpecInputMultiPathFile	isdefined   )
FSLCommandFSLCommandInputSpecInfoc               @   s|   e Zd ZejddddddZedddddd	Zeddd
ddd	Zej	dddddddZ
ejddddddZeddddZdS )PrepareFieldmapInputSpecZSIEMENSz%sr   zmust be SIEMENST)argstrpositiondesc
usedefaultr   zDPhase difference map, in SIEMENS format range from 0-4096 or 0-8192))existsr   r   	mandatoryr   r   z)Magnitude difference map, brain extractedgGz@z%fzPecho time difference of the fieldmap sequence in ms. (usually 2.46ms in Siemens))r   r   r   r   r   Fz	--nocheckz<do not perform sanity checks for image size/range/dimensions)r   r   r   r      z!output name for prepared fieldmap)r   r   r   N)__name__
__module____qualname__r   Stringscannerr	   in_phaseZin_magnitudeFloatZdelta_TEBoolnocheckout_fieldmap r#   r#   ;/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/fsl/epi.pyr      s:   r   c               @   s   e Zd ZedddZdS )PrepareFieldmapOutputSpecTz!output name for prepared fieldmap)r   r   N)r   r   r   r	   r"   r#   r#   r#   r$   r%   ?   s   r%   c                   sB   e Zd ZdZdZeZeZd
 fdd	Z	dd Z
 fdd	Z  ZS )PrepareFieldmapa  
    Interface for the fsl_prepare_fieldmap script (FSL 5.0)

    Prepares a fieldmap suitable for FEAT from SIEMENS data - saves output in
    rad/s format (e.g. ```fsl_prepare_fieldmap SIEMENS
    images_3_gre_field_mapping images_4_gre_field_mapping fmap_rads 2.65```).


    Examples
    --------

    >>> from nipype.interfaces.fsl import PrepareFieldmap
    >>> prepare = PrepareFieldmap()
    >>> prepare.inputs.in_phase = "phase.nii"
    >>> prepare.inputs.in_magnitude = "magnitude.nii"
    >>> prepare.inputs.output_type = "NIFTI_GZ"
    >>> prepare.cmdline # doctest: +ELLIPSIS
    'fsl_prepare_fieldmap SIEMENS phase.nii magnitude.nii .../phase_fslprepared.nii.gz 2.460000'
    >>> res = prepare.run() # doctest: +SKIP


    Zfsl_prepare_fieldmapNc                sb   |d krg }t | jjs.| j| jjdd| j_t | jj sF| jj rP|dg7 }tt| j|dS )NZ_fslprepared)suffixr!   )skip)	r
   inputsr"   
_gen_fnamer   r!   superr&   _parse_inputs)selfr(   )	__class__r#   r$   r,   `   s    
zPrepareFieldmap._parse_inputsc             C   s   | j  j }| jj|d< |S )Nr"   )output_specgetr)   r"   )r-   outputsr#   r#   r$   _list_outputsn   s    zPrepareFieldmap._list_outputsc                sf   t t| j|}|jdkrb| jj}tj|}tjt	j
|j|j|j}tjj||f}tj|| |S )Nr   )r+   r&   _run_interface
returncoder)   r"   nbloadZNifti1ImagenpzerosshapeZaffineheaderfuncsZconcat_imagessave)r-   runtimeout_fileZimZdumb_imgZout_nii)r.   r#   r$   r3   s   s    

zPrepareFieldmap._run_interface)N)r   r   r   __doc___cmdr   
input_specr%   r/   r,   r2   r3   __classcell__r#   r#   )r.   r$   r&   C   s   r&   c               @   s  e Zd ZedddddZedddgdddZejejd	d
ddddddgdgdddZ	e
ejdgdgdddZeddgddddZedddgdddZejdd dd!dd"Zejd#d$dd%dd"Zejd&d'dd(dd"Zed)ddgd*d+dZed,d-dgd.ddd/Zejd0d1d2Zejd3d4d2Zejd5d6d2Zejd7d8dd9d:Zejd;d<d2Zejd=d>d2Zejd?d@dAdBd2ZejdCdDdEdFd2Zejd?d@dGdHd2Zejd@d?dIdJd2Z ejdKdLd2Z!ejdMdNdOdPd2Z"ejdQdRdSdTd2Z#ejd@d?dUdVd2Z$ejd?d@dWdXd2Z%dYS )ZTOPUPInputSpecTzname of 4D file with imagesz
--imain=%s)r   r   r   r   encoding_directionz*name of text file with PE directions/timesz--datain=%s)r   r   xorr   r   yxzzx-zy-zz-encoding_filereadout_timesz<encoding direction for automatic generation of encoding_file)r   rE   requiresr   r   z;readout times (dwell times by # phase-encode steps minus 1))rK   rE   r   r   zLbase-name of output files (spline coefficients (Hz) and movement parameters)in_filez%s_basez--out=%sF)r   name_sourcename_templater   
hash_filesz	--fout=%sz%s_fieldz"name of image file with field (Hz))r   rO   rM   rN   r   Z	warpfieldz
--dfout=%sz'prefix for the warpfield images (in mm))r   rO   r   r   Zxfmz--rbmout=%sz#prefix for the realignment matricesjacz--jacout=%szprefix for the warpfield imagesz	--iout=%sz%s_correctedz*name of 4D image file with unwarped imagesz--logout=%szname of log-filez%s_topup.log)r   r   rM   rN   Zkeep_extensionrO   z--warpres=%fzT(approximate) resolution (in mm) of warp basis for the different sub-sampling levels)r   r   z--subsamp=%dzsub-sampling schemez	--fwhm=%fz)FWHM (in mm) of gaussian smoothing kernelz	b02b0.cnfz--config=%sz5Name of config file specifying command line arguments)r   r   r   z
--miter=%dzmax # of non-linear iterationsz--lambda=%0.fzQWeight of regularisation, default depending on --ssqlambda and --regmod switches.r   r   z--ssqlambda=%da  Weight lambda by the current value of the ssd. If used (=1), the effective weight of regularisation term becomes higher for the initial iterations, therefore initial steps are a little smoother than they would without weighting. This reduces the risk of finding a local minimum.Zbending_energyZmembrane_energyz--regmod=%sa  Regularisation term implementation. Defaults to bending_energy. Note that the two functions have vastly different scales. The membrane energy is based on the first derivatives and the bending energy on the second derivatives. The second derivatives will typically be much smaller than the first derivatives, so input lambda will have to be larger for bending_energy to yield approximately the same level of regularisation.z--estmov=%dzestimate movements if setz--minmet=%dzFMinimisation method 0=Levenberg-Marquardt, 1=Scaled Conjugate Gradientz--splineorder=%dz4order of spline, 2->Qadratic spline, 3->Cubic splinedoublefloatz--numprec=%sz4Precision for representing Hessian, double or float.splinelinearz--interp=%sz,Image interpolation model, linear or spline.z
--scale=%dz@If set (=1), the images are individually scaled to a common meanz--regrid=%dz:If set (=1), the calculations are done in a different gridN)&r   r   r   r	   rL   rI   r   ListEnumrD   r   r   rJ   out_base	out_fieldStrout_warp_prefixout_mat_prefixout_jac_prefixout_correctedout_logfileZwarp_resIntZsubsampfwhmr   configZmax_iterZ
reg_lambdaZ	ssqlambdaZregmodZestmovZminmetZsplineorderZnumprecinterpZscaleZregridr#   r#   r#   r$   rC      s   
	rC   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j	eddd	dZ
ej	eddd
dZej	eddddZeddZeddZdS )TOPUPOutputSpecTz&file containing the field coefficients)r   r   zmovpar.txt output filez.encoding directions file output for applytopup)r   z"name of image file with field (Hz))r   zwarpfield imageszJacobian imageszrealignment matricesz*name of 4D image file with unwarped imageszname of log-fileN)r   r   r   r	   out_fieldcoef
out_movparout_enc_filerX   r   rU   	out_warpsout_jacsout_matsr]   r^   r#   r#   r#   r$   rc   4  s   


rc   c                   sV   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 fdd	Z  ZS )TOPUPa  
    Interface for FSL topup, a tool for estimating and correcting
    susceptibility induced distortions. See FSL documentation for
    `reference <http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/TOPUP>`_,
    `usage examples
    <http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/topup/ExampleTopupFollowedByApplytopup>`_,
    and `exemplary config files
    <https://github.com/ahheckel/FSL-scripts/blob/master/rsc/fsl/fsl4/topup/b02b0.cnf>`_.

    Examples
    --------

    >>> from nipype.interfaces.fsl import TOPUP
    >>> topup = TOPUP()
    >>> topup.inputs.in_file = "b0_b0rev.nii"
    >>> topup.inputs.encoding_file = "topup_encoding.txt"
    >>> topup.inputs.output_type = "NIFTI_GZ"
    >>> topup.cmdline # doctest: +ELLIPSIS
    'topup --config=b02b0.cnf --datain=topup_encoding.txt --imain=b0_b0rev.nii --out=b0_b0rev_base --iout=b0_b0rev_corrected.nii.gz --fout=b0_b0rev_field.nii.gz --jacout=jac --logout=b0_b0rev_topup.log --rbmout=xfm --dfout=warpfield'
    >>> res = topup.run() # doctest: +SKIP

    Ztopupc                s\   |dkr|j | j  S |dkrHt|\}}}|dkrHtjj|sHtdtt| j	|||S )NrD   rW    z$out_base path must exist if provided)
r   _generate_encfiler   ospathr   
ValueErrorr+   rj   _format_arg)r-   nameZ
trait_specvaluern   ext)r.   r#   r$   rp   _  s    zTOPUP._format_argc                s:  t tj }|d= d }tjjrDtjj\}}}|dkrXd }ntjjd d }j|d|d|d< j|dd	|d
|d< t	j
jjjd }tjjj tjjdj fddtd|d D |d<  fddtd|d D |d< fddtd|d D |d< tjjr6j |d< |S )NrW   rk   r   _base
_fieldcoef)r'   cwdrd   Z_movparz.txt)r'   rs   rv   re   z{prefix}_{i:02d}{ext}c                s   g | ]}j j| d qS ))prefixirs   )r)   rZ   ).0rx   )rs   fmtr-   r#   r$   
<listcomp>~  s   z'TOPUP._list_outputs.<locals>.<listcomp>rg   c                s   g | ]}j j| d qS ))rw   rx   rs   )r)   r\   )ry   rx   )rs   rz   r-   r#   r$   r{     s   rh   c                s   g | ]} j j|d dqS )z.mat)rw   rx   rs   )r)   r[   )ry   rx   )rz   r-   r#   r$   r{     s   ri   rf   r   )r+   rj   r2   r
   r)   rW   r   rL   r*   r5   r6   r9   r   Zoutput_type_to_extoutput_typerm   rn   abspathformatrangerD   _get_encfilename)r-   r1   	base_pathbase_Zn_vols)r.   )rs   rz   r-   r$   r2   i  s0    zTOPUP._list_outputsc             C   s&   t jjt j dt| jjd  }|S )Nz%s_encfile.txtr   )rm   rn   joingetcwdr   r)   rL   )r-   r>   r#   r#   r$   r     s    zTOPUP._get_encfilenamec                s   | j  }| jj}t| jjt|krLt| jjdkr<td|t| jj }g }xRt| jjD ]B\}d jdrxd  fdddD || g }|j| q^W t	j
|t	j|d
d |S )zCGenerate a topup compatible encoding file based on given directionsr   zFReadout time must be a float or match thelength of encoding directionsg      ?-c                s$   g | ]}t |d  d  k  qS )r   )rR   )ry   val)	directionencdirr#   r$   r{     s    z+TOPUP._generate_encfile.<locals>.<listcomp>rG   rF   rH   s   %d %d %d %.8f)rz   g      )rG   rF   rH   )r   r)   rJ   lenrD   ro   	enumerateendswithappendr7   Zsavetxtarray)r-   r>   Z	durationslinesidxliner#   )r   r   r$   rl     s"    
zTOPUP._generate_encfileNc                s   |dkr|S t t| j||S )NrW   )r+   rj   _overload_extension)r-   rr   rq   )r.   r#   r$   r     s    zTOPUP._overload_extension)N)r   r   r   r?   r@   rC   rA   rc   r/   rp   r2   r   rl   r   rB   r#   r#   )r.   r$   rj   @  s   
%rj   c            	   @   s   e Zd ZeedddddddZeddddd	Zejej	d
dddZ
eddddgddZeddgdddZeddg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)dZd*S )+ApplyTOPUPInputSpecT)r   zname of file with imagesz
--imain=%s,)r   r   r   sepz*name of text file with PE directions/timesz--datain=%s)r   r   r   r   z--inindex=%sz9comma separated list of indices corresponding to --datain)r   r   r   z
--topup=%sFin_topup_movparz,topup file containing the field coefficients)r   r   copyfilerK   r   in_topup_fieldcoefztopup movpar.txt file)r   rK   r   r   zoutput (warped) imagein_filesz%s_correctedz--out=%s)r   rM   rN   r   rP   lsrz--method=%sz?use jacobian modulation (jac) or least-squares resampling (lsr))r   r   	trilinearrS   z--interp=%szinterpolation methodcharshortintrR   rQ   z-d=%szforce output data typeN)r   r   r   r   r	   r   rI   r   rU   r_   in_indexr   r   r]   rV   methodrb   datatyper#   r#   r#   r$   r     s^   r   c               @   s   e Zd ZedddZdS )ApplyTOPUPOutputSpecTz*name of 4D image file with unwarped images)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d fdd	Z	 fddZ
  ZS )	
ApplyTOPUPa  
    Interface for FSL topup, a tool for estimating and correcting
    susceptibility induced distortions.
    `General reference
    <http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/topup/ApplytopupUsersGuide>`_
    and `use example
    <http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/topup/ExampleTopupFollowedByApplytopup>`_.


    Examples
    --------

    >>> from nipype.interfaces.fsl import ApplyTOPUP
    >>> applytopup = ApplyTOPUP()
    >>> applytopup.inputs.in_files = ["epi.nii", "epi_rev.nii"]
    >>> applytopup.inputs.encoding_file = "topup_encoding.txt"
    >>> applytopup.inputs.in_topup_fieldcoef = "topup_fieldcoef.nii.gz"
    >>> applytopup.inputs.in_topup_movpar = "topup_movpar.txt"
    >>> applytopup.inputs.output_type = "NIFTI_GZ"
    >>> applytopup.cmdline # doctest: +ELLIPSIS
    'applytopup --datain=topup_encoding.txt --imain=epi.nii,epi_rev.nii --inindex=1,2 --topup=topup --out=epi_corrected.nii.gz'
    >>> res = applytopup.run() # doctest: +SKIP

    Z
applytopupNc                sH   |d krg }t | jjs6ttdt| jjd | j_tt| j	|dS )Nr   )r(   )
r
   r)   r   listr   r   r   r+   r   r,   )r-   r(   )r.   r#   r$   r,     s
    zApplyTOPUP._parse_inputsc                s0   |dkr|j |jdd  S tt| j|||S )Nr   ru   r   )r   splitr+   r   rp   )r-   rq   specrr   )r.   r#   r$   rp     s    zApplyTOPUP._format_arg)N)r   r   r   r?   r@   r   rA   r   r/   r,   rp   rB   r#   r#   )r.   r$   r     s   r   c            	   @   sv  e Zd ZedddddZedddddZedddddZeddd	d
dZedddddZedddddZ	e
jdddddZeddddZedddgddZeddgddZeddddZe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d*d+d,d-Ze
jd*d.d/d0d1Ze
jd2d3dd4d5d&Ze
jd6dd7d8dZe
jd9dd:d;dZe
jd*d<d=d-Ze
jd*d>d?d-Ze
jd@dAdBZe
jdCddDdEd&Z e
jdFdGddHdId&Z!e
jd*dJdKd-Z"e
jdLdMdNgd0dOZ#e
jdPdQdNgd0dOZ$e
jdRdSdTdUdVdNgd0dOZ%e
jd*dWdXdNgd0dOZ&e
jd*dYdZdNgd0dOZ'e
jd[d\d0d1Z(e
jd]d^dd_d`dagd0dOZ)e
jdbdcddgdedOZ*e
jdfdgdhgdedOZ+e
jdidjdhgdedOZ,e
jd3d2dkdldhgdedOZ-e
jddmdndhgdogdedpZ.e
jddqdrdhgdsgdtdpZ/e
jd*dudvdtd1Z0e
jdwdxdygdtdOZ1e
jdzd{dygdtdOZ2e
jd|d}dygdtdOZ3e
jd^ddd~dZ4e
jd*ddd-Z5e
jd*ddZ6e
jd*ddd0dZ7e
jd*ddd0dZ8dS )EddyInputSpecTz
--imain=%sz:File containing all the images to estimate distortions for)r   r   r   r   z	--mask=%szMask to indicate brainz
--index=%szJFile containing indices for all volumes in --imain into --acqp and --topupz	--acqp=%sz&File containing acquisition parametersz
--bvecs=%sz8File containing the b-vectors for all volumes in --imainz
--bvals=%sz7File containing the b-values for all volumes in --imaineddy_correctedz--out=%szBasename for output image)default_valuer   r   r   z--session=%sz:File containing session indices for all volumes in --imain)r   r   r   z
--topup=%sr   z4Topup results file containing the field coefficients)r   r   rK   r   r   zBTopup results file containing the movement parameters (movpar.txt))r   rK   r   z
--field=%sz'Non-topup derived fieldmap scaled in Hzz--field_mat=%szrMatrix specifying the relative positions of the fieldmap, --field, and the first volume of the input file, --imainZ	quadraticrT   Zcubicz--flm=%szFirst level EC model)r   r   r   nonez--slm=%szSecond level EC modelFz--fepz'Fill empty planes in x- or y-directions)r   r   z
--initrandz%Resets rand for when selecting voxelsz5.0.10)r   r   min_verrS   r   z--interp=%sz'Interpolation model for estimation stepi  z--nvoxhp=%sz0# of voxels used to estimate the hyperparametersg      $@z--ff=%sz.Fudge factor for hyperparameter error variancez--dont_sep_offs_movez=Do NOT attempt to separate field offset from subject movementz--dont_peasz.Do NOT perform a post-eddy alignment of shellsz;FWHM for conditioning filter when estimating the parametersz	--fwhm=%s)r   r      z
--niter=%szNumber of iterationsrP   r   z--resamp=%sz0Final resampling method (jacobian/least squares)z--repolz!Detect and replace outlier slicesz	--ol_nstdz'Number of std off to qualify as outlierrepol)r   r   rK   r   z	--ol_nvoxz=Min # of voxels in a slice for inclusion in outlier detectionswZgwZbothz	--ol_typez?Type of outliers, slicewise (sw), groupwise (gw) or both (both)z--ol_posz3Consider both positive and negative outliers if setz--ol_sqrz:Consider outliers among sums-of-squared differences if setz--mb=%szMulti-band factorr   r   z--mb_offs=%dzEMulti-band offset (-1 if bottom slice removed, 1 if top slice removedmultiband_factorz--mporder=%sz$Order of slice-to-vol movement modeluse_cudaz5.0.11z--s2v_niter=%dz%Number of iterations for slice-to-volmporderz--s2v_lambda=%dzGRegularisation weight for slice-to-vol movement (reasonable range 1-10)z--s2v_interp=%sz4Slice-to-vol interpolation model for estimation stepz--slspec=%sz?Name of text file completely specifying slice/group acquisitionjson)r   r   r   rK   rE   r   z	--json=%sz;Name of .json text file with information about slice timingslice_orderz6.0.1z!--estimate_move_by_susceptibilityz?Estimate how susceptibility field changes with subject movementz--mbs_niter=%sz'Number of iterations for MBS estimationestimate_move_by_susceptibilityz--mbs_lambda=%sz.Weighting of regularisation for MBS estimationz--mbs_ksp=%smmz%Knot-spacing for MBS field estimationzNumber of openmp threads to use)r   Znohashr   z--data_is_shelledzSOverride internal check to ensure that date are acquired on a set of b-value shellszRun eddy using cuda gpu)r   zOutput CNR-Mapsz
--cnr_maps)r   r   r   zOutput Residualsz--residualsNr   )9r   r   r   r	   rL   Zin_maskr   Zin_acqpZin_bvecZin_bvalr   rY   rW   sessionr   r   fieldZ	field_matrV   ZflmZslmr    ZfepZinitrandrb   r_   Znvoxhpr   Zfudge_factorZdont_sep_offs_moveZ	dont_peasr`   Zniterr   r   Zoutlier_nstdZoutlier_nvoxZoutlier_typeZoutlier_posZoutlier_sqrr   Zmultiband_offsetr   Zslice2vol_niterZslice2vol_lambdaZslice2vol_interpr   r   r   Z	mbs_niterZ
mbs_lambdaZmbs_kspnum_threadsZ
is_shelledr   cnr_maps	residualsr#   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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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dddZedddZedddZdS )EddyOutputSpecTz24D image file containing all the corrected volumes)r   r   zGText file with parameters defining the field and movement for each scanz0File containing rotated b-values for all volumesz.Summary of the 'total movement' in each volumez[Summary of the 'total movement' in each volume disregarding translation in the PE directionzText file containing rigid body movement parameters between the different shells as estimated by a post-hoc mutual information based registrationzText file containing translation along the PE-direction between the different shells as estimated by a post-hoc mutual information based registrationzMatrix where rows represent volumes and columns represent slices. "0" indicates that scan-slice is not an outlier and "1" indicates that it iszMatrix where rows represent volumes and columns represent slices. Values indicate number of standard deviations off the mean difference between observation and prediction iszMatrix where rows represent volumes and columns represent slices. Values indicate number of standard deivations off the square root of the mean squared difference between observation and prediction iszLText file with a plain language report on what outlier slices eddy has foundz4D image file not corrected for susceptibility or eddy-current distortions or subject movement but with outlier slices replacedzRText file containing translations (mm) and rotations (radians) for each excitationz#path/name of file with the cnr_mapsz$path/name of file with the residualsN)r   r   r   r	   r]   out_parameterout_rotated_bvecsout_movement_rmsout_restricted_movement_rmsout_shell_alignment_parameters#out_shell_pe_translation_parametersout_outlier_mapout_outlier_n_stdev_mapout_outlier_n_sqr_stdev_mapout_outlier_reportout_outlier_freeout_movement_over_timeout_cnr_mapsout_residualsr#   r#   r#   r$   r   7  sR   


r   c                   s`   e Zd ZdZdZeZeZdZ	 fddZ
dd Zdd	 Z fd
dZ fddZdd Z  ZS )EddyaQ  
    Interface for FSL eddy, a tool for estimating and correcting eddy
    currents induced distortions. `User guide
    <https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/eddy/UsersGuide>`__ and
    `more info regarding acqp file
    <https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/eddy/Faq#How_do_I_know_what_to_put_into_my_--acqp_file.3F>`_.

    Examples
    --------

    >>> from nipype.interfaces.fsl import Eddy

    Running eddy on a CPU using OpenMP:
    >>> eddy = Eddy()
    >>> eddy.inputs.in_file = 'epi.nii'
    >>> eddy.inputs.in_mask  = 'epi_mask.nii'
    >>> eddy.inputs.in_index = 'epi_index.txt'
    >>> eddy.inputs.in_acqp  = 'epi_acqp.txt'
    >>> eddy.inputs.in_bvec  = 'bvecs.scheme'
    >>> eddy.inputs.in_bval  = 'bvals.scheme'
    >>> eddy.cmdline          # doctest: +ELLIPSIS
    'eddy_openmp --flm=quadratic --ff=10.0 --acqp=epi_acqp.txt --bvals=bvals.scheme --bvecs=bvecs.scheme --imain=epi.nii --index=epi_index.txt --mask=epi_mask.nii --interp=spline --resamp=jac --niter=5 --nvoxhp=1000 --out=.../eddy_corrected --slm=none'

    Running eddy on an Nvidia GPU using cuda:
    >>> eddy.inputs.use_cuda = True
    >>> eddy.cmdline # doctest: +ELLIPSIS
    'eddy_cuda --flm=quadratic --ff=10.0 --acqp=epi_acqp.txt --bvals=bvals.scheme --bvecs=bvecs.scheme --imain=epi.nii --index=epi_index.txt --mask=epi_mask.nii --interp=spline --resamp=jac --niter=5 --nvoxhp=1000 --out=.../eddy_corrected --slm=none'

    Running eddy with slice-to-volume motion correction:
    >>> eddy.inputs.mporder = 6
    >>> eddy.inputs.slice2vol_niter = 5
    >>> eddy.inputs.slice2vol_lambda = 1
    >>> eddy.inputs.slice2vol_interp = 'trilinear'
    >>> eddy.inputs.slice_order = 'epi_slspec.txt'
    >>> eddy.cmdline          # doctest: +ELLIPSIS
    'eddy_cuda --flm=quadratic --ff=10.0 --acqp=epi_acqp.txt --bvals=bvals.scheme --bvecs=bvecs.scheme --imain=epi.nii --index=epi_index.txt --mask=epi_mask.nii --interp=spline --resamp=jac --mporder=6 --niter=5 --nvoxhp=1000 --out=.../eddy_corrected --s2v_interp=trilinear --s2v_lambda=1 --s2v_niter=5 --slspec=epi_slspec.txt --slm=none'
    >>> res = eddy.run()     # doctest: +SKIP

    eddy_openmpr   c                sj   t t| jf | | jj| jd t| jjs:| j| j_n| j  | jj| j	d t| jj
rf| j	  d S )Nr   r   )r+   r   __init__r)   Zon_trait_change_num_threads_updater
   r   _num_threads	_use_cudar   )r-   r)   )r.   r#   r$   r     s    zEddy.__init__c             C   sF   | j j| _t| j js.d| j jkrB| j jd= nt| j j| j jd< d S )NZOMP_NUM_THREADS)r)   r   r   r
   environstr)r-   r#   r#   r$   r     s
    
zEddy._num_threads_updatec             C   s   | j jrdnd| _d S )NZ	eddy_cudar   )r)   r   r@   )r-   r#   r#   r$   r     s    zEddy._use_cudac                s^   t jdd}| j}t|dk|dkt jjt jj|d| frDd| _tt| j	|}|| _|S )NFSLDIRrk   r   binZeddy)
rm   getenvr@   allrn   r   r   r+   r   r3   )r-   r=   r   cmd)r.   r#   r$   r3     s    zEddy._run_interfacec                sd   |dkr|j |jdd  S |dkr6|j t|dd S |dkrP|j tjj| S tt| j|||S )Nr   ru   r   r   F)Zuse_extrW   )	r   r   r   rm   rn   r}   r+   r   rp   )r-   rq   r   rr   )r.   r#   r$   rp     s    zEddy._format_argc             C   s  | j  j }tjjd| jj |d< tjjd| jj |d< tjjd| jj }tjjd| jj }tjjd| jj }tjjd| jj }tjjd	| jj }tjjd
| jj }tjjd| jj }tjjd| jj }	tjjd| jj }
t| jjr2| jjr2tjjd| jj }tjj	|r2||d< t| jj
rx| jj
dkrxtjjd| jj }tjj	|rx||d< t| jjr| jjrtjjd| jj }tjj	|r||d< t| jjr| jjrtjjd| jj }tjj	|r||d< tjj	|r||d< tjj	|r(||d< tjj	|r>||d< tjj	|rT||d< tjj	|rj||d< tjj	|r||d< tjj	|r||d< tjj	|	r|	|d< tjj	|
r|
|d< |S ) Nz	%s.nii.gzr]   z%s.eddy_parametersr   z%s.eddy_rotated_bvecsz%s.eddy_movement_rmsz%s.eddy_restricted_movement_rmsz,%s.eddy_post_eddy_shell_alignment_parametersz1%s.eddy_post_eddy_shell_PE_translation_parametersz%s.eddy_outlier_mapz%s.eddy_outlier_n_stdev_mapz%s.eddy_outlier_n_sqr_stdev_mapz%s.eddy_outlier_reportz%s.eddy_outlier_free_datar   r   z%s.eddy_movement_over_timer   z%s.eddy_cnr_maps.nii.gzr   z%s.eddy_residuals.nii.gzr   r   r   r   r   r   r   r   r   r   )r/   r0   rm   rn   r}   r)   rW   r
   r   r   r   r   r   )r-   r1   r   r   r   r   r   r   r   r   r   r   r   r   r   r#   r#   r$   r2     sx    zEddy._list_outputs)r   r   r   r?   r@   r   rA   r   r/   r   r   r   r   r3   rp   r2   rB   r#   r#   )r.   r$   r     s   4	r   c               @   sZ   e Zd ZedddddZeddddZeddd	d
ZejdddZ	ej
ddddddZdS )SigLossInputSpecTz-i %szb0 fieldmap file)r   r   r   r   z-s %sz output signal loss estimate file)r   r   genfilez-m %szbrain mask file)r   r   r   z--te=%fzecho time in seconds)r   r   rG   rF   rH   z-d %szslicing directionN)r   r   r   r	   rL   r>   	mask_filer   r   Z	echo_timerV   Zslice_directionr#   r#   r#   r$   r   B  s   r   c               @   s   e Zd ZedddZdS )SigLossOuputSpecTzsignal loss estimate file)r   r   N)r   r   r   r	   r>   r#   r#   r#   r$   r   O  s   r   c               @   s,   e Zd ZdZeZeZdZdd Z	dd Z
dS )SigLossa  
    Estimates signal loss from a field map (in rad/s)

    Examples
    --------

    >>> from nipype.interfaces.fsl import SigLoss
    >>> sigloss = SigLoss()
    >>> sigloss.inputs.in_file = "phase.nii"
    >>> sigloss.inputs.echo_time = 0.03
    >>> sigloss.inputs.output_type = "NIFTI_GZ"
    >>> sigloss.cmdline # doctest: +ELLIPSIS
    'sigloss --te=0.030000 -i phase.nii -s .../phase_sigloss.nii.gz'
    >>> res = sigloss.run() # doctest: +SKIP


    Zsiglossc             C   sL   | j  j }| jj|d< t|d  rHt| jjrH| j| jjdd|d< |S )Nr>   Z_sigloss)r'   )r/   r0   r)   r>   r
   rL   r*   )r-   r1   r#   r#   r$   r2   j  s    zSigLoss._list_outputsc             C   s   |dkr| j  d S d S )Nr>   )r2   )r-   rq   r#   r#   r$   _gen_filenames  s    zSigLoss._gen_filenameN)r   r   r   r?   r   rA   r   r/   r@   r2   r   r#   r#   r#   r$   r   S  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d0ddZejdddd1d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jdddZejdddd d!d"d#d$dZedd%d&dZejd'd(d)dZejdd*dd+d,Zd-S )2EpiRegInputSpecTz--epi=%sr   z	EPI image)r   r   r   r   r   z--t1=%sr   zwholehead T1 imagez--t1brain=%sr   zbrain extracted T1 imageZ
epi2structzoutput base namez--out=%sr   )r   r   r   r   z	--fmap=%szfieldmap image (in rad/s))r   r   r   z--fmapmag=%sz$fieldmap magnitude image - wholeheadz--fmapmagbrain=%sz*fieldmap magnitude image - brain extractedz
--wmseg=%szjwhite matter segmentation of T1 image, has to be named                  like the t1brain and end on _wmsegz--echospacing=%fzeEffective EPI echo spacing                                 (sometimes called dwell time) - in seconds)r   r   rG   rF   rH   z-xz-yz-zz
--pedir=%sz.phase encoding direction, dir = x/y/z/-x/-y/-zz--weight=%szweighting image (in T1 space)Fz--nofmapregzbdo not perform registration of fmap to T1                         (use if fmap already registered)z	--nocleanz"do not clean up intermediate files)r   r   r   Nr   r   )r   r   r   r	   ZepiZt1_headZt1_brainr   r   rW   fmapZfmapmagZfmapmagbrainwmsegr   ZechospacingrV   ZpedirZweight_imager    
no_fmapregno_cleanr#   r#   r#   r$   r   y  sl   r   c               @   s   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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dddZedddZedddZedddZdS )EpiRegOutputSpecTz#unwarped and coregistered epi input)r   r   z'unwarped and coregistered single volumez&rigid fieldmap-to-structural transformzrigid fieldmap-to-epi transformzfieldmap in epi spacezfieldmap in structural spacez,fieldmap magnitude image in structural spacez!rigid structural-to-epi transformz!rigid epi-to-structural transformzshiftmap in epi spacezOwarpfield to unwarp epi and transform into                     structural spacez+white matter segmentation used in flirt bbrz+white matter, gray matter, csf segmentationz$white matter edges for visualizationN)r   r   r   r	   r>   out_1volfmap2str_matfmap2epi_matfmap_epifmap_strfmapmag_strepi2str_invepi2str_matshiftmapfullwarpr   segwmedger#   r#   r#   r$   r     s    r   c               @   s$   e Zd ZdZdZeZeZdd Z	dS )EpiRega  

    Runs FSL epi_reg script for simultaneous coregistration and fieldmap
    unwarping.

    Examples
    --------

    >>> from nipype.interfaces.fsl import EpiReg
    >>> epireg = EpiReg()
    >>> epireg.inputs.epi='epi.nii'
    >>> epireg.inputs.t1_head='T1.nii'
    >>> epireg.inputs.t1_brain='T1_brain.nii'
    >>> epireg.inputs.out_base='epi2struct'
    >>> epireg.inputs.fmap='fieldmap_phase_fslprepared.nii'
    >>> epireg.inputs.fmapmag='fieldmap_mag.nii'
    >>> epireg.inputs.fmapmagbrain='fieldmap_mag_brain.nii'
    >>> epireg.inputs.echospacing=0.00067
    >>> epireg.inputs.pedir='y'
    >>> epireg.cmdline # doctest: +ELLIPSIS
    'epi_reg --echospacing=0.000670 --fmap=fieldmap_phase_fslprepared.nii --fmapmag=fieldmap_mag.nii --fmapmagbrain=fieldmap_mag_brain.nii --noclean --pedir=y --epi=epi.nii --t1=T1.nii --t1brain=T1_brain.nii --out=epi2struct'
    >>> epireg.run() # doctest: +SKIP

    Zepi_regc             C   s  | j  j }tjjtj | jjd |d< t| jj	o<| jj	 oJt| jj
r\tjjtj | jjd |d< tjjtj | jjd |d< tjjtj | jjd |d< tjjtj | jjd	 |d
< tjjtj | jjd |d< tjjtj | jjd |d< tjjtj | jjd |d< tjjtj | jjd |d< tjjtj | jjd |d< t| jjstjjtj | jjd |d< tjjtj | jjd |d< tjjtj | jjd |d< tjjtj | jjd |d< |S )Nz.nii.gzr>   z_1vol.nii.gzr   z_fieldmap2str.matr   z_fieldmaprads2epi.matr   z_fieldmaprads2epi.nii.gzr   z_fieldmaprads2str.nii.gzr   z_fieldmap2str.nii.gzr   z_fieldmaprads2epi_shift.nii.gzr   z_warp.nii.gzr   z_inv.matr   z_fast_wmedge.nii.gzr   z_fast_wmseg.nii.gzr   z_fast_seg.nii.gzr   z.matr   )r/   r0   rm   rn   r   r   r)   rW   r
   r   r   r   )r-   r1   r#   r#   r$   r2     sB    zEpiReg._list_outputsN)
r   r   r   r?   r@   r   rA   r   r/   r2   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dd	d
dZe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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Zejddd%d&dZejd'd(d)Zd*S )+EPIDeWarpInputSpecTzMagnitude filez--mag %sr   )r   r   r   r   r   z.Phase file assumed to be scaled from 0 to 4095z--dph %s)r   r   r   r   z example func volume (or use epi)z--exf %s)r   r   r   zEPI volume to unwarpz--epi %sgGz@zdifference in B0 field map TEsz--tediff %s)r   r   r   g(\?zEPI echo spacingz--esp %s)r   r   r   r   z
--sigma %szJ2D spatial gaussing smoothing                        stdev (default = 2mm))r   r   r   zvoxel shift mapz--vsm %s)r   r   r   zdewarped example func volumez
--exfdw %s)r   r   r   zdewarped epi volumeFz
--epidw %stmpdirz--tmpdir %sz
no cleanupz--nocleanupcleanupz	--cleanup)r   r   N)r   r   r   r	   Zmag_fileZdph_fileexf_fileepi_filer   r   ZtediffZespr_   sigmar   vsmexfdwepidwr   r    Z	nocleanupr   r#   r#   r#   r$   r   /  sF   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 )EPIDeWarpOutputSpeczunwarped epi file)r   zvoxel shift mapz"dewarped functional volume examplez#Mask from example functional volumeN)r   r   r   r	   unwarped_filevsm_filer   exf_maskr#   r#   r#   r$   r   _  s   


r   c                   sH   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  ZS )	EPIDeWarpa1  
    Wraps the unwarping script `epidewarp.fsl
    <http://surfer.nmr.mgh.harvard.edu/fswiki/epidewarp.fsl>`_.

    .. warning:: deprecated in FSL, please use
      :func:`niflow.nipype1.workflows.dmri.preprocess.epi.sdc_fmb` instead.

    Examples
    --------

    >>> from nipype.interfaces.fsl import EPIDeWarp
    >>> dewarp = EPIDeWarp()
    >>> dewarp.inputs.epi_file = "functional.nii"
    >>> dewarp.inputs.mag_file = "magnitude.nii"
    >>> dewarp.inputs.dph_file = "phase.nii"
    >>> dewarp.inputs.output_type = "NIFTI_GZ"
    >>> dewarp.cmdline # doctest: +ELLIPSIS
    'epidewarp.fsl --mag magnitude.nii --dph phase.nii --epi functional.nii --esp 0.58 --exfdw .../exfdw.nii.gz --nocleanup --sigma 2 --tediff 2.46 --tmpdir .../temp --vsm .../vsm.nii.gz'
    >>> res = dewarp.run() # doctest: +SKIP


    zepidewarp.fslc                s   t jdt tt| jf |S )NzSDeprecated: Please use niflow.nipype1.workflows.dmri.preprocess.epi.sdc_fmb instead)warningswarnDeprecationWarningr+   r   r   )r-   r)   )r.   r#   r$   r     s    zEPIDeWarp.__init__c                s$   t t| j|}|jr | j| |S )N)r+   r   r3   stderrraise_exception)r-   r=   )r.   r#   r$   r3     s    
zEPIDeWarp._run_interfacec             C   s   |dkr0t | jjr&| j| jjddS | jdS |dkrVt | jjrV| j| jjddS |dkrh| jdS |dkrtjjtj dS d S )	Nr   Z_exfdw)r'   r   Z_epidwr   r   temp)	r
   r)   r   r*   r   rm   rn   r   r   )r-   rq   r#   r#   r$   r     s    

zEPIDeWarp._gen_filenamec             C   s   | j  j }t| jjs(| jd|d< n| jj|d< t| jjrht| jjrZ| jj|d< n| jd|d< t| jjs| jd|d< n| j	| jj|d< t| jj
s| j	| jddd|d	< n| j	| jj
dd|d	< |S )
Nr   r   r   r   r   r   Zmaskexf)rv   basenamer   )r/   r0   r
   r)   r   r   r   r   r   r*   r   )r-   r1   r#   r#   r$   r2     s"    zEPIDeWarp._list_outputs)r   r   r   r?   r@   r   rA   r   r/   r   r3   r   r2   rB   r#   r#   )r.   r$   r   f  s   
r   c               @   sJ   e Zd ZeddddddZeddddgd	d
dZejdddddddZdS )EddyCorrectInputSpecTz4D input filez%sr   )r   r   r   r   r   z4D output filer   rL   z%s_edcr   )r   r   r   rM   rN   Zoutput_namez%dr   zreference number)r   r   r   r   r   N)	r   r   r   r	   rL   r>   r   r_   Zref_numr#   r#   r#   r$   r    s    r  c               @   s   e Zd ZedddZdS )EddyCorrectOutputSpecTz*path/name of 4D eddy corrected output file)r   r   N)r   r   r   r	   r   r#   r#   r#   r$   r    s   r  c                   s8   e Zd ZdZdZeZeZ fddZ	 fddZ
  ZS )EddyCorrecta  

    .. warning:: Deprecated in FSL. Please use
      :class:`nipype.interfaces.fsl.epi.Eddy` instead

    Example
    -------

    >>> from nipype.interfaces.fsl import EddyCorrect
    >>> eddyc = EddyCorrect(in_file='diffusion.nii',
    ...                     out_file="diffusion_edc.nii", ref_num=0)
    >>> eddyc.cmdline
    'eddy_correct diffusion.nii diffusion_edc.nii 0'

    Zeddy_correctc                s   t jdt tt| jf |S )Nz=Deprecated: Please use nipype.interfaces.fsl.epi.Eddy instead)r   r   r  r+   r  r   )r-   r)   )r.   r#   r$   r     s    zEddyCorrect.__init__c                s$   t t| j|}|jr | j| |S )N)r+   r  r3   r  r  )r-   r=   )r.   r#   r$   r3     s    
zEddyCorrect._run_interface)r   r   r   r?   r@   r  rA   r  r/   r   r3   rB   r#   r#   )r.   r$   r    s   r  c               @   s   e Zd ZejddddddZeddddd	Zeddd
dd	Zeddddd	Z	eddddd	Z
eddddZejddgdddZeddddZeddddZejdddZdS ) EddyQuadInputSpecr   Tz%szTBasename (including path) for EDDY output files, i.e., corrected images and QC filesr   )r   r   r   r   z--eddyIdx %szCFile containing indices for all volumes into acquisition parameters)r   r   r   r   z--eddyParams %sz&File containing acquisition parametersz	--mask %szBinary mask filez
--bvals %szb-values filez
--bvecs %szJb-vectors file - only used when <base_name>.eddy_residuals file is present)r   r   r   z%s.qc	base_namez--output-dir %sz-Output directory - default = '<base_name>.qc')rN   rM   r   r   z
--field %szTOPUP estimated field (in Hz)z--slspec %sz,Text file specifying slice/group acquisitionz	--verbosezDisplay debug messages)r   r   N)r   r   r   r   rY   r
  r	   Zidx_fileZ
param_filer   Z	bval_fileZ	bvec_file
output_dirr   Z
slice_specr    verboser#   r#   r#   r$   r	    sF   r	  c               @   s   e Zd ZedddZedddZejeddddZejeddddZ	ejeddd	dZ
edd
dZedddZedddZdS )EddyQuadOutputSpecTzASingle subject database containing quality metrics and data info.)r   r   zSingle subject QC report.)r   zWImage showing mid-sagittal, -coronal and -axial slices of each averaged b-shell volume.)r   zImage showing mid-sagittal, -coronal and -axial slices of each averaged pe-direction b0 volume. Generated when using the -f option.zyImage showing mid-sagittal, -coronal and -axial slices of each b-shell CNR volume. Generated when CNR maps are available.zyImage showing mid-sagittal, -coronal and -axial slices of the voxel displacement map. Generated when using the -f option.zqText file containing the volume-wise mask-averaged squared residuals. Generated when residual maps are available.a  Text file containing a list of clean volumes, based on the eddy squared residuals. To generate a version of the pre-processed dataset without outlier volumes, use: `fslselectvols -i <eddy_corrected_data> -o eddy_corrected_data_clean --vols=vols_no_outliers.txt`N)r   r   r   r	   qc_jsonqc_pdfr   rU   	avg_b_pngavg_b0_pe_pngcnr_pngvdm_pngr   clean_volumesr#   r#   r#   r$   r  0  s,   r  c               @   s$   e Zd ZdZdZeZeZdd Z	dS )EddyQuada*  
    Interface for FSL eddy_quad, a tool for generating single subject reports
    and storing the quality assessment indices for each subject.
    `User guide <https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/eddyqc/UsersGuide>`__

    Examples
    --------

    >>> from nipype.interfaces.fsl import EddyQuad
    >>> quad = EddyQuad()
    >>> quad.inputs.base_name  = 'eddy_corrected'
    >>> quad.inputs.idx_file   = 'epi_index.txt'
    >>> quad.inputs.param_file = 'epi_acqp.txt'
    >>> quad.inputs.mask_file  = 'epi_mask.nii'
    >>> quad.inputs.bval_file  = 'bvals.scheme'
    >>> quad.inputs.bvec_file  = 'bvecs.scheme'
    >>> quad.inputs.output_dir = 'eddy_corrected.qc'
    >>> quad.inputs.field      = 'fieldmap_phase_fslprepared.nii'
    >>> quad.inputs.verbose    = True
    >>> quad.cmdline
    'eddy_quad eddy_corrected --bvals bvals.scheme --bvecs bvecs.scheme --field fieldmap_phase_fslprepared.nii --eddyIdx epi_index.txt --mask epi_mask.nii --output-dir eddy_corrected.qc --eddyParams epi_acqp.txt --verbose'
    >>> res = quad.run() # doctest: +SKIP

    Z	eddy_quadc             C   sN  ddl m } | j j }t| jjsBtjjtjj	| jj
d }ntjj| jj}tjj|d|d< tjj|d|d< t|tjj|d|d	< t| jjrt|tjj|d
|d< x|d D ]}|d	 j| qW tjj|d|d< t|tjj|d|d< tjj|d}tjj|r&||d< tjj|d}tjj|rJ||d< |S )Nr   )globz.qczqc.jsonr  zqc.pdfr  z
avg_b*.pngr  zavg_b0_pe*.pngr  zvdm.pngr  zcnr*.pngr  zeddy_msr.txtr   zvols_no_outliers.txtr  )r  r/   r0   r
   r)   r  rm   rn   r}   r  r
  r   sortedr   removeisfile)r-   r  r1   Zout_dirfnamer   r  r#   r#   r$   r2     s,    zEddyQuad._list_outputsN)
r   r   r   r?   r@   r	  rA   r  r/   r2   r#   r#   r#   r$   r  h  s
   r  ).r?   rm   numpyr7   Znibabelr5   r   Zutils.filemanipr   r   r   r   r   r   r	   r
   r   r   r   r   r%   r&   rC   rc   rj   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$   <module>   sL   ,= 5t;0  L @&IX0W#48