3
d_                @   sP  d Z ddlZddljZddlmZmZmZm	Z	 ddl
mZmZmZmZmZmZmZmZmZmZ ddl
mZmZmZmZmZmZmZmZ dd	lmZ ejd
Z G dd deZ!G dd deZ"G dd deZ#G dd deZ$G dd deZ%G dd deZ&G dd deZ'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Z0G d+d, d,eZ1G d-d. d.eZ2G d/d0 d0eZ3G d1d2 d2eZ4G d3d4 d4eZ5G d5d6 d6eZ6G d7d8 d8eZ7G d9d: d:e!Z8G d;d< d<eZ9G d=d> d>eZ:G d?d@ d@eZ;G dAdB dBeZ<G dCdD dDeZ=G dEdF dFeZ>G dGdH dHe!Z?G dIdJ dJeZ@G dKdL dLeZAG dMdN dNeZBG dOdP dPeZCG dQdR dReZDG dSdT dTeZEG dUdV dVeZFG dWdX dXeZGG dYdZ dZe!ZHG d[d\ d\eZIG d]d^ d^eZJG d_d` d`eZKG dadb dbeZLG dcdd ddeZMG dedf dfeZNG dgdh dheZOG didj djeZPG dkdl dleZQG dmdn dneZRG dodp dpeZSG dqdr dreZTG dsdt dteZUG dudv dveZVG dwdx dxeZWG dydz dzeZXG d{d| d|eZYG d}d~ d~eZZG dd deZ[G dd deZ\G dd deZ]G dd deZ^G dd deZ_G dd deZ`G dd deZaG dd deZbG dd deZcG dd deZdG dd deZeG dd deZfG dd deZgG dd deZhG dd deZiG dd deZjG dd deZkG dd deZlG dd deZmG dd deZnG dd deZoG dd deZpG dd deZqG dd deZrG dd deZsG dd deZtG dd deZuG dd deZvG dd deZwG dd deZxG dd deZyG dd dewZzG dd deyZ{dS )zAFNI preprocessing interfaces.    N   )	load_json	save_jsonsplit_filenamefname_presuffix   )
CommandLineInputSpecCommandLineTraitedSpectraits	isdefinedFileInputMultiPath	UndefinedStrInputMultiObject   )AFNICommandBaseAFNICommandAFNICommandInputSpecAFNICommandOutputSpecAFNIPythonCommandInputSpecAFNIPythonCommandInfono_afni)loggingznipype.interfacec               @   sV   e Zd ZdZe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dS )CentralityInputSpecz;Common input spec class for all centrality-related commandszmask file to mask input dataz-mask %sT)descargstrexistsz5threshold to exclude connections where corr <= threshz
-thresh %f)r   r    z
-polort %dz-Clip off low-intensity regions in the datasetz	-autoclipz,Mask the dataset to target brain-only voxelsz	-automaskN)__name__
__module____qualname____doc__r   maskr   FloatZthreshIntpolortBoolautoclipautomask r,   r,   C/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/afni/preprocess.pyr   '   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jejdd	ej	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ddZej	d(dddZej	d d!dd"d#d$Zej	d d!dd%d&d$Zd'S ))AlignEpiAnatPyInputSpeczEPI dataset to alignz-epi %sTF)r   r   	mandatoryr   copyfilezname of structural datasetz-anat %sr   )lowmeanmedianmaxzLthe epi base used in alignmentshould be one of (0/mean/median/max/subbrick#)z-epi_base %s)r   r/   r   z)align anatomical to EPI dataset (default)z	-anat2epi)r   r   zalign EPI to anatomical datasetz	-epi2anatz!save skull-stripped (not aligned)z-save_skullstripZ_alzfappend suffix to the original anat/epi dataset to usein the resulting dataset names (default is "_al")z
-suffix %s)r   
usedefaultr   3dSkullStrip
3dAutomaskNonezOmethod to mask brain in EPI datashould be one of[3dSkullStrip]/3dAutomask/None)z-epi_strip %sonoffz_do volume registration on EPI dataset before alignmentshould be 'on' or 'off', defaults to 'on'z
-volreg %s)r5   r   r   zYdo time shifting of EPI dataset before alignmentshould be 'on' or 'off', defaults to 'on'z
-tshift %sN)r6   r7   r8   )r!   r"   r#   r   in_fileanatr   EitherRangeEnumZepi_baser)   anat2epiepi2anatsave_skullstripr   suffixZ	epi_stripvolregtshiftr,   r,   r,   r-   r.   8   sX   


r.   c               @   sp   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dS )AlignEpiAnatPyOutputSpecz3A version of the anatomy that is aligned to the EPI)r   z3A version of the EPI dataset aligned to the anatomyz;A version of the EPI dataset aligned to a standard templatez"matrix to align anatomy to the EPIzmatrix to align EPI to anatomyzmatrix to volume register EPIz2matrix to volume register and align epi to anatomyzMmatrix to volume register and align epito anatomy and put into standard spacezumotion parameters from EPI time-seriesregistration (tsh included in name if slicetiming correction is also included).z#skull-stripped (not aligned) volumeN)r!   r"   r#   r   anat_al_origepi_al_origZepi_tlrc_alanat_al_mat
epi_al_matepi_vr_al_matepi_reg_al_matZepi_al_tlrc_matepi_vr_motion
skullstripr,   r,   r,   r-   rF   u   s   





rF   c               @   s$   e Zd ZdZdZeZeZdd Z	dS )AlignEpiAnatPya
	  Align EPI to anatomical datasets or vice versa.

    This Python script computes the alignment between two datasets, typically
    an EPI and an anatomical structural dataset, and applies the resulting
    transformation to one or the other to bring them into alignment.

    This script computes the transforms needed to align EPI and
    anatomical datasets using a cost function designed for this purpose. The
    script combines multiple transformations, thereby minimizing the amount of
    interpolation applied to the data.

    Basic Usage::

        align_epi_anat.py -anat anat+orig -epi epi+orig -epi_base 5

    The user must provide :abbr:`EPI (echo-planar imaging)` and anatomical datasets
    and specify the EPI sub-brick to use as a base in the alignment.

    Internally, the script always aligns the anatomical to the EPI dataset,
    and the resulting transformation is saved to a 1D file.
    As a user option, the inverse of this transformation may be applied to the
    EPI dataset in order to align it to the anatomical data instead.

    This program generates several kinds of output in the form of datasets
    and transformation matrices which can be applied to other datasets if
    needed. Time-series volume registration, oblique data transformations and
    Talairach (standard template) transformations will be combined as needed
    and requested (with options to turn on and off each of the steps) in
    order to create the aligned datasets.

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> al_ea = afni.AlignEpiAnatPy()
    >>> al_ea.inputs.anat = "structural.nii"
    >>> al_ea.inputs.in_file = "functional.nii"
    >>> al_ea.inputs.epi_base = 0
    >>> al_ea.inputs.epi_strip = '3dAutomask'
    >>> al_ea.inputs.volreg = 'off'
    >>> al_ea.inputs.tshift = 'off'
    >>> al_ea.inputs.save_skullstrip = True
    >>> al_ea.cmdline # doctest: +ELLIPSIS
    'python2 ...align_epi_anat.py -anat structural.nii -epi_base 0 -epi_strip 3dAutomask -epi functional.nii -save_skullstrip -suffix _al -tshift off -volreg off'
    >>> res = allineate.run()  # doctest: +SKIP

    See Also
    --------
    For complete details, see the `align_epi_anat.py documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/align_epi_anat.py.html>`__.

    zalign_epi_anat.pyc             C   s  | j  j }| j| jj}| j| jj}d|krHdj|jdd d }d|krhdj|jdd d }| jj}|dkr~d}n
t	j
|}d}| jj}| jjr| j||d |d|d	< | j||d
 |d|d< | jjr| j||d |d|d< | j||d
 |d|d< | jjdkrv| j|d| d
 |d|d< | jjdkrT| j|d|d|d< n"| jjdkrv| j|d|d|d< | jjdkr| jjr| j|d| d
 |d|d< | jjr| j|d|d|_|S )N+r    r   AFNIz.HEADz.1Dz+orig)rC   extrG   z
_mat.aff12rI   rH   rJ   r9   Z_vrrK   Ztsh_vr_motionrM   r:   Z	vr_motionZ_regrL   Z_nsrS   z_ns+orig)output_specget
_gen_fnameinputsr<   r;   joinsplit
outputtyper   output_type_to_extrC   r@   rA   rD   rE   rB   rN   )selfoutputsZanat_prefixZ
epi_prefixrZ   rR   ZmatextrC   r,   r,   r-   _list_outputs   sN    


zAlignEpiAnatPy._list_outputsN)
r!   r"   r#   r$   _cmdr.   
input_specrF   rT   r^   r,   r,   r,   r-   rO      s
   4rO   c               @   s  e Zd ZeddddddZeddddZed	d
ddddgdZeddddgdZeddddgdZeddddgdZ	eddddgdZ
ejdd d!Zed"d#dd%ddd&gdZd'd(d)d*d+d,d-d.d/d0d1d2d3d4gZejed5d6d7Zd8d9d:d;d<gZejed=d d>d?d7Zejed@dAd7ZejdBdCd7ZejdDdEd7ZejdFdGd7ZejdHdId7ZejdJdKd7Zejeje dLdMd7ZejdNdOd7ZejdPdQd7ZejdRdSd7Z ejdTdUd7Z!ejdVdWd7Z"ejdXdYd7Z#e$dZd[d7Z%e$d\d]d7Z&ejd^d_d7Z'ejd`dad7Z(ejdbdcd7Z)eddddedfdgdhZ*ej+eddiej dddjd7Z,edkdldgdZ-eddmdndZ.ejdodpd7Z/ejdqdrdsdtdudvd7Z0ejdwdxd7Z1ejdydzd7Z2ejed{d|d7Z3ejd}d~d7Z4ejddd7Z5ejddd7Z6ejddd7Z7ejddd7Z8eddddZ9ejddd7Z:dd:d;ddddddg	Z;eje;ddd7Z<ddddddgZ=ejeje= ddd7Z>ejeje= ddd7Z?ejddd7Z@ejddd7ZAd=S )AllineateInputSpeczinput file to 3dAllineatez
-source %sTF)r   r   r/   r   r0   z-base %sz{file to be used as reference, the first volume will be used if not given the reference will be the first volume of in_file.)r   r   r   zoutput file from 3dAllineatez
-prefix %sz%s_allineater;   allcostx)r   r   name_templatename_source
hash_filesxorz-1Dparam_save %sz/Save the warp parameters in ASCII (.1D) format.in_param_file)r   r   rf   z-1Dparam_apply %sz^Read warp parameters from file and apply them to the source dataset, and produce a new datasetout_param_file)r   r   r   rf   z-1Dmatrix_save %sz/Save the transformation matrix for each volume.	in_matrixzmatrix to align input filez-1Dmatrix_apply %sr   
out_matrix)r   r   positionrf   z*overwrite output file if it already existsz
-overwrite)r   r   zCompute and print ALL available cost functionals for the un-warped inputsAND THEN QUIT. If you use this option none of the other expected outputs will be producedz-allcostx |& tee %sr   out_fileout_weight_fileZleastsqZlsZ
mutualinfomiZcorratio_mulZcrMZnorm_mutualinfonmiZ	hellingerhelZcorratio_addZcrAZcorratio_unsZcrUz-cost %szUDefines the 'cost' function that defines the matching between the source and the base)r   r   ZnearestneighbourlinearcubicquinticZwsinc5Nz
-interp %sz3Defines interpolation method to use during matchingz	-final %sz>Defines interpolation method used to create the output datasetz
-nmatch %dz5Use at most n scattered points to match the datasets.z-nopadz*Do not use zero-padding on the base image.z-zclipzHReplace negative values in the input datasets (source & base) with zero.z-conv %fz1Convergence test in millimeters (default 0.05mm).z-usetempztemporary file usez	-check %sa%  After cost functional optimization is done, start at the final parameters and RE-optimize using this new cost functions. If the results are too different, a warning message will be printed. However, the final parameters from the original optimization will be used to create the output dataset.z-onepasszUse only the refining pass -- do not try a coarse resolution pass first.  Useful if you know that only small amounts of image alignment are needed.z-twopasszxUse a two pass alignment strategy for all volumes, searching for a large rotation+shift and then refining the alignment.z-twoblur %fz1Set the blurring radius for the first pass in mm.z	-twofirstzUse -twopass on the first image to be registered, and then on all subsequent images from the source dataset, use results from the first image's coarse pass to start the fine pass.z-twobest %da  In the coarse pass, use the best 'bb' set of initialpoints to search for the starting point for the finepass.  If bb==0, then no search is made for the beststarting point, and the identity transformation isused as the starting point.  [Default=5; min=0 max=11]z-fineblur %fa  Set the blurring radius to use in the fine resolution pass to 'x' mm.  A small amount (1-2 mm?) of blurring at the fine step may help with convergence, if there is some problem, especially if the base volume is very noisy. [Default == 0 mm = no blurring at the final alignment pass]z-cmass%sz9Use the center-of-mass calculation to bracket the shifts.z-autoweight%sz^Compute a weight function using the 3dAutomask algorithm plus some blurring of the base image.z-automask+%dz7Compute a mask function, set a value for dilation or 0.z-autoboxzYExpand the -automask function to enclose a rectangular box that holds the irregular mask.z-nomaskziDon't compute the autoweight/mask; if -weight is not also used, then every voxel will be counted equally.z
-weight %sz1.0.0weightzSet the weighting for each voxel in the base dataset; larger weights mean that voxel count more in the cost function. Must be defined on the same grid as the base dataset)r   r   
deprecatednew_namer   )r   zSet the weighting for each voxel in the base dataset; larger weights mean that voxel count more in the cost function. If an image file is given, the volume must be defined on the same grid as the base datasetz-wtprefix %sz,Write the weight volume to disk as a datasetz-source_mask %szmask the input datasetz-source_automask+%dz9Automatically mask the source dataset with dilation or 0.Z
shift_onlyZshift_rotateZshift_rotate_scaleZaffine_generalz-warp %szSet the warp type.z-warpfreezez8Freeze the non-rigid body parameters after first volume.z-replacebasez[If the source has more than one volume, then after the first volume is aligned to the base.z-replacemeth %sz\After first volume is aligned, switch method for later volumes. For use with '-replacebase'.z-EPIzTreat the source dataset as being composed of warped EPI slices, and the base as comprising anatomically 'true' images.  Only phase-encoding direction image shearing and scaling will be allowed with this option.z
-maxrot %fz$Maximum allowed rotation in degrees.z
-maxshf %fzMaximum allowed shift in mm.z
-maxscl %fzMaximum allowed scaling factor.z
-maxshr %fz Maximum allowed shearing factor.z
-master %sz7Write the output dataset on the same grid as this file.z-newgrid %fz<Write the output dataset using isotropic grid spacing in mm.ZbilinearhepticZnonicZpoly3Zpoly5Zpoly7Zpoly9z	-nwarp %sz:Experimental nonlinear warping: bilinear or legendre poly.XYZIJKz-nwarp_fixmot%s...zTo fix motion along directions.z-nwarp_fixdep%s...z3To fix non-linear warp dependency along directions.z-verbz#Print out verbose progress reports.z-quietz)Don't print out verbose progress reports.rS   rS   )Br!   r"   r#   r   r;   	referencerl   rh   rg   rj   ri   r   r)   	overwriterb   Z_cost_funcsr?   ZcostZ_interp_funcsinterpolationZfinal_interpolationr'   ZnmatchZno_padZzclipr&   ZconvergenceZusetempListcheckZone_passZtwo_passZtwo_blurZ	two_firstZtwo_bestZ	fine_blurr   Zcenter_of_massZ
autoweightr+   ZautoboxZnomaskZweight_filer=   rt   rm   Zsource_maskZsource_automaskZ	warp_typeZ
warpfreezeZreplacebaseZreplacemethZepiZmaxrotZmaxshfZmaxsclZmaxshrZmasternewgridZ_nwarp_typesZnwarpZ_dirsZnwarp_fixmotZnwarp_fixdepverbosequietr,   r,   r,   r-   ra      s  














ra   c               @   sF   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Zd	S )
AllineateOutputSpecTzoutput image file name)r   r   zmatrix to align input filezwarp parameterszweight volumezICompute and print ALL available cost functionals for the un-warped inputs)r   N)	r!   r"   r#   r   rl   rj   rh   rm   rb   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	  Z
S )	Allineatea  Program to align one dataset (the 'source') to a base dataset

    For complete details, see the `3dAllineate Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dAllineate.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> allineate = afni.Allineate()
    >>> allineate.inputs.in_file = 'functional.nii'
    >>> allineate.inputs.out_file = 'functional_allineate.nii'
    >>> allineate.inputs.in_matrix = 'cmatrix.mat'
    >>> allineate.cmdline
    '3dAllineate -source functional.nii -prefix functional_allineate.nii -1Dmatrix_apply cmatrix.mat'
    >>> res = allineate.run()  # doctest: +SKIP

    >>> allineate = afni.Allineate()
    >>> allineate.inputs.in_file = 'functional.nii'
    >>> allineate.inputs.reference = 'structural.nii'
    >>> allineate.inputs.allcostx = 'out.allcostX.txt'
    >>> allineate.cmdline
    '3dAllineate -source functional.nii -base structural.nii -allcostx |& tee out.allcostX.txt'
    >>> res = allineate.run()  # doctest: +SKIP

    >>> allineate = afni.Allineate()
    >>> allineate.inputs.in_file = 'functional.nii'
    >>> allineate.inputs.reference = 'structural.nii'
    >>> allineate.inputs.nwarp_fixmot = ['X', 'Y']
    >>> allineate.cmdline
    '3dAllineate -source functional.nii -nwarp_fixmotX -nwarp_fixmotY -prefix functional_allineate -base structural.nii'
    >>> res = allineate.run()  # doctest: +SKIP
    Z3dAllineatec                s   t t| j }| jjr(tj| jj|d< | jjrvt| jjd }|j	 dkrd| j
| jjdd|d< ntj| jj|d< | jjrt| jjd }|j	 dkr| j
| jjdd|d	< ntj| jj|d	< | jjrtjj| jj|d
< |S )Nrm   r   .1d.1Dz	.aff12.1D)rC   rj   z	.param.1Drh   ZallcostXrS   )r   r   rS   )r   r   )superr   r^   rW   rm   opabspathrj   r   lowerrV   rh   rb   ospath)r\   r]   rR   )	__class__r,   r-   r^   J  s$    zAllineate._list_outputs)r!   r"   r#   r$   r_   ra   r`   r   rT   r^   __classcell__r,   r,   )r   r-   r   $  s
    r   c               @   s~   e Zd Zedddd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gdZeddddgdZedddddZdS )AutoTcorrelateInputSpecz+timeseries x space (volume or surface) filez%sr   TF)r   r   rk   r/   r   r0   z;Remove polynomical trend of order m or -1 for no detrendingz
-polort %d)r   r   zeta^2 similarityz-eta2zmask of voxelsz-mask %s)r   r   r   zuse mask only on targets voxelsz-mask_only_targetsmask_source)r   r   rf   zmask for source voxelsz-mask_source %smask_only_targets)r   r   r   rf   z%s_similarity_matrix.1Dzoutput image file namez
-prefix %sr;   )rc   r   r   rd   NrS   )r!   r"   r#   r   r;   r   r'   r(   r)   Zeta2r%   r   r   rl   r,   r,   r,   r-   r   g  s4   

r   c               @   s&   e Zd ZdZeZeZdZdddZ	dS )AutoTcorrelateat  Computes the correlation coefficient between the time series of each
    pair of voxels in the input dataset, and stores the output into a
    new anatomical bucket dataset [scaled to shorts to save memory space].

    For complete details, see the `3dAutoTcorrelate Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dAutoTcorrelate.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> corr = afni.AutoTcorrelate()
    >>> corr.inputs.in_file = 'functional.nii'
    >>> corr.inputs.polort = -1
    >>> corr.inputs.eta2 = True
    >>> corr.inputs.mask = 'mask.nii'
    >>> corr.inputs.mask_only_targets = True
    >>> corr.cmdline  # doctest: +ELLIPSIS
    '3dAutoTcorrelate -eta2 -mask mask.nii -mask_only_targets -prefix functional_similarity_matrix.1D -polort -1 functional.nii'
    >>> res = corr.run()  # doctest: +SKIP
    Z3dAutoTcorrelateNc             C   s4   t |\}}}|j dkr"|d }tjj||| S )N.1d.1D.nii.gz.nii)r   r   r   r   )r   r   r   r   rX   )r\   valuenamer   baserR   r,   r,   r-   _overload_extension  s    z"AutoTcorrelate._overload_extension)N)
r!   r"   r#   r$   r   r`   r   rT   r_   r   r,   r,   r,   r-   r     s
   r   c               @   sj   e Zd Zedd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Z	ej
dddZej
dddZdS )AutomaskInputSpeczinput file to 3dAutomaskz%sr   TF)r   r   rk   r/   r   r0   z%s_maskzoutput image file namez
-prefix %sr;   )rc   r   r   rd   z	%s_maskedzoutput file from 3dAutomaskz-apply_prefix %szpsets the clip level fraction (must be 0.1-0.9). A small value will tend to make the mask larger [default = 0.5].z
-clfrac %s)r   r   zdilate the mask outwardsz
-dilate %szerode the mask inwardsz	-erode %sNrS   )r!   r"   r#   r   r;   rl   
brain_filer   r&   Zclfracr'   ZdilateZeroder,   r,   r,   r-   r     s,   r   c               @   s$   e Zd ZedddZedddZdS )AutomaskOutputSpecz	mask fileT)r   r   zbrain file (skull stripped)N)r!   r"   r#   r   rl   r   r,   r,   r,   r-   r     s   r   c               @   s   e Zd ZdZdZeZeZdS )Automaska  Create a brain-only mask of the image using AFNI 3dAutomask command

    For complete details, see the `3dAutomask Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dAutomask.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> automask = afni.Automask()
    >>> automask.inputs.in_file = 'functional.nii'
    >>> automask.inputs.dilate = 1
    >>> automask.inputs.outputtype = 'NIFTI'
    >>> automask.cmdline  # doctest: +ELLIPSIS
    '3dAutomask -apply_prefix functional_masked.nii -dilate 1 -prefix functional_mask.nii functional.nii'
    >>> res = automask.run()  # doctest: +SKIP

    r7   N)	r!   r"   r#   r$   r_   r   r`   r   rT   r,   r,   r,   r-   r     s   r   c               @   sV   e Zd Zejdeejj ddZ	e
ddddddZejd	dd
dZejdddZdS )AutoTLRCInputSpecrQ   zAFNI output filetype)r   zkOriginal anatomical volume (+orig).The skull is removed by this scriptunless instructed otherwise (-no_ss).z	-input %sTF)r   r   r/   r   r0   ap  Reference anatomical volume.
Usually this volume is in some standard space like
TLRC or MNI space and with afni dataset view of
(+tlrc).
Preferably, this reference volume should have had
the skull removed but that is not mandatory.
AFNI's distribution contains several templates.
For a longer list, use "whereami -show_templates"
TT_N27+tlrc --> Single subject, skull stripped volume.
This volume is also known as
N27_SurfVol_NoSkull+tlrc elsewhere in
AFNI and SUMA land.
(www.loni.ucla.edu, www.bic.mni.mcgill.ca)
This template has a full set of FreeSurfer
(surfer.nmr.mgh.harvard.edu)
surface models that can be used in SUMA.
For details, see Talairach-related link:
https://afni.nimh.nih.gov/afni/suma
TT_icbm452+tlrc --> Average volume of 452 normal brains.
Skull Stripped. (www.loni.ucla.edu)
TT_avg152T1+tlrc --> Average volume of 152 normal brains.
Skull Stripped.(www.bic.mni.mcgill.ca)
TT_EPI+tlrc --> EPI template from spm2, masked as TT_avg152T1
TT_avg152 and TT_EPI volume sources are from
SPM's distribution. (www.fil.ion.ucl.ac.uk/spm/)
If you do not specify a path for the template, the script
will attempt to locate the template AFNI's binaries directory.
NOTE: These datasets have been slightly modified from
their original size to match the standard TLRC
dimensions (Jean Talairach and Pierre Tournoux
Co-Planar Stereotaxic Atlas of the Human Brain
Thieme Medical Publishers, New York, 1988).
That was done for internal consistency in AFNI.
You may use the original form of these
volumes if you choose but your TLRC coordinates
will not be consistent with AFNI's TLRC database
(San Antonio Talairach Daemon database), for example.z-base %s)r   r/   r   a  Do not strip skull of input data set
(because skull has already been removed
or because template still has the skull)
NOTE: The ``-no_ss`` option is not all that optional.
Here is a table of when you should and should not use ``-no_ss``

  +------------------+------------+---------------+
  | Dataset          | Template                   |
  +==================+============+===============+
  |                  | w/ skull   | wo/ skull     |
  +------------------+------------+---------------+
  | WITH skull       | ``-no_ss`` | xxx           |
  +------------------+------------+---------------+
  | WITHOUT skull    | No Cigar   | ``-no_ss``    |
  +------------------+------------+---------------+

Template means: Your template of choice
Dset. means: Your anatomical dataset
``-no_ss`` means: Skull stripping should not be attempted on Dset
xxx means: Don't put anything, the script will strip Dset
No Cigar means: Don't try that combination, it makes no sense.z-no_ss)r   r   N)r!   r"   r#   r   r?   listr   ZftypeskeysrZ   r   r;   r   r   r)   Zno_ssr,   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 )AutoTLRCa\  A minmal wrapper for the AutoTLRC script
    The only option currently supported is no_ss.
    For complete details, see the `3dQwarp Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/@auto_tlrc.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> autoTLRC = afni.AutoTLRC()
    >>> autoTLRC.inputs.in_file = 'structural.nii'
    >>> autoTLRC.inputs.no_ss = True
    >>> autoTLRC.inputs.base = "TT_N27+tlrc"
    >>> autoTLRC.cmdline
    '@auto_tlrc -base TT_N27+tlrc -input structural.nii -no_ss'
    >>> res = autoTLRC.run()  # doctest: +SKIP

    z
@auto_tlrcc             C   s6   | j  j }d}tjj| j| jjdd| |d< |S )Nz.HEADz+tlrc)rC   rl   )rT   rU   r   r   r   rV   rW   r;   )r\   r]   rR   r,   r,   r-   r^   N  s
    zAutoTLRC._list_outputsN)
r!   r"   r#   r$   r_   r   r`   r   rT   r^   r,   r,   r,   r-   r   7  s
   r   c               @   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d0ddZejddd1ddZ	edddddZ
ejdddZeedddddZe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d.S )2BandpassInputSpeczinput file to 3dBandpassz%sr   TF)r   r   rk   r/   r   r0   z%s_bpzoutput file from 3dBandpassz
-prefix %sr;   )rc   r   r   rk   rd   lowpassz%fr   )r   r   rk   r/   highpassr   z	mask filez-mask %s)r   rk   r   r   z-despikez}Despike each time series before other processing. Hopefully, you don't actually need to do this, which is why it is optional.)r   r   )r   z-ort %szQAlso orthogonalize input to columns in f.1D. Multiple '-ort' options are allowed.z	-dsort %szOrthogonalize each voxel to the corresponding voxel time series in dataset 'fset', which must have the same spatial and temporal grid structure as the main input dataset. At present, only one '-dsort' option is allowed.)r   r   r   z
-nodetrendzSkip the quadratic detrending of the input that occurs before the FFT-based bandpassing. You would only want to do this if the dataset had been detrended already in some other program.z-dt %fz8Set time step (TR) in sec [default=from dataset header].z-nfft %dz+Set the FFT length [must be a legal value].z-normzHMake all output time series have L2 norm = 1 (i.e., sum of squares = 1).z	-automaskz%Create a mask from the input dataset.z-blur %fzLBlur (inside the mask only) with a filter width (FWHM) of 'fff' millimeters.z-localPV %fzReplace each vector by the local Principal Vector (AKA first singular vector) from a neighborhood of radius 'rrr' millimeters. Note that the PV time series is L2 normalized. This option is mostly for Bob Cox to have fun with.z-notranszDon't check for initial positive transients in the data. The test is a little slow, so skipping it is OK, if you KNOW the data time series are transient-free.NrS   r~   )r!   r"   r#   r   r;   rl   r   r&   r   r   r%   r)   Zdespiker   Zorthogonalize_fileZorthogonalize_dsetZ
no_detrendtrr'   Znfft	normalizer+   blurZlocalPVZnotransr,   r,   r,   r-   r   W  s`   


r   c               @   s   e Zd ZdZdZeZeZdS )Bandpassa  Program to lowpass and/or highpass each voxel time series in a
    dataset, offering more/different options than Fourier

    For complete details, see the `3dBandpass Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dBandpass.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> from nipype.testing import  example_data
    >>> bandpass = afni.Bandpass()
    >>> bandpass.inputs.in_file = 'functional.nii'
    >>> bandpass.inputs.highpass = 0.005
    >>> bandpass.inputs.lowpass = 0.1
    >>> bandpass.cmdline
    '3dBandpass -prefix functional_bp 0.005000 0.100000 functional.nii'
    >>> res = bandpass.run()  # doctest: +SKIP

    Z
3dBandpassN)	r!   r"   r#   r$   r_   r   r`   r   rT   r,   r,   r,   r-   r     s   r   c               @   s   e Zd ZedddddddZeddd	d
ddZedddZedddZej	dddZ
ejddddZej	dddZej	dddZeddddZdS ) BlurInMaskInputSpeczinput file to 3dSkullStripz	-input %sr   TF)r   r   rk   r/   r   r0   z%s_blurzoutput to the filez
-prefix %sr;   )rc   r   r   rd   rk   z~Mask dataset, if desired.  Blurring will occur only within the mask. Voxels NOT in the mask will be set to zero in the output.z-mask %s)r   r   zvMulti-mask dataset -- each distinct nonzero value in dataset will be treated as a separate mask for blurring purposes.z	-Mmask %sz*Create an automask from the input dataset.z	-automaskzfwhm kernel sizez-FWHM %f)r   r   r/   zNormally, voxels not in the mask will be set to zero in the output. If you want the original values in the dataset to be preserved in the output, use this option.z	-preservez>Save dataset as floats, no matter what the input data type is.z-floatoptionsz%sr   )r   r   rk   NrS   )r!   r"   r#   r   r;   rl   r%   Z	multimaskr   r)   r+   r&   fwhmZpreserveZ	float_outr   r   r,   r,   r,   r-   r     s:   
r   c               @   s   e Zd ZdZdZeZeZdS )
BlurInMaskab  Blurs a dataset spatially inside a mask.  That's all.  Experimental.

    For complete details, see the `3dBlurInMask Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dBlurInMask.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> bim = afni.BlurInMask()
    >>> bim.inputs.in_file = 'functional.nii'
    >>> bim.inputs.mask = 'mask.nii'
    >>> bim.inputs.fwhm = 5.0
    >>> bim.cmdline  # doctest: +ELLIPSIS
    '3dBlurInMask -input functional.nii -FWHM 5.000000 -mask mask.nii -prefix functional_blur'
    >>> res = bim.run()  # doctest: +SKIP

    Z3dBlurInMaskN)	r!   r"   r#   r$   r_   r   r`   r   rT   r,   r,   r,   r-   r     s   r   c               @   sb   e Z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Z
eddddZeddddZdS )BlurToFWHMInputSpecz!The dataset that will be smoothedz	-input %sT)r   r   r/   r   z*Create an automask from the input dataset.z	-automask)r   r   z1Blur until the 3D FWHM reaches this value (in mm)z-FWHM %fz=Blur until the 2D (x,y)-plane FWHM reaches this value (in mm)z
-FWHMxy %fz2The dataset whose smoothness controls the process.z-blurmaster %s)r   r   r   zKMask dataset, if desired. Voxels NOT in mask will be set to zero in output.z-mask %sN)r!   r"   r#   r   r;   r   r)   r+   r&   r   ZfwhmxyZ
blurmasterr%   r,   r,   r,   r-   r     s(   

r   c               @   s   e Zd ZdZdZeZeZdS )
BlurToFWHMa>  Blurs a 'master' dataset until it reaches a specified FWHM smoothness
    (approximately).

    For complete details, see the `3dBlurToFWHM Documentation
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dBlurToFWHM.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> blur = afni.preprocess.BlurToFWHM()
    >>> blur.inputs.in_file = 'epi.nii'
    >>> blur.inputs.fwhm = 2.5
    >>> blur.cmdline  # doctest: +ELLIPSIS
    '3dBlurToFWHM -FWHM 2.500000 -input epi.nii -prefix epi_afni'
    >>> res = blur.run()  # doctest: +SKIP

    Z3dBlurToFWHMN)	r!   r"   r#   r$   r_   r   r`   r   rT   r,   r,   r,   r-   r   !  s   r   c               @   sP   e Zd ZeddddddZejdddd	Zejd
ddddZ	edddddZ
dS )ClipLevelInputSpeczinput file to 3dClipLevelz%sr   T)r   r   rk   r/   r   z2Use the number ff instead of 0.50 in the algorithmz	-mfrac %sr   )r   r   rk   z1Apply the algorithm to each sub-brick separately.z-doallr   grad)r   r   rk   rf   zbAlso compute a 'gradual' clip level as a function of voxel position, and output that to a dataset.z-grad %sdoallNrS   )r!   r"   r#   r   r;   r   r&   Zmfracr)   r   r   r,   r,   r,   r-   r   9  s(   r   c               @   s   e Zd ZejddZdS )ClipLevelOutputSpecoutput)r   N)r!   r"   r#   r   r&   clip_valr,   r,   r,   r-   r   U  s   r   c               @   s&   e Zd ZdZdZeZeZdddZ	dS )	ClipLevela  Estimates the value at which to clip the anatomical dataset so
       that background regions are set to zero.

    For complete details, see the `3dClipLevel Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dClipLevel.html>`_

    Examples
    --------
    >>> from nipype.interfaces.afni import preprocess
    >>> cliplevel = preprocess.ClipLevel()
    >>> cliplevel.inputs.in_file = 'anatomical.nii'
    >>> cliplevel.cmdline
    '3dClipLevel anatomical.nii'
    >>> res = cliplevel.run()  # doctest: +SKIP

    Z3dClipLevelNc             C   s   | j  }tjjtj d}|d krPyt|d }W q tk
rL   | j jS X ng }xV|j	j
dD ]F}|rb|j
 }t|dkr|jdd |D  qb|jdd |D  qbW t|dkr|d }t|t|d	 ||_|S )
Nzstat_result.jsonstat
r   c             S   s   g | ]}t |qS r,   )float).0valr,   r,   r-   
<listcomp>  s    z/ClipLevel.aggregate_outputs.<locals>.<listcomp>c             S   s   g | ]}t |qS r,   )r   )r   r   r,   r,   r-   r     s    r   )r   )_outputsr   r   rX   getcwdr   IOErrorrunr]   stdoutrY   lenappendextendr   dictr   )r\   runtimeneeded_outputsr]   outfiler   linevaluesr,   r,   r-   aggregate_outputso  s&    zClipLevel.aggregate_outputs)NN)
r!   r"   r#   r$   r_   r   r`   r   rT   r   r,   r,   r,   r-   r   Y  s
   r   c               @   s>   e Zd ZdZedddddddZejdd	d
Ze	ddd
Z
dS )DegreeCentralityInputSpeczDegreeCentrality inputspecz input file to 3dDegreeCentralityz%sr   TF)r   r   rk   r/   r   r0   z(only take the top percent of connectionsz-sparsity %f)r   r   z2output filepath to text dump of correlation matrixz	-out1D %sNrS   )r!   r"   r#   r$   r   r;   r   r&   sparsityr   	oned_filer,   r,   r,   r-   r     s   
r   c               @   s   e Zd ZdZeddZdS )DegreeCentralityOutputSpeczDegreeCentrality outputspeczThe text output of the similarity matrix computed after thresholding with one-dimensional and ijk voxel indices, correlations, image extents, and affine matrix.)r   N)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 fddZ	  Z
S )DegreeCentralitya  Performs degree centrality on a dataset using a given maskfile
    via 3dDegreeCentrality

    For complete details, see the `3dDegreeCentrality Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dDegreeCentrality.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> degree = afni.DegreeCentrality()
    >>> degree.inputs.in_file = 'functional.nii'
    >>> degree.inputs.mask = 'mask.nii'
    >>> degree.inputs.sparsity = 1 # keep the top one percent of connections
    >>> degree.inputs.out_file = 'out.nii'
    >>> degree.cmdline
    '3dDegreeCentrality -mask mask.nii -prefix out.nii -sparsity 1.000000 functional.nii'
    >>> res = degree.run()  # doctest: +SKIP

    Z3dDegreeCentralityc                s.   t t| j }| jjr*tjj| jj|d< |S )Nr   )r   r   r^   rW   r   r   r   r   )r\   r]   )r   r,   r-   r^     s    zDegreeCentrality._list_outputs)r!   r"   r#   r$   r_   r   r`   r   rT   r^   r   r,   r,   )r   r-   r     s
   r   c               @   s0   e Zd ZedddddddZeddd	d
dZdS )DespikeInputSpeczinput file to 3dDespikez%sr   TF)r   r   rk   r/   r   r0   z
%s_despikezoutput image file namez
-prefix %sr;   )rc   r   r   rd   NrS   )r!   r"   r#   r   r;   rl   r,   r,   r,   r-   r     s   r   c               @   s   e Zd ZdZdZeZeZdS )Despikea  Removes 'spikes' from the 3D+time input dataset

    For complete details, see the `3dDespike Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dDespike.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> despike = afni.Despike()
    >>> despike.inputs.in_file = 'functional.nii'
    >>> despike.cmdline
    '3dDespike -prefix functional_despike functional.nii'
    >>> res = despike.run()  # doctest: +SKIP

    Z	3dDespikeN)	r!   r"   r#   r$   r_   r   r`   r   rT   r,   r,   r,   r-   r     s   r   c               @   s0   e Zd ZedddddddZeddd	d
dZdS )DetrendInputSpeczinput file to 3dDetrendz%sr   TF)r   r   rk   r/   r   r0   z
%s_detrendzoutput image file namez
-prefix %sr;   )rc   r   r   rd   NrS   )r!   r"   r#   r   r;   rl   r,   r,   r,   r-   r     s   r   c               @   s   e Zd ZdZdZeZeZdS )Detrenda[  This program removes components from voxel time series using
    linear least squares

    For complete details, see the `3dDetrend Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dDetrend.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> detrend = afni.Detrend()
    >>> detrend.inputs.in_file = 'functional.nii'
    >>> detrend.inputs.args = '-polort 2'
    >>> detrend.inputs.outputtype = 'AFNI'
    >>> detrend.cmdline
    '3dDetrend -polort 2 -prefix functional_detrend functional.nii'
    >>> res = detrend.run()  # doctest: +SKIP

    Z	3dDetrendN)	r!   r"   r#   r$   r_   r   r`   r   rT   r,   r,   r,   r-   r     s   r   c               @   s   e Zd ZdZe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jddd
ZdS )ECMInputSpeczECM inputspeczinput file to 3dECMz%sr   TF)r   r   rk   r/   r   r0   z(only take the top percent of connectionsz-sparsity %f)r   r   z_Full power method; enables thresholding; automatically selected if -thresh or -sparsity are setz-fullzFast centrality method; substantial speed increase but cannot accomodate thresholding; automatically selected if -thresh or -sparsity are not setz-fecmzshift correlation coefficients in similarity matrix to enforce non-negativity, s >= 0.0; default = 0.0 for -full, 1.0 for -fecmz	-shift %fzwscale correlation coefficients in similarity matrix to after shifting, x >= 0.0; default = 1.0 for -full, 0.5 for -fecmz	-scale %fzsets the stopping criterion for the power iteration; :math:`l2\|v_\text{old} - v_\text{new}\| < eps\|v_\text{old}\|`; default = 0.001z-eps %fzSsets the maximum number of iterations to use in the power iteration; default = 1000z-max_iter %dzgLimit memory consumption on system by setting the amount of GB to limit the algorithm to; default = 2GBz
-memory %fNrS   )r!   r"   r#   r$   r   r;   r   r&   r   r)   fullZfecmshiftscaleepsr'   Zmax_iterZmemoryr,   r,   r,   r-   r     s>   
r   c               @   s   e Zd ZdZdZeZeZdS )ECMa  Performs degree centrality on a dataset using a given maskfile
    via the 3dECM command

    For complete details, see the `3dECM Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dECM.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> ecm = afni.ECM()
    >>> ecm.inputs.in_file = 'functional.nii'
    >>> ecm.inputs.mask = 'mask.nii'
    >>> ecm.inputs.sparsity = 0.1 # keep top 0.1% of connections
    >>> ecm.inputs.out_file = 'out.nii'
    >>> ecm.cmdline
    '3dECM -mask mask.nii -prefix out.nii -sparsity 0.100000 functional.nii'
    >>> res = ecm.run()  # doctest: +SKIP

    Z3dECMN)	r!   r"   r#   r$   r_   r   r`   r   rT   r,   r,   r,   r-   r   R  s   r   c               @   s`   e Zd ZedddddddZeddd	d
dZeddddddZejddddZ	e
ddddZdS )FimInputSpeczinput file to 3dfim+z	-input %sr   TF)r   r   rk   r/   r   r0   z%s_fimzoutput image file namez
-bucket %sr;   )rc   r   r   rd   zideal time series file namez-ideal_file %sr   )r   r   rk   r/   r   z!fim internal mask threshold valuez-fim_thr %fr   )r   r   rk   z&Flag to output the specified parameterz-out %s   N)r!   r"   r#   r   r;   rl   Z
ideal_filer   r&   Zfim_thrr   outr,   r,   r,   r-   r   l  s,   r   c               @   s   e Zd ZdZdZeZeZdS )Fima  Program to calculate the cross-correlation of an ideal reference
    waveform with the measured FMRI time series for each voxel.

    For complete details, see the `3dfim+ Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dfim+.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> fim = afni.Fim()
    >>> fim.inputs.in_file = 'functional.nii'
    >>> fim.inputs.ideal_file= 'seed.1D'
    >>> fim.inputs.out_file = 'functional_corr.nii'
    >>> fim.inputs.out = 'Correlation'
    >>> fim.inputs.fim_thr = 0.0009
    >>> fim.cmdline
    '3dfim+ -input functional.nii -ideal_file seed.1D -fim_thr 0.000900 -out Correlation -bucket functional_corr.nii'
    >>> res = fim.run()  # doctest: +SKIP

    z3dfim+N)	r!   r"   r#   r$   r_   r   r`   r   rT   r,   r,   r,   r-   r     s   r   c               @   s^   e Zd ZedddddddZe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ZdS )FourierInputSpeczinput file to 3dFourierz%sr   TF)r   r   rk   r/   r   r0   z
%s_fourierzoutput image file namez
-prefix %sr;   )rc   r   r   rd   r   z-lowpass %f)r   r   r/   r   z-highpass %fzdAny mean and linear trend are removed before filtering. This will restore the trend after filtering.z-retrend)r   r   NrS   )r!   r"   r#   r   r;   rl   r   r&   r   r   r)   Zretrendr,   r,   r,   r-   r     s"   r   c               @   s   e Zd ZdZdZeZeZdS )Fouriera  Program to lowpass and/or highpass each voxel time series in a
    dataset, via the FFT

    For complete details, see the `3dFourier Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dFourier.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> fourier = afni.Fourier()
    >>> fourier.inputs.in_file = 'functional.nii'
    >>> fourier.inputs.retrend = True
    >>> fourier.inputs.highpass = 0.005
    >>> fourier.inputs.lowpass = 0.1
    >>> fourier.cmdline
    '3dFourier -highpass 0.005000 -lowpass 0.100000 -prefix functional_fourier -retrend functional.nii'
    >>> res = fourier.run()  # doctest: +SKIP

    Z	3dFourierN)	r!   r"   r#   r$   r_   r   r`   r   rT   r,   r,   r,   r-   r     s   r   c               @   s   e Zd ZedddddddZedddd	d
gdZejdddddZeddddd
d!dZ	e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d S )"HistInputSpeczinput file to 3dHistz	-input %sr   TF)r   r   rk   r/   r   r0   z-Write histogram to niml file with this prefixz%s_histz
-prefix %sr;   )r   rc   keep_extensionr   rd   zwrite a text visual histogramz	-showhist)r5   r   r   z%s_hist.outzoutput image file namez> %s)rc   r   r   r   rd   rk   zmatrix to align input filez-mask %s)r   r   r   znumber of binsz-nbin %d)r   r   z-max %fzmaximum intensity value)r   r   z-min %fzminimum intensity valuez-binwidth %fz	bin widthNrS   )r!   r"   r#   r   r;   rl   r   r)   showhistout_showr%   r'   Znbinr&   Z	max_valueZ	min_valueZ	bin_widthr,   r,   r,   r-   r     s6   
r   c               @   s"   e Zd ZedddZeddZdS )HistOutputSpeczoutput fileT)r   r   zoutput visual histogram)r   N)r!   r"   r#   r   rl   r   r,   r,   r,   r-   r     s   r   c                   sJ   e Zd ZdZdZeZeZdZ	 fddZ
d fdd	Z fd	d
Z  ZS )Hista  Computes average of all voxels in the input dataset
    which satisfy the criterion in the options list

    For complete details, see the `3dHist Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dHist.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> hist = afni.Hist()
    >>> hist.inputs.in_file = 'functional.nii'
    >>> hist.cmdline
    '3dHist -input functional.nii -prefix functional_hist'
    >>> res = hist.run()  # doctest: +SKIP

    Z3dHistTc                s6   t t| jf | t s2tj }|d dkr2d| _d S )Nr   i  F)r   r   __init__r   r   version_redirect_x)r\   rW   r   )r   r,   r-   r     s
    zHist.__init__Nc                s0   | j js|d krg }|dg7 }tt| j|dS )Nr   )skip)rW   r   r   r   _parse_inputs)r\   r   )r   r,   r-   r     s
    
zHist._parse_inputsc                s2   t t| j }|d  d7  < | jjs.t|d< |S )Nrl   z
.niml.histr   )r   r   r^   rW   r   r   )r\   r]   )r   r,   r-   r^   %  s
    zHist._list_outputs)N)r!   r"   r#   r$   r_   r   r`   r   rT   r   r   r   r^   r   r,   r,   )r   r-   r     s   	r   c               @   s$   e Zd ZdZeddd	ddddZdS )
LFCDInputSpeczLFCD inputspeczinput file to 3dLFCDz%sr   TF)r   r   rk   r/   r   r0   NrS   )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S )LFCDa  Performs degree centrality on a dataset using a given maskfile
    via the 3dLFCD command

    For complete details, see the `3dLFCD Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dLFCD.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> lfcd = afni.LFCD()
    >>> lfcd.inputs.in_file = 'functional.nii'
    >>> lfcd.inputs.mask = 'mask.nii'
    >>> lfcd.inputs.thresh = 0.8 # keep all connections with corr >= 0.8
    >>> lfcd.inputs.out_file = 'out.nii'
    >>> lfcd.cmdline
    '3dLFCD -mask mask.nii -prefix out.nii -thresh 0.800000 functional.nii'
    >>> res = lfcd.run()  # doctest: +SKIP
    Z3dLFCDN)	r!   r"   r#   r$   r_   r   r`   r   rT   r,   r,   r,   r-   r   :  s   r   c               @   sT   e Zd ZedddddddZedddd	d
ddZedddddZejddddZ	dS )MaskaveInputSpeczinput file to 3dmaskavez%sr   TF)r   r   rk   r/   r   r0   z%s_maskave.1Dzoutput image file namez> %sr;   r   )rc   r   r   r   rd   rk   zmatrix to align input filez-mask %s)r   r   rk   r   z-quiet)r   r   rk   Nr   rS   )
r!   r"   r#   r   r;   rl   r%   r   r)   r   r,   r,   r,   r-   r   S  s"   r   c               @   s   e Zd ZdZdZeZeZdS )Maskavea  Computes average of all voxels in the input dataset
    which satisfy the criterion in the options list

    For complete details, see the `3dmaskave Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dmaskave.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> maskave = afni.Maskave()
    >>> maskave.inputs.in_file = 'functional.nii'
    >>> maskave.inputs.mask= 'seed_mask.nii'
    >>> maskave.inputs.quiet= True
    >>> maskave.cmdline  # doctest: +ELLIPSIS
    '3dmaskave -mask seed_mask.nii -quiet functional.nii > functional_maskave.1D'
    >>> res = maskave.run()  # doctest: +SKIP

    Z	3dmaskaveN)	r!   r"   r#   r$   r_   r   r`   r   rT   r,   r,   r,   r-   r   j  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dddddZ	e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d!S )$MeansInputSpeczinput file to 3dMeanz%sr   T)r   r   rk   r/   r   zanother input file to 3dMeanr   )r   r   rk   r   z(Sets the data type of the output datasetz	-datum %s)r   r   z%s_meanzoutput image file namez
-prefix %s	in_file_a)rc   r   r   rd   zscaling of outputz-%sscalezuse only non-zero valuesz	-non_zerozcalculate std devz-stdevzmean square instead of valuez-sqrztake sum, (not average)z-sumz compute count of non-zero voxelsz-countzcreate intersection maskz-mask_interzcreate union maskz-mask_unionNr   rS   )r!   r"   r#   r   r   Z	in_file_br   r   datumrl   r   r)   Znon_zeroZstd_devZsqrZsummcountZ
mask_interZ
mask_unionr,   r,   r,   r-   r     s.   
r   c               @   s   e Zd ZdZdZeZeZdS )Meansa_  Takes the voxel-by-voxel mean of all input datasets using 3dMean

    For complete details, see the `3dMean Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dMean.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> means = afni.Means()
    >>> means.inputs.in_file_a = 'im1.nii'
    >>> means.inputs.in_file_b = 'im2.nii'
    >>> means.inputs.out_file =  'output.nii'
    >>> means.cmdline
    '3dMean -prefix output.nii im1.nii im2.nii'
    >>> res = means.run()  # doctest: +SKIP

    >>> from nipype.interfaces import afni
    >>> means = afni.Means()
    >>> means.inputs.in_file_a = 'im1.nii'
    >>> means.inputs.out_file =  'output.nii'
    >>> means.inputs.datum = 'short'
    >>> means.cmdline
    '3dMean -datum short -prefix output.nii im1.nii'
    >>> res = means.run()  # doctest: +SKIP

    Z3dMeanN)	r!   r"   r#   r$   r_   r   r`   r   rT   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gd	d
ZejdddddddZej	ddddgddZ
ej	ddddg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ddd gd!dd"d#Zejd$d%d&Zej	ddd'd(dZedd gdd)d*Zd+S )-OutlierCountInputSpecz%sTr   zinput dataset)r   r/   r   rk   r   z-mask %sr*   r+   z'only count voxels within the given mask)r   r   rf   r   gMbP?g        g      ?z
-qthr %.5fz'indicate a value for q to compute alpha)r   r1   highr5   r   r   Fz	-autoclipr%   zclip off small voxels)r5   r   rf   r   z	-automaskz	-fractionzLwrite out the fraction of masked voxels which are outliers at each timepoint)r5   r   r   z-rangezCwrite out the median + 3.5 MAD of outlier count with each timepointzenables out_file option)r5   r   z%s_outliersz-save %sr;   out_outlierszoutput image file name)rc   r   rd   Zoutput_namer   r   z
-polort %dz.detrend each voxel timeseries with polynomials)r   r   z	-legendrezuse Legendre polynomialszcapture standard output)rc   rd   r   r   Nr   )r!   r"   r#   r   r;   r%   r   r>   Zqthrr)   r*   r+   fractionintervalsave_outliersoutliers_filer'   r(   Zlegendrerl   r,   r,   r,   r-   r     sj   
r   c               @   s"   e Zd ZedddZeddZdS )OutlierCountOutputSpecTzoutput image file name)r   r   zcapture standard output)r   N)r!   r"   r#   r   r   rl   r,   r,   r,   r-   r    s   r  c                   sH   e Zd ZdZdZeZeZdZ	d fdd	Z
d fdd		Zd
d Z  ZS )OutlierCounta  Calculates number of 'outliers' at each time point of a
    a 3D+time dataset.

    For complete details, see the `3dToutcount Documentation
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dToutcount.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> toutcount = afni.OutlierCount()
    >>> toutcount.inputs.in_file = 'functional.nii'
    >>> toutcount.cmdline  # doctest: +ELLIPSIS
    '3dToutcount -qthr 0.00100 functional.nii'
    >>> res = toutcount.run()  # doctest: +SKIP

    Z3dToutcount
file_splitNc                s>   |d krg }| j dkrd| _ | jjs.|dg7 }tt| j|S )Nnoner  r   )Zterminal_outputrW   r   r   r  r   )r\   r   )r   r,   r-   r   "  s    

zOutlierCount._parse_inputsr   c          	      sH   t t| j||}ttj| jjd}|j|j	p6|j
 W d Q R X |S )Nw)r   r  _run_interfaceopenr   r   rW   rl   writer   Zmerged)r\   r   correct_return_codesZoutfh)r   r,   r-   r  /  s
    
zOutlierCount._run_interfacec             C   s<   | j  j }tj| jj|d< | jjr8tj| jj|d< |S )Nrl   r   )rT   rU   r   r   rW   rl   r   r   )r\   r]   r,   r,   r-   r^   9  s
    zOutlierCount._list_outputs)Nr   )r
  )r!   r"   r#   r$   r_   r   r`   r  rT   _terminal_outputr   r  r^   r   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g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gddZ
ejddddgddZejdddZejdddddZeddgddd#dd Zd!S )$QualityIndexInputSpecz%sTr   zinput dataset)r   r/   r   rk   r   z-mask %sr*   r+   z-compute correlation only across masked voxels)r   r   rf   r   Fz	-spearmanz|Quality index is 1 minus the Spearman (rank) correlation coefficient of each sub-brick with the median sub-brick. (default).)r5   r   r   z	-quadrantzbSimilar to -spearman, but using 1 minus the quadrant correlation coefficient as the quality index.z	-autoclipr%   zclip off small voxels)r5   r   rf   r   z	-automaskz-clip %fzclip off values below)r   r   z-rangezCwrite out the median + 3.5 MAD of outlier count with each timepointz%s_tqualr;   z> %sr   zcapture standard output)rc   rd   r   r   rk   r   Nr   rS   )r!   r"   r#   r   r;   r%   r   r)   spearmanquadrantr*   r+   r&   Zclipr   rl   r,   r,   r,   r-   r  A  sT   r  c               @   s   e Zd ZeddZdS )QualityIndexOutputSpecz,file containing the captured standard output)r   N)r!   r"   r#   r   rl   r,   r,   r,   r-   r  y  s   r  c               @   s   e Zd ZdZdZeZeZdS )QualityIndexas  Computes a quality index for each sub-brick in a 3D+time dataset.
    The output is a 1D time series with the index for each sub-brick.
    The results are written to stdout.

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> tqual = afni.QualityIndex()
    >>> tqual.inputs.in_file = 'functional.nii'
    >>> tqual.cmdline  # doctest: +ELLIPSIS
    '3dTqual functional.nii > functional_tqual'
    >>> res = tqual.run()  # doctest: +SKIP

    See Also
    --------
    For complete details, see the `3dTqual Documentation
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTqual.html>`_

    Z3dTqualN)	r!   r"   r#   r$   r_   r  r`   r  rT   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	d
dZeddddZejdddZ	ej
dddZejdgdddZe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!gd"d#d$Zejd%gd&d'd$Zd(d)d*d+d,d-d.d/d0d1d2d3gZeejed4d5dZed6d7d8d9d:d?d<Zd=S )@ROIStatsInputSpeczinput datasetz%sr   T)r   r   rk   r/   r   z
input maskz-mask %sr   z1.1.4	mask_file)r   r   rk   r   ru   rv   )r   r   r   zPTells the program to convert a float mask to short integers, by simple rounding.z-mask_f2short)r   r   a  Forces the assumption that the mask dataset's ROIs are denoted by 1 to n inclusive.  Normally, the program figures out the ROIs on its own.  This option is useful if a) you are certain that the mask dataset has no values outside the range [0 n], b) there may be some ROIs missing between [1 n] in the mask data-set and c) you want those columns in the output any-way so the output lines up with the output from other invocations of 3dROIstats.z
-numroi %snum_roiz{For ROI labels not found, use the provided string instead of a '0' in the output file. Only active if `num_roi` is enabled.z-zerofill %s)requiresr   r   zOnly considers ROIs denoted by values found in the specified file. Note that the order of the ROIs as specified in the file is not preserved. So an SEL.1D of '2 8 20' produces the same output as '8 20 2'z
-roisel %s)r   r   r   zprint debug informationz-debugzexecute quietlyz-quietz=Do not include the (zero-inclusive) mean among computed statsz
-nomeanoutz2Do not print the sub-brick label next to its indexz
-nobriklab	format1DRz<Output results in a 1D format that includes commented labelsz	-1Dformat)rf   r   r   format1DzOutput results in a 1D format that includes uncommented labels. May not work optimally with typical 1D functions, but is useful for R functions.z
-1DRformatr2   sumvoxelsminmaxsigmar3   modesummary
zerominmax	zerosigma
zeromedianzeromodeaX  Statistics to compute. Options include:

 * mean       =   Compute the mean using only non_zero voxels.
                  Implies the opposite for the mean computed
                  by default.
 * median     =   Compute the median of nonzero voxels
 * mode       =   Compute the mode of nonzero voxels.
                  (integral valued sets only)
 * minmax     =   Compute the min/max of nonzero voxels
 * sum        =   Compute the sum using only nonzero voxels.
 * voxels     =   Compute the number of nonzero voxels
 * sigma      =   Compute the standard deviation of nonzero
                  voxels

Statistics that include zero-valued voxels:

 * zerominmax =   Compute the min/max of all voxels.
 * zerosigma  =   Compute the standard deviation of all
                  voxels.
 * zeromedian =   Compute the median of all voxels.
 * zeromode   =   Compute the mode of all voxels.
 * summary    =   Only output a summary line with the grand
                  mean across all briks in the input dataset.
                  This option cannot be used with nomeanout.

More that one option can be specified.z%s...z%s_roistat.1Dzoutput fileFz> %sr;   r   )rc   r   r   r   rd   rk   Nr   rS   )r!   r"   r#   r   r;   r%   r  r   r)   Zmask_f2shortr'   r  r   ZzerofillZroiseldebugr   Z	nomeanoutZ	nobriklabr  r  Z_stat_namesr   r?   r   rl   r,   r,   r,   r-   r    s|   	
r  c               @   s   e Zd ZedddZdS )ROIStatsOutputSpecz output tab-separated values fileT)r   r   N)r!   r"   r#   r   rl   r,   r,   r,   r-   r"    s   r"  c                   s0   e Zd ZdZdZdZeZeZ	 fddZ
  ZS )ROIStatsa  Display statistics over masked regions

    For complete details, see the `3dROIstats Documentation
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dROIstats.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> roistats = afni.ROIStats()
    >>> roistats.inputs.in_file = 'functional.nii'
    >>> roistats.inputs.mask_file = 'skeleton_mask.nii.gz'
    >>> roistats.inputs.stat = ['mean', 'median', 'voxels']
    >>> roistats.inputs.nomeanout = True
    >>> roistats.cmdline
    '3dROIstats -mask skeleton_mask.nii.gz -nomeanout -nzmean -nzmedian -nzvoxels functional.nii > functional_roistat.1D'
    >>> res = roistats.run()  # doctest: +SKIP

    Z
3dROIstatsZ	allatoncec                sL   ddddddddd	d
ddd |dkr8 fdd|D }t t| j|||S )Nz-nzmeanz	-nzmedianz-nzmodez	-nzminmaxz-nzsigmaz	-nzvoxelsz-nzsumz-summaryz-minmaxz-medianz-sigmaz-mode)r2   r3   r  r  r  r  r  r  r  r  r  r   r   c                s   g | ]} | qS r,   r,   )r   v)
_stat_dictr,   r-   r   =  s    z(ROIStats._format_arg.<locals>.<listcomp>)r   r#  _format_arg)r\   r   
trait_specr   )r   )r%  r-   r&  -  s    zROIStats._format_arg)r!   r"   r#   r$   r_   r  r  r`   r"  rT   r&  r   r,   r,   )r   r-   r#    s   r#  c               @   s   e Zd Zeddd"ddddZeddg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Z
ej	ddd&dZeddd'ddZeddd(ddZd!S ))RetroicorInputSpeczinput file to 3dretroicorz%sr   TF)r   r   rk   r/   r   r0   z%s_retroicorr;   zoutput image file namez
-prefix %s)rc   rd   r   r   rk   z+1D cardiac data file for cardiac correctionz-card %sr   )r   r   rk   r   z+1D respiratory waveform data for correctionz-resp %sr   zThreshold for detection of R-wave peaks in input (Make sure it is above the background noise level, Try 3/4 or 4/5 times range plus minimum)z-threshold %dr   )r   r   rk   z*The order of the correction (2 is typical)z	-order %s   z$Filename for 1D cardiac phase outputz-cardphase %s   )r   r   rk   re   z!Filename for 1D resp phase outputz-respphase %s   NrS   r   r~   ii)r!   r"   r#   r   r;   rl   cardrespr   r'   	thresholdorderZ	cardphaseZ	respphaser,   r,   r,   r-   r(  A  sR   r(  c                   s,   e Zd ZdZdZeZeZ fddZ	  Z
S )	RetroicoraE  Performs Retrospective Image Correction for physiological
    motion effects, using a slightly modified version of the
    RETROICOR algorithm

    The durations of the physiological inputs are assumed to equal
    the duration of the dataset. Any constant sampling rate may be
    used, but 40 Hz seems to be acceptable. This program's cardiac
    peak detection algorithm is rather simplistic, so you might try
    using the scanner's cardiac gating output (transform it to a
    spike wave if necessary).

    This program uses slice timing information embedded in the
    dataset to estimate the proper cardiac/respiratory phase for
    each slice. It makes sense to run this program before any
    program that may destroy the slice timings (e.g. 3dvolreg for
    motion correction).

    For complete details, see the `3dretroicor Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dretroicor.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> ret = afni.Retroicor()
    >>> ret.inputs.in_file = 'functional.nii'
    >>> ret.inputs.card = 'mask.1D'
    >>> ret.inputs.resp = 'resp.1D'
    >>> ret.inputs.outputtype = 'NIFTI'
    >>> ret.cmdline
    '3dretroicor -prefix functional_retroicor.nii -resp resp.1D -card mask.1D functional.nii'
    >>> res = ret.run()  # doctest: +SKIP

    Z3dretroicorc                s<   |dkr(t | jj r(t | jj r(d S tt| j|||S )Nr;   )r   rW   r.  r/  r   r2  r&  )r\   r   r'  r   )r   r,   r-   r&    s    zRetroicor._format_arg)r!   r"   r#   r$   r_   r(  r`   r   rT   r&  r   r,   r,   )r   r-   r2  w  s
   !r2  c               @   s   e Zd Zeddd#ddddZejejded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Zej
dddZedddZedddZedddZej
dddZejd d!dZd"S )%SegInputSpeczANAT is the volume to segmentz-anat %sr   T)r   r   rk   r/   r   r0   ZAUTO)r   zonly non-zero voxels in mask are analyzed. mask can either be a dataset or the string "AUTO" which would use AFNI's automask function to create the mask.z-mask %sr   )r   r   rk   r/   ZBFTZBIMz-blur_meth %sz1set the blurring method for bias field estimation)r   r   zPThe amount of blurring used when estimating the field bias with the Wells methodz-bias_fwhm %f)r   r   z<CLASS_STRING is a semicolon delimited string of class labelsz-classes %szGWeighting factor controlling spatial homogeneity of the classificationsz-bmrf %fz[A semicolon delimited string of classes that contribute to the estimation of the bias fieldz-bias_classes %sz>the prefix for the output folder containing all output volumesz
-prefix %sz}MIXFRAC sets up the volume-wide (within mask) tissue fractions while initializing the segmentation (see IGNORE for exception)z-mixfrac %sz5Set the minimum value for any class's mixing fractionz-mixfloor %fz Number of iterations to perform.z
-main_N %dNrS   r   )r!   r"   r#   r   r;   r   r=   r?   r%   Z	blur_methr&   Z	bias_fwhmr   classesZbmrfZbias_classesprefixZmixfracZmixfloorr'   Zmain_Nr,   r,   r,   r-   r3    sR   r3  c               @   s&   e Zd ZdZdZeZeZdddZ	dS )Segav  3dSeg segments brain volumes into tissue classes. The program allows
    for adding a variety of global and voxelwise priors. However for the
    moment, only mixing fractions and MRF are documented.

    For complete details, see the `3dSeg Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dSeg.html>`_

    Examples
    --------
    >>> from nipype.interfaces.afni import preprocess
    >>> seg = preprocess.Seg()
    >>> seg.inputs.in_file = 'structural.nii'
    >>> seg.inputs.mask = 'AUTO'
    >>> seg.cmdline
    '3dSeg -mask AUTO -anat structural.nii'
    >>> res = seg.run()  # doctest: +SKIP

    Z3dSegNc             C   s^   dd l }| j }t| jjr6tjjtj | jjd}ntjjtj dd}|j |d |_	|S )Nr   zClasses+*.BRIKZSegsy)
globr   r   rW   r5  r   r   rX   r   rl   )r\   r   r   r7  r]   r   r,   r,   r-   r     s    zSeg.aggregate_outputs)NN)
r!   r"   r#   r$   r_   r3  r`   r   rT   r   r,   r,   r,   r-   r6    s
   r6  c               @   s0   e Zd ZedddddddZeddd	d
dZdS )SkullStripInputSpeczinput file to 3dSkullStripz	-input %sr   TF)r   r   rk   r/   r   r0   z%s_skullstripzoutput image file namez
-prefix %sr;   )rc   r   r   rd   N)r!   r"   r#   r   r;   rl   r,   r,   r,   r-   r8  		  s   r8  c                   s0   e Zd ZdZdZdZeZeZ	 fddZ
  ZS )
SkullStripar  A program to extract the brain from surrounding tissue from MRI
    T1-weighted images.
    TODO Add optional arguments.

    For complete details, see the `3dSkullStrip Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dSkullStrip.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> skullstrip = afni.SkullStrip()
    >>> skullstrip.inputs.in_file = 'functional.nii'
    >>> skullstrip.inputs.args = '-o_ply'
    >>> skullstrip.cmdline
    '3dSkullStrip -input functional.nii -o_ply -prefix functional_skullstrip'
    >>> res = skullstrip.run()  # doctest: +SKIP

    r6   Tc                s:   t t| jf | t s6tj }|dkr6|dk r6d| _d S )N  r   r   r+  F)r:  r   r   )r:  r   r+  )r   r9  r   r   r   r   r   )r\   rW   r$  )r   r,   r-   r   3	  s
    zSkullStrip.__init__)r!   r"   r#   r$   r_   r   r8  r`   r   rT   r   r   r,   r,   )r   r-   r9  	  s   r9  c               @   s   e Zd Zed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gddZ	ejdddddgddZ
ejdddddgddZejdddddgddZdS )TCorr1DInputSpecz3d+time dataset inputz %sr   TF)r   r   rk   r/   r   r0   z1D time series file inputr   )r   r   rk   r/   r   zoutput filename prefixz%s_correlation.nii.gzz
-prefix %sxset)r   rc   r   rd   r   z9Correlation is the normal Pearson correlation coefficientz	 -pearsonr  r  ktaub)r   r   rf   rk   z:Correlation is the Spearman (rank) correlation coefficientz
 -spearmanpearsonz3Correlation is the quadrant correlation coefficientz
 -quadrantz:Correlation is the Kendall's tau_b correlation coefficientz -ktaubNr   rS   )r!   r"   r#   r   r<  Zy_1drl   r   r)   r>  r  r  r=  r,   r,   r,   r-   r;  >	  sN   r;  c               @   s   e Zd ZedddZdS )TCorr1DOutputSpecz#output file containing correlationsT)r   r   N)r!   r"   r#   r   rl   r,   r,   r,   r-   r?  o	  s   r?  c               @   s   e Zd ZdZdZeZeZdS )TCorr1Da=  Computes the correlation coefficient between each voxel time series
    in the input 3D+time dataset.

    For complete details, see the `3dTcorr1D Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTcorr1D.html>`_

    >>> from nipype.interfaces import afni
    >>> tcorr1D = afni.TCorr1D()
    >>> tcorr1D.inputs.xset= 'u_rc1s1_Template.nii'
    >>> tcorr1D.inputs.y_1d = 'seed.1D'
    >>> tcorr1D.cmdline
    '3dTcorr1D -prefix u_rc1s1_Template_correlation.nii.gz  u_rc1s1_Template.nii  seed.1D'
    >>> res = tcorr1D.run()  # doctest: +SKIP

    Z	3dTcorr1DN)	r!   r"   r#   r$   r_   r;  r`   r?  rT   r,   r,   r,   r-   r@  s	  s   r@  c               @   sp  e Zd ZedddddZeddddZeddd	Zejd
dZ	ej
ddZejej ej fddZeddd	Zej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ddddZd7Zejej
 Zed d!ded"Zed#d$ded"Zed%d&ded"Zed'dd(Zed)dd(Zd8Ze Z ed-d.ded"Z!ed/d0ded"Z"ed1d2ded"Z#ej
 Z$edd3d4d5Z%d6S )9TCorrMapInputSpecTz	-input %sF)r   r   r/   r0   z-seed %sseeds_width)r   r   rf   z-mask %s)r   r   z	-automask)r   z
-polort %dz-bpass %f %fz-ort %sz	-Gblur %fz	-Mseed %fseeds)r   rf   z-Mean %sZ_meanr;   )r   rC   rd   z	-Zmean %sZ_zmeanz	-Qmean %sZ_qmeanz	-Pmean %sZ_pmeanabsolute_thresholdvar_absolute_threshold var_absolute_threshold_normalizez-Thresh %f %sZ_thresh)r   rC   rd   rf   z-VarThresh %f %f %f %sZ
_varthreshz-VarThreshN %f %f %f %sZ_varthreshnz-CorrMap %s)r   rd   z-CorrMask %saverage_expraverage_expr_nonzerosum_exprz-Aexpr %s %sZ_aexprz-Cexpr %s %sZ_cexprz-Sexpr %s %sZ_sexprz-Hist %d %sZ_hist)rd   r   rC   N)rD  rE  rF  )rG  rH  rI  )&r!   r"   r#   r   r;   rC  r%   r   r)   r+   r'   r(   Tupler&   bandpassZregress_out_timeseriesZ	blur_fwhmrB  	mean_filezmeanqmeanpmean_thresh_optsr   
thresholdsrD  rE  rF  correlation_mapscorrelation_maps_masked
_expr_optsr   exprrG  rH  rI  histogram_bin_numbers	histogramr,   r,   r,   r-   rA  	  sX     rA  c               @   sZ   e Zd Ze Ze Ze Ze Ze Ze Z	e Z
e Ze Ze Ze Ze Ze ZdS )TCorrMapOutputSpecN)r!   r"   r#   r   rL  rM  rN  rO  rD  rE  rF  rR  rS  rG  rH  rI  rW  r,   r,   r,   r-   rX  	  s   rX  c                   s2   e Zd ZdZdZeZeZdgZ	 fddZ
  ZS )TCorrMapa  For each voxel time series, computes the correlation between it
    and all other voxels, and combines this set of values into the
    output dataset(s) in some way.

    For complete details, see the `3dTcorrMap Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTcorrMap.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> tcm = afni.TCorrMap()
    >>> tcm.inputs.in_file = 'functional.nii'
    >>> tcm.inputs.mask = 'mask.nii'
    >>> tcm.mean_file = 'functional_meancorr.nii'
    >>> tcm.cmdline # doctest: +SKIP
    '3dTcorrMap -input functional.nii -mask mask.nii -Mean functional_meancorr.nii'
    >>> res = tcm.run()  # doctest: +SKIP

    Z
3dTcorrMaprC   c                sp   || j jkr |j| j j |g S || j jkr>|j| j j|f S |dkrX|j| j j|f S tt| j	|||S d S )NrW  )
rW   rP  r   rQ  rT  rU  rV  r   rY  r&  )r\   r   r'  r   )r   r,   r-   r&  	  s    zTCorrMap._format_arg)r!   r"   r#   r$   r_   rA  r`   rX  rT   Z_additional_metadatar&  r   r,   r,   )r   r-   rY  	  s   rY  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	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d%d&d'd(d)d*Zd+S ),NetCorrInputSpecz$input time series file (4D data set)Tz	-inset %s)r   r   r   r/   z7input set of ROIs, each labelled with distinct integersz-in_rois %szncan include a whole brain mask within which to calculate correlation. Otherwise, data should be masked alreadyz-mask %s)r   r   r   a  input a 1D file WTS of weights that will be applied multiplicatively to each ROI's average time series. WTS can be a column- or row-file of values, but it must have the same length as the input time series volume. If the initial average time series was A[n] for n=0,..,(N-1) time points, then applying a set of weights W[n] of the same length from WTS would produce a new time series:  B[n] = A[n] * W[n]z-weight_ts %sa  switch to also output a matrix of Fisher Z-transform values for the corr coefs (r): Z = atanh(r) , (with Z=4 being output along matrix diagonals where r=1, as the r-to-Z conversion is ceilinged at Z = atanh(r=0.999329) = 4, which is still *quite* a high Pearson-r valuez-fish_z)r   r   z%output the partial correlation matrixz
-part_corrzswitch to output the mean time series of the ROIs that have been used to generate the correlation matrices. Output filenames mirror those of the correlation matrix files, with a '.netts' postfixz-ts_outa5  additional switch when using '-ts_out'. Using this option will insert the integer ROI label at the start of each line of the *.netts file created. Thus, for a time series of length N, each line will have N+1 numbers, where the first is the integer ROI label and the subsequent N are scientific notation valuesz	-ts_labelas  switch to create a directory for each network that contains the average time series for each ROI in individual files (each file has one line). The directories are labelled PREFIX_000_INDIV/, PREFIX_001_INDIV/, etc. (one per network). Within each directory, the files are labelled ROI_001.netts, ROI_002.netts, etc., with the numbers given by the actual ROI integer labelsz	-ts_indiva  switch to create a set of whole brain correlation maps. Performs whole brain correlation for each ROI's average time series; this will automatically create a directory for each network that contains the set of whole brain correlation maps (Pearson 'r's). The directories are labelled as above for '-ts_indiv' Within each directory, the files are labelled WB_CORR_ROI_001+orig, WB_CORR_ROI_002+orig, etc., with the numbers given by the actual ROI integer labelsz-ts_wb_corra  same as above in '-ts_wb_corr', except that the maps have been Fisher transformed to Z-scores the relation: Z=atanh(r). To avoid infinities in the transform, Pearson values are effectively capped at |r| = 0.999329 (where |Z| = 4.0). Files are labelled WB_Z_ROI_001+orig, etcz-ts_wb_Za  by default, '-ts_wb_{corr,Z}' output files are named using the int number of a given ROI, such as: WB_Z_ROI_001+orig. With this option, one can replace the int (such as '001') with the string label (such as 'L-thalamus') *if* one has a labeltable attached to the filez-ts_wb_strlabelz|output any correlation map files as NIFTI files (default is BRIK/HEAD). Only useful if using '-ts_wb_corr' and/or '-ts_wb_Z'z-niftizinternally, this program checks for where there are nonnull time series, because we don't like those, in general.  With this flag, the user can output the determined mask of non-null time series.z-output_mask_nonnulla  by default, this program will grind to a halt and refuse to calculate if any ROI contains >10 percent of voxels with null times series (i.e., each point is 0), as of April, 2017.  This is because it seems most likely that hidden badness is responsible. However, if the user still wants to carry on the calculation anyways, then this option will allow one to push on through.  However, if any ROI *only* has null time series, then the program will not calculate and the user will really, really, really need to address their maskingz-push_thru_many_zerosz`switch to ignore any label table labels in the '-in_rois' file, if there are any labels attachedz
-ignore_LTzoutput file name partz
%s_netcorrz
-prefix %sr   r;   )r   rc   r   rk   rd   N)r!   r"   r#   r   r;   Zin_roisr%   Z	weight_tsr   r)   Zfish_zZ	part_corrZts_outZts_labelZts_indiv
ts_wb_corrZts_wb_ZZts_wb_strlabelZniftiZoutput_mask_nonnullZpush_thru_many_zerosZ	ignore_LTrl   r,   r,   r,   r-   rZ  	  sv   	
	
rZ  c               @   s&   e Zd ZeddZeje ddZdS )NetCorrOutputSpeczPoutput correlation matrix between ROIs written to a text file with .netcc suffix)r   z2output correlation maps in Pearson and/or Z-scoresN)r!   r"   r#   r   out_corr_matrixr   r   out_corr_mapsr,   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 )NetCorrac  Calculate correlation matrix of a set of ROIs (using mean time series of
    each). Several networks may be analyzed simultaneously, one per brick.

    For complete details, see the `3dNetCorr Documentation
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dNetCorr.html>`_.

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> ncorr = afni.NetCorr()
    >>> ncorr.inputs.in_file = 'functional.nii'
    >>> ncorr.inputs.mask = 'mask.nii'
    >>> ncorr.inputs.in_rois = 'maps.nii'
    >>> ncorr.inputs.ts_wb_corr = True
    >>> ncorr.inputs.ts_wb_Z = True
    >>> ncorr.inputs.fish_z = True
    >>> ncorr.inputs.out_file = 'sub0.tp1.ncorr'
    >>> ncorr.cmdline
    '3dNetCorr -prefix sub0.tp1.ncorr -fish_z -inset functional.nii -in_rois maps.nii -mask mask.nii -ts_wb_Z -ts_wb_corr'
    >>> res = ncorr.run()  # doctest: +SKIP

    Z	3dNetCorrc             C   s   dd l }| j j }t| jjs4| j| jjdd}n| jj}tj	j
tj	j|}|j tj	j|dd |d< t| jjst| jjrtj	j||d }|j tj	j|d|d< |S )	Nr   Z_netcorr)rC   z*.netccr]  Z
_000_INDIVz*.nii.gzr^  )r7  rT   rU   r   rW   rl   rV   r;   r   r   dirnamer   rX   r[  Z	ts_Z_corr)r\   r7  r]   r5  ZodirZcorrdirr,   r,   r-   r^   
  s    zNetCorr._list_outputsN)
r!   r"   r#   r$   r_   rZ  r`   r\  rT   r^   r,   r,   r,   r-   r_  
  s
   r_  c               @   s`   e Zd ZedddddddZed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dS )TCorrelateInputSpecz
input xsetz%sr   TF)r   r   rk   r/   r   r0   z
input ysetr   z%s_tcorrzoutput image file namez
-prefix %sr<  )rc   r   r   rd   z9Correlation is the normal Pearson correlation coefficientz-pearson)r   r   z#Remove polynomical trend of order mz
-polort %dNr   rS   )r!   r"   r#   r   r<  Zysetrl   r   r)   r>  r'   r(   r,   r,   r,   r-   ra  
  s.   ra  c               @   s   e Zd ZdZdZeZeZdS )
TCorrelateaE  Computes the correlation coefficient between corresponding voxel
    time series in two input 3D+time datasets 'xset' and 'yset'

    For complete details, see the `3dTcorrelate Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTcorrelate.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> tcorrelate = afni.TCorrelate()
    >>> tcorrelate.inputs.xset= 'u_rc1s1_Template.nii'
    >>> tcorrelate.inputs.yset = 'u_rc1s2_Template.nii'
    >>> tcorrelate.inputs.out_file = 'functional_tcorrelate.nii.gz'
    >>> tcorrelate.inputs.polort = -1
    >>> tcorrelate.inputs.pearson = True
    >>> tcorrelate.cmdline
    '3dTcorrelate -prefix functional_tcorrelate.nii.gz -pearson -polort -1 u_rc1s1_Template.nii u_rc1s2_Template.nii'
    >>> res = tcarrelate.run()  # doctest: +SKIP

    Z3dTcorrelateN)	r!   r"   r#   r$   r_   ra  r`   r   rT   r,   r,   r,   r-   rb  
  s   rb  c               @   s   e Zd Zed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Z
ejdddZejdddZejdddZdS )TNormInputSpeczinput file to 3dTNormz%sr   TF)r   r   rk   r/   r   r0   z%s_tnormzoutput image file namez
-prefix %sr;   )rc   r   r   rd   z+L2 normalize (sum of squares = 1) [DEFAULT]z-norm2)r   r   zHnormalize so sum of squares = number of time points \* e.g., so RMS = 1.z-normRz)L1 normalize (sum of absolute values = 1)z-norm1z1Scale so max absolute value = 1 (L_infinity norm)z-normxzDetrend with polynomials of order p before normalizing [DEFAULT = don't do this].
Use '-polort 0' to remove the mean, for examplez
-polort %szZDetrend with L1 regression (L2 is the default)
This option is here just for the hell of itz-L1fitNrS   )r!   r"   r#   r   r;   rl   r   r)   Znorm2ZnormRZnorm1Znormxr'   r(   ZL1fitr,   r,   r,   r-   rc  
  s6   


rc  c               @   s   e Zd ZdZdZeZeZdS )TNormaj  Shifts voxel time series from input so that separate slices are aligned
    to the same temporal origin.

    For complete details, see the `3dTnorm Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTnorm.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> tnorm = afni.TNorm()
    >>> tnorm.inputs.in_file = 'functional.nii'
    >>> tnorm.inputs.norm2 = True
    >>> tnorm.inputs.out_file = 'rm.errts.unit errts+tlrc'
    >>> tnorm.cmdline
    '3dTnorm -norm2 -prefix rm.errts.unit errts+tlrc functional.nii'
    >>> res = tshift.run()  # doctest: +SKIP

    Z3dTnormN)	r!   r"   r#   r$   r_   rc  r`   r   rT   r,   r,   r,   r-   rd  &  s   rd  c               @   s,  e Zd ZedddddddZeddd6d	d
dZeddddZejej	 dddZ
ejddddddZeddddZejdddZeddddZejdddZeeddd d!d"d#Zejejejd$d%dZejejejd&d'dZejd(d)dZedd*d+d,Zejd-d.gd/d0Zejd1d2dZejd3d4dZd5S )7TProjectInputSpeczinput file to 3dTprojectz	-input %sr   TF)r   r   rk   r/   r   r0   z%s_tprojectzoutput image file namez
-prefix %sr;   )rc   r   rk   r   rd   zFilename of censor .1D time series.
This is a file of 1s and 0s, indicating which
time points are to be included (1) and which are
to be excluded (0).z
-censor %s)r   r   r   az  List of strings that specify time indexes
to be removed from the analysis.  Each string is
of one of the following forms:

* ``37`` => remove global time index #37
* ``2:37`` => remove time index #37 in run #2
* ``37..47`` => remove global time indexes #37-47
* ``37-47`` => same as above
* ``2:37..47`` => remove time indexes #37-47 in run #2
* ``*:0-2`` => remove time indexes #0-2 in all runs

  * Time indexes within each run start at 0.
  * Run indexes start at 1 (just be to confusing).
  * N.B.: 2:37,47 means index #37 in run #2 and
    global time index 47; it does NOT mean
    index #37 in run #2 AND index #47 in run #2.

z-CENSORTR %s)r   r   ZKILLZZEROZNTRPa   Specifies how censored time points are treated in
the output dataset:

* mode = ZERO -- put zero values in their place;
  output datset is same length as input
* mode = KILL -- remove those time points;
  output dataset is shorter than input
* mode = NTRP -- censored values are replaced by interpolated
  neighboring (in time) non-censored values,
  BEFORE any projections, and then the
  analysis proceeds without actual removal
  of any time points -- this feature is to
  keep the Spanish Inquisition happy.
* The default mode is KILL !!!

z-cenmode %sa  The catenation file, as in 3dDeconvolve, containing the
TR indexes of the start points for each contiguous run
within the input dataset (the first entry should be 0).

* Also as in 3dDeconvolve, if the input dataset is
  automatically catenated from a collection of datasets,
  then the run start indexes are determined directly,
  and '-concat' is not needed (and will be ignored).
* Each run must have at least 9 time points AFTER
  censoring, or the program will not work!
* The only use made of this input is in setting up
  the bandpass/stopband regressors.
* '-ort' and '-dsort' regressors run through all time
  points, as read in.  If you want separate projections
  in each run, then you must either break these ort files
  into appropriate components, OR you must run 3dTproject
  for each run separately, using the appropriate pieces
  from the ort files via the ``{...}`` selector for the
  1D files and the ``[...]`` selector for the datasets.

z
-concat %s)r   r   r   zAlso as in 3dDeconvolve, if you want the program to treat
an auto-catenated dataset as one long run, use this option.
However, '-noblock' will not affect catenation if you use
the '-concat' option.z-noblockzCRemove each column in file.
Each column will have its mean removed.z-ort %sa  Remove polynomials up to and including degree pp.

* Default value is 2.
* It makes no sense to use a value of pp greater than
  2, if you are bandpassing out the lower frequencies!
* For catenated datasets, each run gets a separate set
  set of pp+1 Legendre polynomial regressors.
* Use of -polort -1 is not advised (if data mean != 0),
  even if -ort contains constant terms, as all means are
  removed.

z
-polort %d)r   r0   z-dsort %s...zRemove the 3D+time time series in dataset fset.

* That is, 'fset' contains a different nuisance time
  series for each voxel (e.g., from AnatICOR).
* Multiple -dsort options are allowed.

)r   r   z0Remove all frequencies EXCEPT those in the rangez-bandpass %g %gz#Remove all frequencies in the rangez-stopband %g %gzdUse time step dd for the frequency calculations,
rather than the value stored in the dataset header.z-TR %gzOnly operate on voxels nonzero in the mset dataset.

* Voxels outside the mask will be filled with zeros.
* If no masking option is given, then all voxels
  will be processed.

z-mask %s)r   r   r   zGenerate a mask automaticallyr%   z	-automask)r   rf   r   zBlur (inside the mask only) with a filter that has
width (FWHM) of fff millimeters.
Spatial blurring (if done) is after the time
series filtering.z-blur %gzZ
Normalize each output time series to have sum of
squares = 1. This is the LAST operation.z-normNrS   )r!   r"   r#   r   r;   rl   Zcensorr   r   r   Zcensortrr?   Zcenmodeconcatr)   ZnoblockZortr'   r(   r   ZdsortrJ  r&   rK  ZstopbandZTRr%   r+   r   Znormr,   r,   r,   r-   re  ?  s   
re  c               @   s   e Zd ZdZdZeZeZdS )TProjecta  
    This program projects (detrends) out various 'nuisance' time series from
    each voxel in the input dataset.  Note that all the projections are done
    via linear regression, including the frequency-based options such
    as ``-passband``.  In this way, you can bandpass time-censored data, and at
    the same time, remove other time series of no interest
    (e.g., physiological estimates, motion parameters).
    Shifts voxel time series from input so that seperate slices are aligned to
    the same temporal origin.

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> tproject = afni.TProject()
    >>> tproject.inputs.in_file = 'functional.nii'
    >>> tproject.inputs.bandpass = (0.00667, 99999)
    >>> tproject.inputs.polort = 3
    >>> tproject.inputs.automask = True
    >>> tproject.inputs.out_file = 'projected.nii.gz'
    >>> tproject.cmdline
    '3dTproject -input functional.nii -automask -bandpass 0.00667 99999 -polort 3 -prefix projected.nii.gz'
    >>> res = tproject.run()  # doctest: +SKIP

    See Also
    --------
    For complete details, see the `3dTproject Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTproject.html>`__

    Z
3dTprojectN)	r!   r"   r#   r$   r_   re  r`   r   rT   r,   r,   r,   r-   rg    s   rg  c               @   s   e Zd Zeddd9ddddZeddd	d
dZedddZej	dddgdZ
ejdddg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$d%d&d'd(
ed)d*d+gdZejedd,ejej	d-d.d/gdZejd0d1dd2d3Zejd4d5dZejd6d7dZd8S );TShiftInputSpeczinput file to 3dTshiftz%sr   TF)r   r   rk   r/   r   r0   z	%s_tshiftzoutput image file namez
-prefix %sr;   )rc   r   r   rd   zTmanually set the TR. You can attach suffix "s" for seconds or "ms" for milliseconds.z-TR %s)r   r   z%align each slice to given time offsetz	-tzero %stslice)r   r   rf   z.align each slice to time offset of given slicez	-slice %stzeroz(ignore the first set of points specifiedz
-ignore %sr   rq   rr   rs   rw   zLdifferent interpolation methods (see 3dTshift for details) default = Fourierz-%szalt+zZaltpluszalt+z2zalt-zZaltminuszalt-z2zseq+zZseqpluszseq-zZseqminusz:use specified slice time pattern rather than one in headerz-tpattern %sslice_timing)r   z=time offsets from the volume acquisition onset for each slicez-tpattern @%stpatternkzk-aB  Direction in which slice_timing is specified (default: k). If negative,slice_timing is defined in reverse order, that is, the first entry corresponds to the slice with the largest index, and the final entry corresponds to slice index zero. Only in effect when slice_timing is passed as list, not when it is passed as file.)r5   r   z1Before shifting, remove the mean and linear trendz-rltzMBefore shifting, remove the mean and linear trend and later put back the meanz-rlt+NrS   )r   rq   rr   rs   rw   )r!   r"   r#   r   r;   rl   r   r   r   r&   rj  r'   ri  ignorer?   interpr=   rl  r   rk  slice_encoding_directionr)   ZrltZrltplusr,   r,   r,   r-   rh     sv   





rh  c               @   s   e Zd ZeddZdS )TShiftOutputSpecz9AFNI formatted timing file, if ``slice_timing`` is a list)r   N)r!   r"   r#   r   timing_filer,   r,   r,   r-   rq  r  s   rq  c                   s@   e Zd ZdZdZeZeZ fddZ	dd Z
 fddZ  ZS )	TShiftaW  Shifts voxel time series from input so that seperate slices are aligned
    to the same temporal origin.

    For complete details, see the `3dTshift Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTshift.html>`_

    Examples
    --------
    Slice timing details may be specified explicitly via the ``slice_timing``
    input:

    >>> from nipype.interfaces import afni
    >>> TR = 2.5
    >>> tshift = afni.TShift()
    >>> tshift.inputs.in_file = 'functional.nii'
    >>> tshift.inputs.tzero = 0.0
    >>> tshift.inputs.tr = '%.1fs' % TR
    >>> tshift.inputs.slice_timing = list(np.arange(40) / TR)
    >>> tshift.cmdline
    '3dTshift -prefix functional_tshift -tpattern @slice_timing.1D -TR 2.5s -tzero 0.0 functional.nii'

    When the ``slice_timing`` input is used, the ``timing_file`` output is populated,
    in this case with the generated file.

    >>> tshift._list_outputs()['timing_file']  # doctest: +ELLIPSIS
    '.../slice_timing.1D'

    >>> np.loadtxt(tshift._list_outputs()['timing_file']).tolist()[:5]
    [0.0, 0.4, 0.8, 1.2, 1.6]

    If ``slice_encoding_direction`` is set to ``'k-'``, the slice timing is reversed:

    >>> tshift.inputs.slice_encoding_direction = 'k-'
    >>> tshift.cmdline
    '3dTshift -prefix functional_tshift -tpattern @slice_timing.1D -TR 2.5s -tzero 0.0 functional.nii'
    >>> np.loadtxt(tshift._list_outputs()['timing_file']).tolist()[:5]
    [15.6, 15.2, 14.8, 14.4, 14.0]

    This method creates a ``slice_timing.1D`` file to be passed to ``3dTshift``.
    A pre-existing slice-timing file may be used in the same way:

    >>> tshift = afni.TShift()
    >>> tshift.inputs.in_file = 'functional.nii'
    >>> tshift.inputs.tzero = 0.0
    >>> tshift.inputs.tr = '%.1fs' % TR
    >>> tshift.inputs.slice_timing = 'slice_timing.1D'
    >>> tshift.cmdline
    '3dTshift -prefix functional_tshift -tpattern @slice_timing.1D -TR 2.5s -tzero 0.0 functional.nii'

    When a pre-existing file is provided, ``timing_file`` is simply passed through.

    >>> tshift._list_outputs()['timing_file']  # doctest: +ELLIPSIS
    '.../slice_timing.1D'

    Alternatively, pre-specified slice timing patterns may be specified with the
    ``tpattern`` input.
    For example, to specify an alternating, ascending slice timing pattern:

    >>> tshift = afni.TShift()
    >>> tshift.inputs.in_file = 'functional.nii'
    >>> tshift.inputs.tzero = 0.0
    >>> tshift.inputs.tr = '%.1fs' % TR
    >>> tshift.inputs.tpattern = 'alt+z'
    >>> tshift.cmdline
    '3dTshift -prefix functional_tshift -tpattern alt+z -TR 2.5s -tzero 0.0 functional.nii'

    For backwards compatibility, ``tpattern`` may also take filenames prefixed
    with ``@``.
    However, in this case, filenames are not validated, so this usage will be
    deprecated in future versions of Nipype.

    >>> tshift = afni.TShift()
    >>> tshift.inputs.in_file = 'functional.nii'
    >>> tshift.inputs.tzero = 0.0
    >>> tshift.inputs.tr = '%.1fs' % TR
    >>> tshift.inputs.tpattern = '@slice_timing.1D'
    >>> tshift.cmdline
    '3dTshift -prefix functional_tshift -tpattern @slice_timing.1D -TR 2.5s -tzero 0.0 functional.nii'

    In these cases, ``timing_file`` is undefined.

    >>> tshift._list_outputs()['timing_file']  # doctest: +ELLIPSIS
    <undefined>

    In any configuration, the interface may be run as usual:

    >>> res = tshift.run()  # doctest: +SKIP
    Z3dTshiftc                sL   |dkr|j drtjd n|dkr8t|tr8| j }tt| j|||S )Nrl  @zVPassing a file prefixed by "@" will be deprecated; please use the `slice_timing` inputrk  )	
startswithifloggerwarning
isinstancer   _write_slice_timingr   rs  r&  )r\   r   r'  r   )r   r,   r-   r&    s    zTShift._format_argc             C   sV   t | jj}| jjjdr"|j  d}t|d}|jdjt	t
| W d Q R X |S )N-zslice_timing.1Dr  	)r   rW   rk  rp  endswithreverser  r  rX   mapstr)r\   rk  fnameZfobjr,   r,   r-   ry    s     zTShift._write_slice_timingc                sR   t t| j }t| jjrNt| jjtr:tj	j
d|d< ntj	j
| jj|d< |S )Nzslice_timing.1Drr  )r   rs  r^   r   rW   rk  rx  r   r   r   r   )r\   r]   )r   r,   r-   r^     s    zTShift._list_outputs)r!   r"   r#   r$   r_   rh  r`   rq  rT   r&  ry  r^   r   r,   r,   )r   r-   rs  v  s   X

rs  c               @   s   e Zd Zed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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ZejdddZd S )"TSmoothInputSpeczinput file to 3dTSmoothz%sr   TF)r   r   rk   r/   r   r0   z	%s_smoothzoutput file from 3dTSmoothz
-prefix %sr;   )rc   r   r   rd   z(Sets the data type of the output datasetz	-datum %s)r   r   zY3 point linear filter: :math:`0.15\,a + 0.70\,b + 0.15\,c` [This is the default smoother]z-linz$3 point median filter: median(a,b,c)z-medza3 point order statistics filter::math:`0.15\,min(a,b,c) + 0.70\,median(a,b,c) + 0.15\,max(a,b,c)`z-osfzt3 point linear filter: :math:`0.5\,(1-m)\,a + m\,b + 0.5\,(1-m)\,c`. Here, 'm' is a number strictly between 0 and 1.z-3lin %dz-hamming %dz?Use N point Hamming windows. (N must be odd and bigger than 1.))r   r   z-blackman %dz@Use N point Blackman windows. (N must be odd and bigger than 1.)z
-custom %sz>odd # of coefficients must be in a single column in ASCII filez-adaptive %dzOuse adaptive mean filtering of width N (where N must be odd and bigger than 3).NrS   )r!   r"   r#   r   r;   rl   r   r   r   r)   ZlinZmedZosfr'   Zlin3ZhammingZblackmanZcustomZadaptiver,   r,   r,   r-   r    sH   
r  c               @   s   e Zd ZdZdZeZeZdS )TSmootha  Smooths each voxel time series in a 3D+time dataset and produces
    as output a new 3D+time dataset (e.g., lowpass filter in time).

    For complete details, see the `3dTsmooth Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTSmooth.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> from nipype.testing import  example_data
    >>> smooth = afni.TSmooth()
    >>> smooth.inputs.in_file = 'functional.nii'
    >>> smooth.inputs.adaptive = 5
    >>> smooth.cmdline
    '3dTsmooth -adaptive 5 -prefix functional_smooth functional.nii'
    >>> res = smooth.run()  # doctest: +SKIP

    Z	3dTsmoothN)	r!   r"   r#   r$   r_   r  r`   r   rT   r,   r,   r,   r-   r  '  s   r  c               @   s   e Zd Zeddd3ddddZejejeddejedddd	d
Z	edddddZ
eddd4ddZejddd5dZedddddd6d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d'd(d)ddd*Zejd7d0d1d
Zd2S )8VolregInputSpeczinput file to 3dvolregz%sr   TF)r   r   rk   r/   r   r0   )r   zYweights for each voxel specified by a file with an optional volume number (defaults to 0)z-weight '%s[%d]')r   r   z	%s_volregzoutput image file namez
-prefix %sr;   )rc   r   r   rd   zbase file for registrationz-base %sr*  )r   r   rk   r   z7Zeropad around the edges by 'n' voxels during rotationsz-zpad %dr)  )r   r   rk   z%s_md.1Dzmax displacement output filez-maxdisp1D %sr   )rc   r   r   rd   r   rk   z%s.1Dz"1D movement parameters output filez
-1Dfile %s)rc   r   r   rd   r   z(more detailed description of the processz-verbosez$time shift to mean slice time offsetz	-tshift 0z&copy base file origin coords to outputz-twodupz%s.aff12.1DzSave the matrix transformationz-1Dmatrix_save %s)rc   r   r   r   rd   r   rr   rw   rs   rq   z0spatial interpolation methods [default = heptic]z-%sNrS   ir-  r,  )r   rr   rw   rs   rq   )r!   r"   r#   r   r;   r   r=   rJ  r'   in_weight_volumerl   Zbasefilezpad	md1d_filer   r)   r   Z	timeshiftZ
copyoriginoned_matrix_saver?   ro  r,   r,   r,   r-   r  @  sh   


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dS )VolregOutputSpeczregistered fileT)r   r   zmax displacement info filezmovement parameters info filez(matrix transformation from base to inputN)r!   r"   r#   r   rl   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	  Z
S )Volrega  Register input volumes to a base volume using AFNI 3dvolreg command

    For complete details, see the `3dvolreg Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dvolreg.html>`_

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> volreg = afni.Volreg()
    >>> volreg.inputs.in_file = 'functional.nii'
    >>> volreg.inputs.args = '-Fourier -twopass'
    >>> volreg.inputs.zpad = 4
    >>> volreg.inputs.outputtype = 'NIFTI'
    >>> volreg.cmdline  # doctest: +ELLIPSIS
    '3dvolreg -Fourier -twopass -1Dfile functional.1D -1Dmatrix_save functional.aff12.1D -prefix functional_volreg.nii -zpad 4 -maxdisp1D functional_md.1D functional.nii'
    >>> res = volreg.run()  # doctest: +SKIP

    >>> from nipype.interfaces import afni
    >>> volreg = afni.Volreg()
    >>> volreg.inputs.in_file = 'functional.nii'
    >>> volreg.inputs.interp = 'cubic'
    >>> volreg.inputs.verbose = True
    >>> volreg.inputs.zpad = 1
    >>> volreg.inputs.basefile = 'functional.nii'
    >>> volreg.inputs.out_file = 'rm.epi.volreg.r1'
    >>> volreg.inputs.oned_file = 'dfile.r1.1D'
    >>> volreg.inputs.oned_matrix_save = 'mat.r1.tshift+orig.1D'
    >>> volreg.cmdline
    '3dvolreg -cubic -1Dfile dfile.r1.1D -1Dmatrix_save mat.r1.tshift+orig.1D -prefix rm.epi.volreg.r1 -verbose -base functional.nii -zpad 1 -maxdisp1D functional_md.1D functional.nii'
    >>> res = volreg.run()  # doctest: +SKIP

    Z3dvolregc                s0   |dkrt |t r|df}tt| j|||S )Nr  r   )rx  tupler   r  r&  )r\   r   r'  r   )r   r,   r-   r&    s    zVolreg._format_arg)r!   r"   r#   r$   r_   r  r`   r  rT   r&  r   r,   r,   )r   r-   r    s
   "r  c               @   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ddddZ
eddddZejdddZejd+dddZe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'gd(Zd)S ),WarpInputSpeczinput file to 3dWarpz%sr   TF)r   r   rk   r/   r   r0   z%s_warpzoutput image file namez
-prefix %sr;   )rc   r   r   rd   r   z*transform dataset from Talairach to MNI152z-tta2mni)r   r   z*transform dataset from MNI152 to Talaraichz-mni2ttaz%apply transformation from 3dWarpDrivez-matparent %s)r   r   r   zlRead in the oblique transformation matrix from an oblique dataset and make cardinal dataset oblique to matchz-oblique_parent %sz*transform dataset from oblique to cardinalz
-deobliquerq   rr   NNrs   z0spatial interpolation methods [default = linear]z-%szcopy grid of specified datasetz-gridset %szspecify grid of this size (mm)z-newgrid %fz5pad input dataset with N planes of zero on all sides.z-zpad %dz)Print out some information along the way.z-verbzsave warp as .mat filer   )r   r  NrS   )rq   rr   r  rs   )r!   r"   r#   r   r;   rl   r   r)   Ztta2mniZmni2ttaZ	matparentZoblique_parentZ	deobliquer?   ro  Zgridsetr&   r   r'   r  r   	save_warpr,   r,   r,   r-   r    sN   




r  c               @   s"   e Zd ZedddZeddZdS )WarpOutputSpeczWarped file.T)r   r   zwarp transform .mat file)r   N)r!   r"   r#   r   rl   	warp_filer,   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 )
Warpa]  Use 3dWarp for spatially transforming a dataset.

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> warp = afni.Warp()
    >>> warp.inputs.in_file = 'structural.nii'
    >>> warp.inputs.deoblique = True
    >>> warp.inputs.out_file = 'trans.nii.gz'
    >>> warp.cmdline
    '3dWarp -deoblique -prefix trans.nii.gz structural.nii'
    >>> res = warp.run()  # doctest: +SKIP

    >>> warp_2 = afni.Warp()
    >>> warp_2.inputs.in_file = 'structural.nii'
    >>> warp_2.inputs.newgrid = 1.0
    >>> warp_2.inputs.out_file = 'trans.nii.gz'
    >>> warp_2.cmdline
    '3dWarp -newgrid 1.000000 -prefix trans.nii.gz structural.nii'
    >>> res = warp_2.run()  # doctest: +SKIP

    See Also
    --------
    For complete details, see the `3dWarp Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dWarp.html>`__.

    Z3dWarpr   c                sJ   t t| j||}| jjrFdd l}| j d }|j||jgt	dd |S )Nr   r  z%s)fmt)
r   r  r  rW   r  numpyr^   Zsavetxtr   r  )r\   r   r	  npr  )r   r,   r-   r    s    zWarp._run_interfacec                s0   t t| j }| jjr,t|d ddd|d< |S )Nrl   z_transform.matF)rC   use_extr  )r   r  r^   rW   r  r   )r\   r]   )r   r,   r-   r^   !  s
    zWarp._list_outputsr   )r  )r!   r"   r#   r$   r_   r  r`   r  rT   r  r^   r   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dZedd	d
gddZejdddZ	ejdddZ
ejdddgdZejdddZejdddg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ej d*d+d,d,d-gd.Zejej ej fd/d0 ejedd1ej fd2d3d4gdZed5d6d$Zejej d7d8d9d:d;Zejej d<d=d9d:d;Zed>d?ddd@ZejdAdBdZejdCdDdZ ejdEdFdZ!ejedddGdHdIdJgdZ"ejdKdLdJgdZ#ejdMdNdZ$ejdKdOdJgddPZ%edQdRdddJdgdSZ&ejdTdUdVdJdgdZ'ejdWdXdYdZd[d\dd]gdZ(ejd^d_d`dagdZ)ejdbdcdZ*ejdddedZ+ejdfdgdJd]dhgdZ,ejdidjdZ-ejdkdld]dmgdZ.ejdndodVgdZ/ejdpdqdrd`gdZ0ejdsdtdrdagdZ1ejdudvdwgdZ2ejdxdydzgdZ3ejd{d|dZ4ejd}d~dddddgddPZ5ejdddddddgdZ6ejdddddddgdZ7ejdddddddgdZ8ejdddddddgdZ9dS )QwarpInputSpeczASource image (opposite phase encoding direction than base image).z
-source %sTF)r   r   r/   r   r0   zABase image (opposite phase encoding direction than source image).z-base %sz
-prefix %szppp_%sr;   a  Sets the prefix/suffix for the output datasets.

* The source dataset is warped to match the base
  and gets prefix 'ppp'. (Except if '-plusminus' is used
* The final interpolation to this output dataset is
  done using the 'wsinc5' method.  See the output of
  3dAllineate -HELP
  (in the "Modifying '-final wsinc5'" section) for
  the lengthy technical details.
* The 3D warp used is saved in a dataset with
  prefix 'ppp_WARP' -- this dataset can be used
  with 3dNwarpApply and 3dNwarpCat, for example.
* To be clear, this is the warp from source dataset
  coordinates to base dataset coordinates, where the
  values at each base grid point are the xyz displacments
  needed to move that grid point's xyz values to the
  corresponding xyz values in the source dataset:
  base( (x,y,z) + WARP(x,y,z) ) matches source(x,y,z)
  Another way to think of this warp is that it 'pulls'
  values back from source space to base space.
* 3dNwarpApply would use 'ppp_WARP' to transform datasets
  aligned with the source dataset to be aligned with the
  base dataset.

**If you do NOT want this warp saved, use the option '-nowarp'**.
(However, this warp is usually the most valuable possible output!)

* If you want to calculate and save the inverse 3D warp,
  use the option '-iwarp'.  This inverse warp will then be
  saved in a dataset with prefix 'ppp_WARPINV'.
* This inverse warp could be used to transform data from base
  space to source space, if you need to do such an operation.
* You can easily compute the inverse later, say by a command like
  3dNwarpCat -prefix Z_WARPINV 'INV(Z_WARP+tlrc)'
  or the inverse can be computed as needed in 3dNwarpApply, like
  3dNwarpApply -nwarp 'INV(Z_WARP+tlrc)' -source Dataset.nii ...

)r   rc   rd   r   a  This option simply resamples the source dataset to match the
base dataset grid.  You can use this if the two datasets
overlap well (as seen in the AFNI GUI), but are not on the
same 3D grid.

* If they don't overlap well, allineate them first
* The reampling here is done with the
  'wsinc5' method, which has very little blurring artifact.
* If the base and source datasets ARE on the same 3D grid,
  then the -resample option will be ignored.
* You CAN use -resample with these 3dQwarp options:
  -plusminus  -inilev  -iniwarp  -duplo

z	-resample)r   r   zThis option will make 3dQwarp run 3dAllineate first, to align the source dataset to the base with an affine transformation. It will then use that alignment as a starting point for the nonlinear warping.z
-allineatezBadd extra options to the 3dAllineate command to be run by 3dQwarp.z-allineate_opts %s	allineate)r   r   r  zDo not save the _WARP file.z-nowarpz&Do compute and save the _WARPINV file.z-iwarp	plusminus)r   r   rf   zUse strict Pearson correlation for matching.Not usually recommended, since the 'clipped Pearson' methodused by default will reduce the impact of outlier values.z-pearaB  Replace negative values in either input volume with 0.

* If there ARE negative input values, and you do NOT use -noneg,
  then strict Pearson correlation will be used, since the 'clipped'
  method only is implemented for non-negative volumes.
* '-noneg' is not the default, since there might be situations where
  you want to align datasets with positive and negative values mixed.
* But, in many cases, the negative values in a dataset are just the
  result of interpolation artifacts (or other peculiarities), and so
  they should be ignored.  That is what '-noneg' is for.

z-nonegaA  Replace negative values in either input volume with 0.

* If there ARE negative input values, and you do NOT use -noneg,
  then strict Pearson correlation will be used, since the 'clipped'
  method only is implemented for non-negative volumes.
* '-noneg' is not the default, since there might be situations where
  you want to align datasets with positive and negative values mixed.
* But, in many cases, the negative values in a dataset are just the
  result of interpolation artifacts (or other peculiarities), and so
  they should be ignored. That is what '-noneg' is for.

z
-nopenaltyz
-penfac %fa3  Use this value to weight the penalty.
The default value is 1. Larger values mean the
penalty counts more, reducing grid distortions,
insha'Allah; '-nopenalty' is the same as '-penfac 0'.
In 23 Sep 2013 Zhark increased the default value of
the penalty by a factor of 5, and also made it get
progressively larger with each level of refinement.
Thus, warping results will vary from earlier instances
of 3dQwarp.

* The progressive increase in the penalty at higher levels
  means that the 'cost function' can actually look like the
  alignment is getting worse when the levels change.
* IF you wish to turn off this progression, for whatever
  reason (e.g., to keep compatibility with older results),
  use the option '-penold'.To be completely compatible with
  the older 3dQwarp, you'll also have to use '-penfac 0.2'.

)r   r   zIf you want a binary weight (the old default), use this option.That is, each voxel in the base volume automask will beweighted the same in the computation of the cost functional.z	-noweightzInstead of computing the weight from the base dataset,directly input the weight volume from dataset 'www'.Useful if you know what over parts of the base image youwant to emphasize or de-emphasize the matching functional.z
-weight %s)r   r   r   a  "``-wball x y z r f``
Enhance automatic weight from '-useweight' by a factor
of 1+f\*Gaussian(FWHM=r) centered in the base image at
DICOM coordinates (x,y,z) and with radius 'r'. The
goal of this option is to try and make the alignment
better in a specific part of the brain.
Example:  -wball 0 14 6 30 40
to emphasize the thalamic area (in MNI/Talairach space).

* The 'r' parameter must be positive!
* The 'f' parameter must be between 1 and 100 (inclusive).
* '-wball' does nothing if you input your own weight
  with the '-weight' option.
* '-wball' does change the binary weight created by
  the '-noweight' option.
* You can only use '-wball' once in a run of 3dQwarp.

**The effect of '-wball' is not dramatic.** The example
above makes the average brain image across a collection
of subjects a little sharper in the thalamic area, which
might have some small value.  If you care enough about
alignment to use '-wball', then you should examine the
results from 3dQwarp for each subject, to see if the
alignments are good enough for your purposes.z	-wball %sr)  wmask)r   r   minlenmaxlenrf   z-bpass %f %f)r   )r   a  Similar to '-wball', but here, you provide a dataset 'ws'
that indicates where to increase the weight.

* The 'ws' dataset must be on the same 3D grid as the base dataset.
* 'ws' is treated as a mask -- it only matters where it
  is nonzero -- otherwise, the values inside are not used.
* After 'ws' comes the factor 'f' by which to increase the
  automatically computed weight.  Where 'ws' is nonzero,
  the weighting will be multiplied by (1+f).
* As with '-wball', the factor 'f' should be between 1 and 100.

z-wpass %s %fwballz-wtprefix %sz,Write the weight volume to disk as a dataseta  Gaussian blur the input images by 'bb' (FWHM) voxels before
doing the alignment (the output dataset will not be blurred).
The default is 2.345 (for no good reason).

* Optionally, you can provide 2 values for 'bb', and then
  the first one is applied to the base volume, the second
  to the source volume.
  e.g., '-blur 0 3' to skip blurring the base image
  (if the base is a blurry template, for example).
* A negative blur radius means to use 3D median filtering,
  rather than Gaussian blurring.  This type of filtering will
  better preserve edges, which can be important in alignment.
* If the base is a template volume that is already blurry,
  you probably don't want to blur it again, but blurring
  the source volume a little is probably a good idea, to
  help the program avoid trying to match tiny features.
* Note that -duplo will blur the volumes some extra
  amount for the initial small-scale warping, to make
  that phase of the program converge more rapidly.

z-blur %sr   r   )r   r   r  r  a  Use progressive blurring; that is, for larger patch sizes,
the amount of blurring is larger.  The general idea is to
avoid trying to match finer details when the patch size
and incremental warps are coarse.  When '-blur' is used
as well, it sets a minimum amount of blurring that will
be used. [06 Aug 2014 -- '-pblur' may become the default someday].

* You can optionally give the fraction of the patch size that
  is used for the progressive blur by providing a value between
  0 and 0.25 after '-pblur'.  If you provide TWO values, the
  the first fraction is used for progressively blurring the
  base image and the second for the source image.  The default
  parameters when just '-pblur' is given is the same as giving
  the options as '-pblur 0.09 0.09'.
* '-pblur' is useful when trying to match 2 volumes with high
  amounts of detail; e.g, warping one subject's brain image to
  match another's, or trying to warp to match a detailed template.
* Note that using negative values with '-blur' means that the
  progressive blurring will be done with median filters, rather
  than Gaussian linear blurring.

Note: The combination of the -allineate and -pblur options will make
the results of using 3dQwarp to align to a template somewhat
less sensitive to initial head position and scaling.z	-pblur %sa>  Here, 'ee' is a dataset to specify a mask of voxelsto EXCLUDE from the analysis -- all voxels in 'ee'that are NONZERO will not be used in the alignment.The base image always automasked -- the emask isextra, to indicate voxels you definitely DON'T wantincluded in the matching process, even if they areinside the brain.z	-emask %s)r   r   r   r0   z%Warp will not displace in x directionz-noXdisz%Warp will not displace in y directionz-noYdisz%Warp will not displace in z directionz-noZdis)r   r0   a  A dataset with an initial nonlinear warp to use.

* If this option is not used, the initial warp is the identity.
* You can specify a catenation of warps (in quotes) here, as in
  program 3dNwarpApply.
* As a special case, if you just input an affine matrix in a .1D
  file, that will work also -- it is treated as giving the initial
  warp via the string "IDENT(base_dataset) matrix_file.aff12.1D".
* You CANNOT use this option with -duplo !!
* -iniwarp is usually used with -inilev to re-start 3dQwarp from
  a previous stopping point.

z-iniwarp %sduploa  The initial refinement 'level' at which to start.

* Usually used with -iniwarp; CANNOT be used with -duplo.
* The combination of -inilev and -iniwarp lets you take the
  results of a previous 3dQwarp run and refine them further:
  Note that the source dataset in the second run is the SAME as
  in the first run.  If you don't see why this is necessary,
  then you probably need to seek help from an AFNI guru.

z
-inilev %da4  The value of mm should be an odd integer.

* The default value of mm is 25.
* For more accurate results than mm=25, try 19 or 13.
* The smallest allowed patch size is 5.
* You may want stop at a larger patch size (say 7 or 9) and use
  the -Qfinal option to run that final level with quintic warps,
  which might run faster and provide the same degree of warp detail.
* Trying to make two different brain volumes match in fine detail
  is usually a waste of time, especially in humans.  There is too
  much variability in anatomy to match gyrus to gyrus accurately.
  For this reason, the default minimum patch size is 25 voxels.
  Using a smaller '-minpatch' might try to force the warp to
  match features that do not match, and the result can be useless
  image distortions -- another reason to LOOK AT THE RESULTS.

z-minpatch %dz
-maxlev %d)r   r   rf   rk   a  This option provides an alternate way to specify the patch
grid sizes used in the warp optimization process. 'gl' is
a 1D file with a list of patches to use -- in most cases,
you will want to use it in the following form:
``-gridlist '1D: 0 151 101 75 51'``

* Here, a 0 patch size means the global domain. Patch sizes
  otherwise should be odd integers >= 5.
* If you use the '0' patch size again after the first position,
  you will actually get an iteration at the size of the
  default patch level 1, where the patch sizes are 75% of
  the volume dimension.  There is no way to force the program
  to literally repeat the sui generis step of lev=0.

z-gridlist %s)r   r   r   r0   rf   z
This option lets you save the output warps from each level"
of the refinement process.  Mostly used for experimenting."
Will only save all the outputs if the program terminates"
normally -- if it crashes, or freezes, then all these"
warps are lost.z-allsave	nopadWARPa  Start off with 1/2 scale versions of the volumes,"
for getting a speedy coarse first alignment."

* Then scales back up to register the full volumes."
  The goal is greater speed, and it seems to help this"
  positively piggish program to be more expeditious."
* However, accuracy is somewhat lower with '-duplo',"
  for reasons that currenly elude Zhark; for this reason,"
  the Emperor does not usually use '-duplo'.

z-duplogridlistmaxlevinileviniwarpallsavea
  Iterate more times, which can help when the volumes are
hard to align at all, or when you hope to get a more precise
alignment.

* Slows the program down (possibly a lot), of course.
* When you combine '-workhard'  with '-duplo', only the
  full size volumes get the extra iterations.
* For finer control over which refinement levels work hard,
  you can use this option in the form (for example) ``-workhard:4:7``
  which implies the extra iterations will be done at levels
  4, 5, 6, and 7, but not otherwise.
* You can also use '-superhard' to iterate even more, but
  this extra option will REALLY slow things down.

  * Under most circumstances, you should not need to use either
    ``-workhard`` or ``-superhard``.
  * The fastest way to register to a template image is via the
    ``-duplo`` option, and without the ``-workhard`` or ``-superhard`` options.
  * If you use this option in the form '-Workhard' (first letter
    in upper case), then the second iteration at each level is
    done with quintic polynomial warps.

z	-workhardZboxoptballopta  At the finest patch size (the final level), use Hermite
quintic polynomials for the warp instead of cubic polynomials.

* In a 3D 'patch', there are 2x2x2x3=24 cubic polynomial basis
  function parameters over which to optimize (2 polynomials
  dependent on each of the x,y,z directions, and 3 different
  directions of displacement).
* There are 3x3x3x3=81 quintic polynomial parameters per patch.
* With -Qfinal, the final level will have more detail in
  the allowed warps, at the cost of yet more CPU time.
* However, no patch below 7x7x7 in size will be done with quintic
  polynomials.
* This option is also not usually needed, and is experimental.

z-QfinalzUse Hermite quintic polynomials at all levels.

* Very slow (about 4 times longer).  Also experimental.
* Will produce a (discrete representation of a) C2 warp.

z-Qonlya  Normally, the warp displacements dis(x) are defined to match
base(x) to source(x+dis(x)).  With this option, the match
is between base(x-dis(x)) and source(x+dis(x)) -- the two
images 'meet in the middle'.

* One goal is to mimic the warping done to MRI EPI data by
  field inhomogeneities, when registering between a 'blip up'
  and a 'blip down' down volume, which will have opposite
  distortions.
* Define Wp(x) = x+dis(x) and Wm(x) = x-dis(x).  Then since
  base(Wm(x)) matches source(Wp(x)), by substituting INV(Wm(x))
  wherever we see x, we have base(x) matches source(Wp(INV(Wm(x))));
  that is, the warp V(x) that one would get from the 'usual' way
  of running 3dQwarp is V(x) = Wp(INV(Wm(x))).
* Conversely, we can calculate Wp(x) in terms of V(x) as follows:
  If V(x) = x + dv(x), define Vh(x) = x + dv(x)/2;
  then Wp(x) = V(INV(Vh(x)))
* With the above formulas, it is possible to compute Wp(x) from
  V(x) and vice-versa, using program 3dNwarpCalc.  The requisite
  commands are left as an exercise for the aspiring AFNI Jedi Master.
* You can use the semi-secret '-pmBASE' option to get the V(x)
  warp and the source dataset warped to base space, in addition to
  the Wp(x) '_PLUS' and Wm(x) '_MINUS' warps.

  * Alas: -plusminus does not work with -duplo or -allineate :-(
  * However, you can use -iniwarp with -plusminus :-)
  * The outputs have _PLUS (from the source dataset) and _MINUS
    (from the base dataset) in their filenames, in addition to
    the prefix.  The -iwarp option, if present, will be ignored.

z
-plusminusiwarpa\  Do NOT use zero-padding on the 3D base and source images.
[Default == zero-pad, if needed]

* The underlying model for deformations goes to zero at the
  edge of the volume being warped.  However, if there is
  significant data near an edge of the volume, then it won't
  get displaced much, and so the results might not be good.
* Zero padding is designed as a way to work around this potential
  problem.  You should NOT need the '-nopad' option for any
  reason that Zhark can think of, but it is here to be symmetrical
  with 3dAllineate.
* Note that the output (warped from source) dataset will be on the
  base dataset grid whether or not zero-padding is allowed.  However,
  unless you use the following option, allowing zero-padding (i.e.,
  the default operation) will make the output WARP dataset(s) be
  on a larger grid (also see '-expad' below).

z-nopadzIf for some reason you require the warp volume tomatch the base volume, then use this option to have the outputWARP dataset(s) truncated.z
-nopadWARPexpada  This option instructs the program to pad the warp by an extra'EE' voxels (and then 3dQwarp starts optimizing it).This option is seldom needed, but can be useful if youmight later catenate the nonlinear warp -- via 3dNwarpCat --with an affine transformation that contains a large shift.Under that circumstance, the nonlinear warp might be shiftedpartially outside its original grid, so expanding that gridcan avoid this problem.Note that this option perforce turns off '-nopadWARP'.z	-expad %da  Normally, the incremental warp parameters are optimized insidea rectangular 'box' (24 dimensional for cubic patches, 81 forquintic patches), whose limits define the amount of distortionallowed at each step.  Using '-ballopt' switches these limitsto be applied to a 'ball' (interior of a hypersphere), whichcan allow for larger incremental displacements.  Use thisoption if you think things need to be able to move farther.z-balloptworkharda  Use the 'box' optimization limits instead of the 'ball'[this is the default at present].Note that if '-workhard' is used, then ball and box optimizationare alternated in the different iterations at each level, sothese two options have no effect in that case.z-boxoptz(more detailed description of the processz-verbr   z5Cut out most of the fun fun fun progress messages :-(z-quietverbzOverwrite outputsz
-overwritea  Local Pearson minimization (i.e., EPI-T1 registration)This option has not be extensively testedIf you use '-lpc', then '-maxlev 0' is automatically set.If you want to go to more refined levels, you can set '-maxlev'This should be set up to have lpc as the second to last argumentand maxlev as the second to last argument, as needed by AFNIUsing maxlev > 1 is not recommended for EPI-T1 alignment.z-lpcro   rn   rp   lpapearzELocal Pearson maximization. This option has not be extensively testedz-lpalpczHellinger distance: a matching function for the adventurousThis option has NOT be extensively tested for usefullnessand should be considered experimental at this infundibulum.z-helzMutual Information: a matching function for the adventurousThis option has NOT be extensively tested for usefullnessand should be considered experimental at this infundibulum.z-mizNormalized Mutual Information: a matching function for the adventurousThis option has NOT been extensively tested for usefullnessand should be considered experimental at this infundibulum.z-nmiNrS   r   ):r!   r"   r#   r   r;   Z	base_filerl   r   r)   Zresampler  r   allineate_optsnowarpr  r  ZnonegZ	nopenaltyr&   ZpenfacZnoweightrt   r   r'   r  rJ  r  rm   r   ZpblurZemaskZnoXdisZnoYdisZnoZdisr  r  Zminpatchr  r  r  r  r  ZQfinalZQonlyr  Znopadr  r  r  Zbaxoptr  r   r   r  r  rp   rn   ro   r,   r,   r,   r-   r  +  sd  '







 	

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dS )QwarpOutputSpeczMWarped source file. If plusminus is used, this is the undistortedsource file.)r   zUndistorted base file.zDisplacement in mm for the source image.If plusminus is used this is the field suceptibility correctionwarp (in 'mm') for source image.zDisplacement in mm for the base image.If plus minus is used, this is the field suceptibility correctionwarp (in 'mm') for base image. This is only output if plusminusor iwarp options are passedzAuto-computed weight volume.N)	r!   r"   r#   r   warped_sourcewarped_basesource_warp	base_warpweightsr,   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 )	Qwarpa`  
    Allineate your images prior to passing them to this workflow.

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> qwarp = afni.Qwarp()
    >>> qwarp.inputs.in_file = 'sub-01_dir-LR_epi.nii.gz'
    >>> qwarp.inputs.nopadWARP = True
    >>> qwarp.inputs.base_file = 'sub-01_dir-RL_epi.nii.gz'
    >>> qwarp.inputs.plusminus = True
    >>> qwarp.cmdline
    '3dQwarp -base sub-01_dir-RL_epi.nii.gz -source sub-01_dir-LR_epi.nii.gz -nopadWARP -prefix ppp_sub-01_dir-LR_epi -plusminus'
    >>> res = qwarp.run()  # doctest: +SKIP

    >>> from nipype.interfaces import afni
    >>> qwarp = afni.Qwarp()
    >>> qwarp.inputs.in_file = 'structural.nii'
    >>> qwarp.inputs.base_file = 'mni.nii'
    >>> qwarp.inputs.resample = True
    >>> qwarp.cmdline
    '3dQwarp -base mni.nii -source structural.nii -prefix ppp_structural -resample'
    >>> res = qwarp.run()  # doctest: +SKIP

    >>> from nipype.interfaces import afni
    >>> qwarp = afni.Qwarp()
    >>> qwarp.inputs.in_file = 'structural.nii'
    >>> qwarp.inputs.base_file = 'epi.nii'
    >>> qwarp.inputs.out_file = 'anatSSQ.nii.gz'
    >>> qwarp.inputs.resample = True
    >>> qwarp.inputs.lpc = True
    >>> qwarp.inputs.verb = True
    >>> qwarp.inputs.iwarp = True
    >>> qwarp.inputs.blur = [0,3]
    >>> qwarp.cmdline
    '3dQwarp -base epi.nii -blur 0.0 3.0 -source structural.nii -iwarp -prefix anatSSQ.nii.gz -resample -verb -lpc'

    >>> res = qwarp.run()  # doctest: +SKIP

    >>> from nipype.interfaces import afni
    >>> qwarp = afni.Qwarp()
    >>> qwarp.inputs.in_file = 'structural.nii'
    >>> qwarp.inputs.base_file = 'mni.nii'
    >>> qwarp.inputs.duplo = True
    >>> qwarp.inputs.blur = [0,3]
    >>> qwarp.cmdline
    '3dQwarp -base mni.nii -blur 0.0 3.0 -duplo -source structural.nii -prefix ppp_structural'

    >>> res = qwarp.run()  # doctest: +SKIP

    >>> from nipype.interfaces import afni
    >>> qwarp = afni.Qwarp()
    >>> qwarp.inputs.in_file = 'structural.nii'
    >>> qwarp.inputs.base_file = 'mni.nii'
    >>> qwarp.inputs.duplo = True
    >>> qwarp.inputs.minpatch = 25
    >>> qwarp.inputs.blur = [0,3]
    >>> qwarp.inputs.out_file = 'Q25'
    >>> qwarp.cmdline
    '3dQwarp -base mni.nii -blur 0.0 3.0 -duplo -source structural.nii -minpatch 25 -prefix Q25'

    >>> res = qwarp.run()  # doctest: +SKIP
    >>> qwarp2 = afni.Qwarp()
    >>> qwarp2.inputs.in_file = 'structural.nii'
    >>> qwarp2.inputs.base_file = 'mni.nii'
    >>> qwarp2.inputs.blur = [0,2]
    >>> qwarp2.inputs.out_file = 'Q11'
    >>> qwarp2.inputs.inilev = 7
    >>> qwarp2.inputs.iniwarp = ['Q25_warp+tlrc.HEAD']
    >>> qwarp2.cmdline
    '3dQwarp -base mni.nii -blur 0.0 2.0 -source structural.nii -inilev 7 -iniwarp Q25_warp+tlrc.HEAD -prefix Q11'

    >>> res2 = qwarp2.run()  # doctest: +SKIP
    >>> res2 = qwarp2.run()  # doctest: +SKIP
    >>> qwarp3 = afni.Qwarp()
    >>> qwarp3.inputs.in_file = 'structural.nii'
    >>> qwarp3.inputs.base_file = 'mni.nii'
    >>> qwarp3.inputs.allineate = True
    >>> qwarp3.inputs.allineate_opts = '-cose lpa -verb'
    >>> qwarp3.cmdline
    "3dQwarp -allineate -allineate_opts '-cose lpa -verb' -base mni.nii -source structural.nii -prefix ppp_structural"

    >>> res3 = qwarp3.run()  # doctest: +SKIP

    See Also
    --------
    For complete details, see the `3dQwarp Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dQwarp.html>`__

    Z3dQwarpc                s.   |dkr|j d| d  S tt| j|||S )Nr  ')r   r   r  r&  )r\   r   r'  r   )r   r,   r-   r&    s    zQwarp._format_argc             C   s  | j  j }t| jjsT| j| jjdd}| jj}|dkrDd}d}qtj	|}d}nJ| jj}t
|j jd|j jdg}|dkrd}d}n||d  }d}tjjtjj|}t||d
|d| |d< | jjst|d| d
|d| |d< | jjrt|d| d
|d| |d< t| jjr6tjj| jj|d< | jjrt|d| d
|d| |d< t|d| d
|d| |d< t|d| d
|d| |d< t|d| d
|d| |d< |S )N_QW)rC   rQ   z.HEADz+tlrcr    z.nii.gzz.niir   F)rC   r  newpathr  Z_WARPr  Z_WARPINVr  r  Z_PLUSZ_MINUSr  Z
_PLUS_WARPZ_MINUS_WARPrS   )rT   rU   r   rW   rl   rV   r;   rZ   r   r[   r4   r   rfindr   r   r`  r   r   r  r  rm   r  )r\   r]   r5  rZ   rR   rC   Zext_indZout_dirr,   r,   r-   r^     s\    








zQwarp._list_outputsc             C   s   |dkr| j | jjddS d S )Nrl   r  )rC   )rV   rW   r;   )r\   r   r,   r,   r-   _gen_filenamec  s    zQwarp._gen_filename)r!   r"   r#   r$   r_   r  r`   r  rT   r&  r^   r  r   r,   r,   )r   r-   r    s   ^Mr  c            	   @   sN   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dddddgdZdS )QwarpPlusMinusInputSpecz@Source image (opposite phase encoding direction than base image)z
-source %sTz1.1.2r;   F)r   r   r   ru   rv   r0   zQwarp.nii.gzz
-prefix %sr   zOutput file)r   rk   r5   r   r   zNormally, the warp displacements dis(x) are defined to matchbase(x) to source(x+dis(x)).  With this option, the matchis between base(x-dis(x)) and source(x+dis(x)) -- the twoimages 'meet in the middle'. For more info, view Qwarp` interfacez
-plusminusr  r  r  )r5   rk   r   r   rf   N)	r!   r"   r#   r   Zsource_filerl   r   r)   r  r,   r,   r,   r-   r  h  s(   r  c               @   s   e Zd ZdZeZdS )QwarpPlusMinusa  A version of 3dQwarp for performing field susceptibility correction
    using two images with opposing phase encoding directions.

    Examples
    --------
    >>> from nipype.interfaces import afni
    >>> qwarp = afni.QwarpPlusMinus()
    >>> qwarp.inputs.in_file = 'sub-01_dir-LR_epi.nii.gz'
    >>> qwarp.inputs.nopadWARP = True
    >>> qwarp.inputs.base_file = 'sub-01_dir-RL_epi.nii.gz'
    >>> qwarp.cmdline
    '3dQwarp -prefix Qwarp.nii.gz -plusminus -base sub-01_dir-RL_epi.nii.gz -source sub-01_dir-LR_epi.nii.gz -nopadWARP'
    >>> res = warp.run()  # doctest: +SKIP

    See Also
    --------
    For complete details, see the `3dQwarp Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dQwarp.html>`__

    N)r!   r"   r#   r$   r  r`   r,   r,   r,   r-   r    s   r  )|r$   r   os.pathr   r   Zutils.filemanipr   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r   	getLoggerrv  r   r.   rF   rO   ra   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   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r"  r#  r(  r2  r3  r6  r8  r9  r;  r?  r@  rA  rX  rY  rZ  r\  r_  ra  rb  rc  rd  re  rg  rh  rq  rs  r  r  r  r  r  r  r  r  r  r  r  r  r  r,   r,   r,   r-   <module>   s   
0(
=n  #
C"!R O+3
#5"/!D68y-6.<($1<% 	1* >$R|5D	.65    r <