3
d                 @   s  d Z ddlZddlZddlmZmZmZ ddlmZm	Z	m
Z
mZmZmZmZ ddlmZmZmZ G d	d
 d
eZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZeZeZG dd  d eZG d!d" d"eZ G d#d$ d$eZ!G d%d& d&eZ"G d'd( d(eZ#G d)d* d*e!Z$G d+d, d,e"Z%G d-d. d.eZ&G d/d0 d0eZ'G d1d2 d2eZ(G d3d4 d4eZ)G d5d6 d6eZ*G d7d8 d8eZ+G d9d: d:eZ,G d;d< d<eZ-G d=d> d>eZ.G d?d@ d@eZ/G dAdB dBeZ0G dCdD dDeZ1G dEdF dFeZ2G dGdH dHeZ3G dIdJ dJeZ4G dKdL dLeZ5G dMdN dNeZ6G dOdP dPeZ7dS )QzThe fsl module provides classes for interfacing with the `FSL
<http://www.fmrib.ox.ac.uk/fsl/index.html>`_ command line tools.  This
was written to work with FSL version 4.1.4.
    N   )fname_presuffixsplit_filenamecopyfile   )TraitedSpec	isdefinedFile	DirectoryInputMultiPathOutputMultiPathtraits   )
FSLCommandFSLCommandInputSpecInfoc               @   s  e Zd ZeddddddZejdddd	dd
ZeddddddZeddddddZ	e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edd&d'd(Zejd)d*d#Zedd+d,d-Zd.S )/DTIFitInputSpecTz"diffusion weighted image data filez-k %sr   )existsdescargstrposition	mandatoryZdtifit_z/base_name that all output files will start withz-o %sr   )r   r   r   
usedefaultzbet binary mask filez-m %sr   zb vectors filez-r %sr   zb values filez-b %s   z-z %dzmin z)r   r   z-Z %dzmax zz-y %dzmin yz-Y %dzmax yz-x %dzmin xz-X %dzmax xzsave the elements of the tensorz--save_tensor)r   r   zoutput sum of squared errorsz--ssezinput counfound regressorsz--cni=%s)r   r   r   z only process small area of brainz--littlebitz--gradnonlin=%szgradient non linearities)r   r   r   N)__name__
__module____qualname__r	   dwir   Str	base_namemaskbvecsbvalsIntZmin_zZmax_zZmin_yZmax_yZmin_xZmax_xBoolsave_tensorsseZcniZ
little_bit
gradnonlin r(   r(   ;/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/fsl/dti.pyr      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edddZedddZ	edd	dZ
edd
dZedddZedddZedddZedddZdS )DTIFitOutputSpecTz*path/name of file with the 1st eigenvector)r   r   z*path/name of file with the 2nd eigenvectorz*path/name of file with the 3rd eigenvectorz)path/name of file with the 1st eigenvaluez)path/name of file with the 2nd eigenvaluez)path/name of file with the 3rd eigenvaluez+path/name of file with the mean diffusivityz0path/name of file with the fractional anisotropyz-path/name of file with the mode of anisotropyzDpath/name of file with the raw T2 signal with no diffusion weightingz+path/name of file with the 4D tensor volumez/path/name of file with the summed squared errorN)r   r   r   r	   ZV1ZV2ZV3ZL1ZL2ZL3ZMDZFAZMOZS0tensorr&   r(   r(   r(   r)   r*   G   s   r*   c               @   s$   e Zd ZdZdZeZeZdd Z	dS )DTIFita  Use FSL  dtifit command for fitting a diffusion tensor model at each
    voxel

    Example
    -------

    >>> from nipype.interfaces import fsl
    >>> dti = fsl.DTIFit()
    >>> dti.inputs.dwi = 'diffusion.nii'
    >>> dti.inputs.bvecs = 'bvecs'
    >>> dti.inputs.bvals = 'bvals'
    >>> dti.inputs.base_name = 'TP'
    >>> dti.inputs.mask = 'mask.nii'
    >>> dti.cmdline
    'dtifit -k diffusion.nii -o TP -m mask.nii -r bvecs -b bvals'

    Zdtifitc             C   s   dddh}| j j| j jd}x,|j D ] \}}t|r<|r<q&|j| q&W | j j }x2t|j	 | D ]}| j
| j jd| d||< qhW |S )NZ
outputtypeenvironargs)r+   r&   _)suffix)inputsr%   r&   itemsr   addoutput_specgetsetkeys
_gen_fnamer   )selfZkeys_to_ignoreZ
opt_outputoutputZ
input_flagoutputskr(   r(   r)   _list_outputsr   s    
zDTIFit._list_outputsN)
r   r   r   __doc___cmdr   
input_specr*   r4   r=   r(   r(   r(   r)   r,   [   s
   r,   c               @   s  e Zd ZedddddZedddddZedddddZedd	dd
dZeddddZ	e
jdddddddZe
jddddddZe
jdddZe
jdddddZe
jdddddd Ze
jdddd!d"d Ze
jdddd#d$d Ze
jdd%dd&d'd Ze
jd(d)dZdEZe
jd,ed-d.Ze
jd/ed0d.ZdFZe
jd4ed5d.Ze
jd6ed7d.Ze
jd8ed9d.Ze
jd:d;dZd<d=gZ e
jd>e d?d.Z!e
jd@e d+g d?d.Z"e
jddAddBdCZ#dDS )GFSLXCommandInputSpecTz	--data=%sz"diffusion weighted image data file)r   r   r   r   z	--mask=%sz&brain binary mask file (i.e. from BET)z
--bvecs=%szb vectors filez
--bvals=%szb values file.z--logdir=%s)r   r   r   r   z--nfibres=%dz-Maximum number of fibres to fit in each voxel)r   lowvaluer   r   r   r   z
--model=%dzfuse monoexponential (1, default, required for single-shell) or multiexponential (2, multi-shell) model)r   r   z
--fudge=%dzARD fudge factori  z--njumps=%dzNum of jumps to be made by MCMC)r   r   r   r   z--burnin=%dz3Total num of jumps at start of MCMC to be discarded)rC   rD   r   r   r   z--burnin_noard=%dz-num of burnin jumps before the ard is imposedz--sampleevery=%dz#Num of jumps for each sample (MCMC)(   z--updateproposalevery=%dz?Num of jumps for each update to the proposal density std (MCMC)z	--seed=%dz'seed for pseudo random number generatorno_ardall_ardz--noardzTurn ARD off on all fibres)r   xorr   z--allardzTurn ARD on on all fibresno_spat
non_linearcnlinearz--nospatz%Initialise with tensor, not spatiallyz--nonlinearz!Initialise with nonlinear fittingz--cnonlinearz-Initialise with constrained nonlinear fittingz--ricianzuse Rician noise modelingf0_noardf0_ardz--f0zINoise floor model: add to the model an unattenuated signal compartment f0z--f0 --ardf0z
--forcedirzJuse the actual directory name given (do not add + to make a new directory))r   r   r   N)rF   rG   )rI   rJ   rK   )$r   r   r   r	   r   r    r!   r"   r
   logdirr   Rangen_fibresEnummodelr#   fudgen_jumpsburn_inZburn_in_no_ardsample_everyZupdate_proposal_everyseedZ_xor_inputs1r$   rF   rG   Z_xor_inputs2rI   rJ   rK   ricianZ_xor_inputs3rL   rM   	force_dirr(   r(   r(   r)   rA      s   
rA   c               @   s   e Zd ZeeddddZeeddddZedddZeeddddZedd	dZ	edd
dZ
eeddddZeeddddZdS )FSLXCommandOutputSpecT)r   z(Mean of PDD distribution in vector form.)r   z-Samples from the distribution on f anisotropyz%Mean of distribution on diffusivity d)r   r   z$Mean of distribution on f anisotropyz7Mean of distribution on T2wbaseline signal intensity S0z<Mean of distribution on tau samples (only with rician noise)zphi samples, per fiberztheta samples, per fiberN)r   r   r   r   r	   dyadsfsamplesmean_dsamplesmean_fsamplesmean_S0samplesmean_tausamples	phsamples	thsamplesr(   r(   r(   r)   rZ     s   
rZ   c                   s2   e Zd ZdZeZeZ fddZdddZ	  Z
S )FSLXCommandz7
    Base support for ``xfibres`` and ``bedpostx``
    c                s.   t j | _tt| j|}|jr*| j| |S )N)osgetcwd_out_dirsuperrc   _run_interfacestderrraise_exception)r9   runtime)	__class__r(   r)   rh   #  s
    

zFSLXCommand._run_interfaceNc             C   sv  | j  j }| jj}|sBt| jjr6tjj| jj}ntjjd}dddddg}ddg}x|D ]}| j	||d	||< q^W t| jj
r| jj
r| j	d
|d	|d
< x|D ]}g ||< qW xNtd|d D ]<}|d j| j	d| |d	 |d j| j	d| |d	 qW xltd|d D ]Z}|d j| j	d| |d	 |d j| j	d| |d	 |d j| j	d| |d	 qW |S )NrN   r[   r\   r^   ra   rb   r]   r_   )cwdr`   r   z
f%dsampleszmean_f%dsampleszdyads%dzph%dsampleszth%dsamples)r4   r5   r1   rP   r   rN   rd   pathabspathr8   rX   rangeappend)r9   out_dirr;   rP   	multi_out
single_outr<   ir(   r(   r)   r=   *  s.    

"zFSLXCommand._list_outputs)N)r   r   r   r>   rA   r@   rZ   r4   rh   r=   __classcell__r(   r(   )rl   r)   rc     s
   rc   c               @   s   e Zd ZeddddZeddddZeddddZeddddZeddZ	e
jdd	d
ddddZe
jd	d
ddddZe
jdddZe
jdddddZe
jddddddZe
jdd	ddddZeddddd	d d!Ze
jd"d#d$dZedd%d&Ze
jd"d'd(Zd)S )*BEDPOSTX5InputSpecTz"diffusion weighted image data file)r   r   r   zbet binary mask filezb vectors filezb values filez--logdir=%s)r   r   r   z-n %dz-Maximum number of fibres to fit in each voxel)r   rC   rD   r   r   r   r   z	-model %dzfuse monoexponential (1, default, required for single-shell) or multiexponential (2, multi-shell) model)r   r   z-w %dzARD fudge factori  z-j %dzNum of jumps to be made by MCMC)r   r   r   r   z-b %dz3Total num of jumps at start of MCMC to be discarded)rC   rD   r   r   r   z-s %dz#Num of jumps for each sample (MCMC)bedpostxzoutput directoryz%s)r   r   r   r   r   Fz-gz-consider gradient nonlinearities, default offz(grad_dev file, if gradnonlin, -g is True)r   r   zUse the GPU version of bedpostx)r   N)r   r   r   r	   r   r    r!   r"   r
   rN   r   rO   rP   rQ   rR   r#   rS   rT   rU   rV   rr   r$   r'   grad_devuse_gpur(   r(   r(   r)   rw   M  sX   
rw   c               @   s   e Zd ZedddZeeddddZedddZeeddddZeeddd	dZ	eeddd
dZ
eeddddZeeddddZeeddddZeeddddZdS )BEDPOSTX5OutputSpecTz%Mean of distribution on diffusivity d)r   r   )r   z$Mean of distribution on f anisotropy)r   z7Mean of distribution on T2wbaseline signal intensity S0zMean of distribution on phizMean of distribution on thetaz&Samples from the distribution on thetaz$Samples from the distribution on phiz<Samples from the distribution on anisotropic volume fractionz(Mean of PDD distribution in vector form.Z
DispersionN)r   r   r   r	   r]   r   r^   r_   mean_phsamplesmean_thsamplesmerged_thsamplesmerged_phsamplesmerged_fsamplesr[   dyads_dispersionr(   r(   r(   r)   r{     s&   
r{   c                   sP   e Zd ZdZdZeZeZeZ	dZ
 fddZdd Z fdd	Zd
d Z  ZS )	BEDPOSTX5a  
    BEDPOSTX stands for Bayesian Estimation of Diffusion Parameters Obtained
    using Sampling Techniques. The X stands for modelling Crossing Fibres.
    bedpostx runs Markov Chain Monte Carlo sampling to build up distributions
    on diffusion parameters at each voxel. It creates all the files necessary
    for running probabilistic tractography. For an overview of the modelling
    carried out within bedpostx see this `technical report
    <http://www.fmrib.ox.ac.uk/analysis/techrep/tr03tb1/tr03tb1/index.html>`_.


    .. note:: Consider using
      :func:`niflow.nipype1.workflows.fsl.dmri.create_bedpostx_pipeline` instead.


    Example
    -------

    >>> from nipype.interfaces import fsl
    >>> bedp = fsl.BEDPOSTX5(bvecs='bvecs', bvals='bvals', dwi='diffusion.nii',
    ...                     mask='mask.nii', n_fibres=1)
    >>> bedp.cmdline
    'bedpostx bedpostx -b 0 --burnin_noard=0 --forcedir -n 1 -j 5000 -s 1 --updateproposalevery=40'

    rx   Tc                s&   t t| jf | | jj| jd d S )Nrz   )rg   r   __init__r1   Zon_trait_change_cuda_update)r9   r1   )rl   r(   r)   r     s    zBEDPOSTX5.__init__c             C   s(   t | jjr| jjrd| _n| j| _d S )NZbedpostx_gpu)r   r1   rz   r?   _default_cmd)r9   r(   r(   r)   r     s    zBEDPOSTX5._cuda_updatec                s
  t jj| jj}t jj|s&t j| t| jj\}}}t	| jjt jj
|d|  t| jj\}}}t	| jjt jj
|d|  t	| jjt jj
|d t	| jjt jj
|d t| jjrt| jj\}}}t	| jjt jj
|d|  tt| j|}|d | _|S )NZnodif_brain_maskdatar"   r!   ry   z	.bedpostX)rd   rn   ro   r1   rr   r   makedirsr   r    r   joinr   r"   r!   r   ry   rg   r   rh   rf   )r9   rk   Z
subjectdirr/   extretval)rl   r(   r)   rh     s    

zBEDPOSTX5._run_interfacec             C   sv  | j  j }| jj}ddddddddg}d	d
g}x |D ]}| j|| jd||< q6W x|D ]}g ||< qXW xtd|d D ]}|d j| jd| | jd |d j| jd| | jd |d j| jd| | jd |d j| jd| | jd |d j| jd| | jd |d j| jd| | jd |d j| jd| | jd |d j| jd| | jd qzW |S )Nr~   r   r   r|   r}   r^   r   r[   r]   r_   )rm   r   zmerged_th%dsampleszmerged_f%dsampleszmerged_ph%dsampleszmean_th%dsampleszmean_ph%dsampleszmean_f%dsampleszdyads%dzdyads%d_dispersion)r4   r5   r1   rP   r8   rf   rp   rq   )r9   r;   rP   rs   rt   r<   ru   r(   r(   r)   r=     s@    

zBEDPOSTX5._list_outputs)r   r   r   r>   r?   r   rw   r@   r{   r4   Z_can_resumer   r   rh   r=   rv   r(   r(   )rl   r)   r     s   r   c               @   s   e Zd ZeddddZdS )XFibres5InputSpecTz--gradnonlin=%sz$gradient file corresponding to slice)r   r   r   N)r   r   r   r	   r'   r(   r(   r(   r)   r     s   r   c               @   s   e Zd ZdZdZeZeZdS )XFibres5z\
    Perform model parameters estimation for local (voxelwise) diffusion
    parameters
    ZxfibresN)	r   r   r   r>   r?   r   r@   rZ   r4   r(   r(   r(   r)   r     s   r   c            	   @   s<  e Zd ZeeddddZeeddddZeeddddZej	dddddZ
eddd	dd
Zejeddejeddejejej dddd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ddddZedddddZejdddddZejdd d!ddZejd"d#d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/Zejd0d1d2dd3Zejd4d5d/Z ej!d6d7d/Z"ej!d8d9d/Z#ejd:d;d/Z$ej!d<d=d/Z%ejd>d?d/Z&ejd@dAd/Z'ej(dBdCdDddEdFd/Z)ejdGdHd/Z*ejdIdJd/Z+ejdKdLd/Z,ejdMdNd/Z-ej(dBdCdDdOdPdZ.dQS )RProbTrackXBaseInputSpecT)r   )r   Zmergedz(the rootname/base_name for samples filesz--samples=%s)r   r   r   z'bet binary mask file in diffusion spacez-m %s)r   r   r   r   r   )Zminlenmaxlenz4seed volume(s), or voxel(s) or freesurfer label filez	--seed=%s)r   r   r   )ZexitszClist of target masks - required for seeds_to_targets classificationz--targetmasks=%s)r   r   z[waypoint mask or ascii list of waypoint masks - only keep paths going through ALL the masksz--waypoints=%s)r   r   r   znactivate network mode - only keep paths going through at least one seed mask (required if multiple seed masks)z	--networkzUreference vol to define seed space in simple mode - diffusion space assumed if absentz--seedref=%sz--dir=%sz%directory to put the final volumes in)r   r   r   genfilezOuse the actual directory name given - i.e. do not add + to make a new directoryz
--forcedirzoutputs path distributionsz--opdz8correct path distribution for the length of the pathwaysz--pdzOutputs seeds to targetsz--os2tz<reject pathways passing through locations given by this maskz
--avoid=%sz	--stop=%sz2stop tracking at locations given by this mask file)r   r   r   z--xfm=%szttransformation matrix taking seed space to DTI space (either FLIRT matrix or FNIRT warp_field) - default is identityz--invxfm=%szjtransformation matrix taking DTI space to seed space (compulsory when using a warp_field for seeds_to_dti))r   r   i  z--nsamples=%dz number of samples - default=5000)r   r   r   z--nsteps=%dz)number of steps per sample - default=2000z--distthresh=%.3fz@discards samples shorter than this threshold (in mm - default=0)z--cthr=%.3fz!curvature threshold - default=0.2z	--sampvoxz'sample random points within seed voxelsz--steplength=%.3fzstep_length in mm - default=0.5z--loopcheckzKperform loop_checks on paths - slower, but allows lower curvature thresholdz--usefz$use anisotropy to constrain trackingr   r   r   z--randfib=%dzoptions: 0 - default, 1 - to randomly sample initial fibres (with f > fibthresh), 2 - to sample in proportion fibres (with f>fibthresh) to f, 3 - to sample ALL populations at random (even if f<fibthresh)z
--fibst=%dzgforce a starting fibre for tracking - default=1, i.e. first fibre orientation. Only works if randfib==0z
--modeulerzuse modified euler streamliningz--rseedzrandom seedz--s2tastextzMoutput seed-to-target counts as a text file (useful when seeding from a mesh)zCVerbose level, [0-2]. Level 2 is required to output particle files.z--verbose=%dN)/r   r   r   r   r	   rb   ra   r\   r   r   samples_base_namer    EitherListr#   rW   target_masksZ	waypointsr$   networkZseed_refr
   rr   rY   opdZcorrect_path_distributionZos2tZavoid_mpZ	stop_maskZxfmZinv_xfm	n_samplesZn_stepsFloatZdist_threshZc_threshZsample_random_pointsZstep_lengthZ
loop_checkZuse_anisotropyrQ   Zrand_fibZfibstZ	mod_eulerZrandom_seedZ	s2tastextverboser(   r(   r(   r)   r   ,  s   




r   c               @   s>   e Zd ZejdddddddZeddd	d
Zedddd
ZdS )ProbTrackXInputSpecsimpleZtwo_mask_symmseedmaskzhoptions: simple (single seed voxel), seedmask (mask of seed voxels), twomask_symm (two bet binary masks)z	--mode=%sT)r   r   r   z@second bet binary mask (in diffusion space) in twomask_symm modez
--mask2=%s)r   r   r   z4Freesurfer-type surface descriptor (in ascii format)z	--mesh=%sN)	r   r   r   r   rQ   moder	   Zmask2Zmeshr(   r(   r(   r)   r     s   r   c               @   s^   e Zd ZedddZeeddddZedddZej	eddddZ
ej	eddd	dZd
S )ProbTrackXOutputSpecTz6path/name of a text record of the command that was run)r   r   )r   z]path/name of a 3D image file containing the output connectivity distribution to the seed mask)r   zpath/name of a text file containing a single number corresponding to the total number of generated tracts that have not been rejected by inclusion/exclusion mask criteriaz/a list with all generated seeds_to_target fileszPFiles describing all of the tract samples. Generated only if verbose is set to 2N)r   r   r   r	   logr   	fdt_paths	way_totalr   r   targetsparticle_filesr(   r(   r(   r)   r     s   
r   c                   sT   e Zd ZdZdZeZeZ fddZ	 fddZ
 fddZd	d
 Zdd Z  ZS )
ProbTrackXa   Use FSL  probtrackx for tractography on bedpostx results

    Examples
    --------

    >>> from nipype.interfaces import fsl
    >>> pbx = fsl.ProbTrackX(samples_base_name='merged', mask='mask.nii',     seed='MASK_average_thal_right.nii', mode='seedmask',     xfm='trans.mat', n_samples=3, n_steps=10, force_dir=True, opd=True,     os2t=True, target_masks = ['targets_MASK1.nii', 'targets_MASK2.nii'],     thsamples='merged_thsamples.nii', fsamples='merged_fsamples.nii',     phsamples='merged_phsamples.nii', out_dir='.')
    >>> pbx.cmdline
    'probtrackx --forcedir -m mask.nii --mode=seedmask --nsamples=3 --nsteps=10 --opd --os2t --dir=. --samples=merged --seed=MASK_average_thal_right.nii --targetmasks=targets.txt --xfm=trans.mat'

    Z
probtrackxc                s   t jdt tt| jf |S )Nz7Deprecated: Please use create_bedpostx_pipeline instead)warningswarnDeprecationWarningrg   r   r   )r9   r1   )rl   r(   r)   r   /  s    zProbTrackX.__init__c                s  xt dt| jjd D ]}t| jj|d  \}}}t| jj|d  | jjd|  | dd t| jj|d  \}}}t| jj|d  | jjd|  | dd t| jj|d  \}}}t| jj|d  | jjd|  | dd qW t	| jj
r.tdd}x | jj
D ]}|jd	|  qW |j  t| jjtrtd
d}xL| jjD ]@}t|tr|jd	djdd |D   n|jd	|  qRW |j  tt| j|}|jr| j| |S )Nr   z_th%dsamplesF)copyz_ph%dsamplesz_f%dsamplesztargets.txtwz%s
z	seeds.txt c             S   s   g | ]}t |qS r(   )str).0sr(   r(   r)   
<listcomp>T  s    z-ProbTrackX._run_interface.<locals>.<listcomp>)rp   lenr1   rb   r   r   r   ra   r\   r   r   openwriteclose
isinstancerW   listr   rg   r   rh   ri   rj   )r9   rk   ru   r/   r   ftargetrW   )rl   r(   r)   rh   6  s@    

 
zProbTrackX._run_interfacec                sl   |dkr*t |r*d}tt| j|||gS |dkrTt|trTd}tt| j|||S tt| j|||S d S )Nr   ztargets.txtrW   z	seeds.txt)r   rg   r   _format_argr   r   )r9   namespecrD   fname)rl   r(   r)   r   ^  s    zProbTrackX._format_argc                s~  | j  j }t| jjs$| jd n| jj tjjtjj	 d|d< t| jj
dkrt| jjtrt| jjd trg |d< xd| jjD ]:}|d jtjj| jddj	d	d
 |D   dd qW ntjj| jd dd|d< t| jjr@g |d< xD| jjD ]8}|d jtjj| jdtjj|d   dd qW t| jjrz| jjdkrz fdd
t| jjD |d< |S )Nrr   zprobtrackx.logr   Tr   r   zfdt_paths_%sr/   c             S   s   g | ]}t |qS r(   )r   )r   r   r(   r(   r)   r   {  s    z,ProbTrackX._list_outputs.<locals>.<listcomp> )rm   r0   r   Z	seeds_to_r   r   c                s&   g | ]}t jjt jj d | qS )z
particle%d)rd   rn   ro   r   )r   ru   )rr   r(   r)   r     s   r   )r4   r5   r   r1   rr   _gen_filenamerd   rn   ro   r   r   r   rW   r   rq   r8   r   splitr   rp   r   )r9   r;   rW   r   r(   )rr   r)   r=   h  s>    
zProbTrackX._list_outputsc             C   sD   |dkrt j S |dkr@t| jjtr<t| jjd tr<dS dS d S )Nrr   r   r   r   r   )rd   re   r   r1   rW   r   )r9   r   r(   r(   r)   r     s    zProbTrackX._gen_filename)r   r   r   r>   r?   r   r@   r   r4   r   rh   r   r=   r   rv   r(   r(   )rl   r)   r     s   (
2r   c               @   s  e Zd ZejdddZeddddZejdd	d
ddZ	ejdddZ
ejdddZejdddZejdddZejdddgdZeddddZejddddg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dd'd(dZedd)d*dZejd+d,d-d.d/d0dZd1S )2ProbTrackX2InputSpeczErack from a list of voxels (seed must be a ASCII list of coordinates)z--simple)r   r   Tz)Other mask for binning tract distributionz	--fopd=%s)r   r   r   ORZANDz--waycond=%sz2Waypoint condition. Either "AND" (default) or "OR")r   r   zVReject streamlines that do not hit waypoints in given order. Only valid if waycond=ANDz
--wayorderz7Apply waypoint conditions to each half tract separatelyz--onewayconditionz(Output matrix1 - SeedToSeed Connectivityz
--omatrix1z--distthresh1=%.3fzMDiscards samples (in matrix1) shorter than this threshold (in mm - default=0)z!Output matrix2 - SeedToLowResMaskz
--omatrix2target2)r   r   requireszVLow resolution binary brain mask for storing connectivity distribution in matrix2 modez--target2=%sz(Output matrix3 (NxN connectivity matrix)z
--omatrix3target3	lrtarget3zBMask used for NxN connectivity matrix (or Nxn if lrtarget3 is set)z--target3=%sz2Column-space mask used for Nxn connectivity matrixz--lrtarget3=%sz--distthresh3=%.3fzMDiscards samples (in matrix3) shorter than this threshold (in mm - default=0)z=Output matrix4 - DtiMaskToSeed (special Oxford Sparse Format)z
--omatrix4z/Mask for columns of matrix4 (default=seed mask)z--colmask4=%szBrain mask in DTI spacez--target4=%sZcaretZ
freesurferfirstZvoxz--meshspace=%szSMesh reference space - either "caret" (default) or "freesurfer" or "first" or "vox"N)r   r   r   r   r$   r   r	   ZfopdrQ   ZwaycondZwayorderZonewayconditionomatrix1r   Zdistthresh1omatrix2r   omatrix3r   r   Zdistthresh3Zomatrix4Zcolmask4Ztarget4Z	meshspacer(   r(   r(   r)   r     sz   

r   c               @   sH   e Zd ZedddZedddZedddZedddZedddZdS )	ProbTrackX2OutputSpecTz1the network matrix generated by --omatrix1 option)r   r   z,Output matrix1.dot - SeedToSeed Connectivityz0lookup_tractspace generated by --omatrix2 optionz%Output matrix2.dot - SeedToLowResMaskz(Output matrix3 - NxN connectivity matrixN)	r   r   r   r	   network_matrixmatrix1_dotlookup_tractspacematrix2_dotmatrix3_dotr(   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 )ProbTrackX2a  Use FSL  probtrackx2 for tractography on bedpostx results

    Examples
    --------

    >>> from nipype.interfaces import fsl
    >>> pbx2 = fsl.ProbTrackX2()
    >>> pbx2.inputs.seed = 'seed_source.nii.gz'
    >>> pbx2.inputs.thsamples = 'merged_th1samples.nii.gz'
    >>> pbx2.inputs.fsamples = 'merged_f1samples.nii.gz'
    >>> pbx2.inputs.phsamples = 'merged_ph1samples.nii.gz'
    >>> pbx2.inputs.mask = 'nodif_brain_mask.nii.gz'
    >>> pbx2.inputs.out_dir = '.'
    >>> pbx2.inputs.n_samples = 3
    >>> pbx2.inputs.n_steps = 10
    >>> pbx2.cmdline
    'probtrackx2 --forcedir -m nodif_brain_mask.nii.gz --nsamples=3 --nsteps=10 --opd --dir=. --samples=merged --seed=seed_source.nii.gz'
    Zprobtrackx2c                s   t t| j }t| jjs$tj }n| jj}tjj	tjj
|d|d< t| jjrtjj	tjj
|d|d< tjj	tjj
|d|d< t| jjrtjj	tjj
|d|d< tjj	tjj
|d	|d
< t| jjrtjj	tjj
|d|d< |S )NZwaytotalr   Zmatrix_seeds_to_all_targetsr   zfdt_matrix1.dotr   z$lookup_tractspace_fdt_matrix2.nii.gzr   zfdt_matrix2.dotr   zfdt_matrix3.dotr   )rg   r   r=   r   r1   rr   rd   re   rn   ro   r   r   r   r   )r9   r;   rr   )rl   r(   r)   r=   /  s&    
zProbTrackX2._list_outputs)r   r   r   r>   r?   r   r@   r   r4   r=   rv   r(   r(   )rl   r)   r     s
   r   c               @   s   e Zd ZedddddZedddddZedd	d
ddZeddddZeddddZeddddZ	eddddZ
ejdddddddZeddddZeddddZdS ) VecRegInputSpecTz-i %sz)filename for input vector or tensor field)r   r   r   r   z-o %sz5filename for output registered vector or tensor fieldF)r   r   r   
hash_filesz-r %sz&filename for reference (target) volumez-t %sz)filename for affine transformation matrix)r   r   r   z-w %sz5filename for 4D warp field for nonlinear registrationz--rotmat=%szjfilename for secondary affine matrix if set, this will be used for the rotation of the vector/tensor fieldz--rotwarp=%szgfilename for secondary warp field if set, this will be used for the rotation of the vector/tensor fieldZnearestneighbourZ	trilinearZsincZsplinez--interp=%szLinterpolation method : nearestneighbour, trilinear (default), sinc or spline)r   r   z-m %szbrain mask in input spacez--refmask=%szAbrain mask in output space (useful for speed up of nonlinear reg)N)r   r   r   r	   in_fileout_fileZref_volZ
affine_matZ
warp_fieldZrotation_matZrotation_warpr   rQ   interpolationr    Zref_maskr(   r(   r(   r)   r   P  sR   r   c               @   s   e Zd ZedddZdS )VecRegOutputSpecTz?path/name of filename for the registered vector or tensor field)r   r   N)r   r   r   r	   r   r(   r(   r(   r)   r     s   r   c                   s<   e Zd ZdZdZeZeZ fddZ	dd Z
dd Z  ZS )	VecRega  Use FSL vecreg for registering vector data
    For complete details, see the FDT Documentation
    <http://www.fmrib.ox.ac.uk/fsl/fdt/fdt_vecreg.html>

    Example
    -------

    >>> from nipype.interfaces import fsl
    >>> vreg = fsl.VecReg(in_file='diffusion.nii',                  affine_mat='trans.mat',                  ref_vol='mni.nii',                  out_file='diffusion_vreg.nii')
    >>> vreg.cmdline
    'vecreg -t trans.mat -i diffusion.nii -o diffusion_vreg.nii -r mni.nii'

    Zvecregc                sL   t | jjs<tjj| jj\}}| j|tjj|dd| j_t	t
| j|S )N_vreg)rm   r0   )r   r1   r   rd   rn   r   r   r8   ro   rg   r   rh   )r9   rk   pthr   )rl   r(   r)   rh     s
    zVecReg._run_interfacec             C   sz   | j  j }| jj|d< t|d  rbt| jjrbtjj| jj\}}| j	|tjj
|dd|d< tjj
|d |d< |S )Nr   r   )rm   r0   )r4   r5   r1   r   r   r   rd   rn   r   r8   ro   )r9   r;   r   r   r(   r(   r)   r=     s    zVecReg._list_outputsc             C   s   |dkr| j  | S d S d S )Nr   )r=   )r9   r   r(   r(   r)   r     s    zVecReg._gen_filename)r   r   r   r>   r?   r   r@   r   r4   rh   r=   r   rv   r(   r(   )rl   r)   r     s   r   c               @   s8   e Zd ZejedddddddZejdddd	dZd
S )ProjThreshInputSpecT)r   z%sza list of input volumesr   )r   r   r   r   z%dzLthreshold indicating minimum number of seed voxels entering this mask regionr   N)	r   r   r   r   r   r	   in_filesr#   	thresholdr(   r(   r(   r)   r     s   r   c               @   s    e Zd ZejeddddZdS )ProjThreshOuputSpecT)r   z-path/name of output volume after thresholding)r   N)r   r   r   r   r   r	   	out_filesr(   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 )
ProjThresha  Use FSL proj_thresh for thresholding some outputs of probtrack
    For complete details, see the FDT Documentation
    <http://www.fmrib.ox.ac.uk/fsl/fdt/fdt_thresh.html>

    Example
    -------

    >>> from nipype.interfaces import fsl
    >>> ldir = ['seeds_to_M1.nii', 'seeds_to_M2.nii']
    >>> pThresh = fsl.ProjThresh(in_files=ldir, threshold=3)
    >>> pThresh.cmdline
    'proj_thresh seeds_to_M1.nii seeds_to_M2.nii 3'

    Zproj_threshc             C   s^   | j  j }g |d< xD| jjD ]8}tjj|\}}|d j| j||dj	| jj
d qW |S )Nr   z_proj_seg_thr_{})rm   r0   )r4   r5   r1   r   rd   rn   r   rq   r8   formatr   )r9   r;   r   rm   r   r(   r(   r)   r=     s    zProjThresh._list_outputsN)
r   r   r   r>   r?   r   r@   r   r4   r=   r(   r(   r(   r)   r     s
   r   c               @   s8   e Zd ZejedddddddZeddddd	d
ZdS )FindTheBiggestInputSpecT)r   z%sz-a list of input volumes or a singleMatrixFiler   )r   r   r   r   z$file with the resulting segmentationr   F)r   r   r   r   r   N)r   r   r   r   r   r	   r   r   r(   r(   r(   r)   r     s   r   c               @   s   e Zd ZeddddZdS )FindTheBiggestOutputSpecTz%sz+output file indexed in order of input files)r   r   r   N)r   r   r   r	   r   r(   r(   r(   r)   r     s   r   c                   s<   e Zd ZdZdZeZeZ fddZ	dd Z
dd Z  ZS )	FindTheBiggesta$  
    Use FSL find_the_biggest for performing hard segmentation on
    the outputs of connectivity-based thresholding in probtrack.
    For complete details, see the `FDT
    Documentation. <http://www.fmrib.ox.ac.uk/fsl/fdt/fdt_biggest.html>`_

    Example
    -------

    >>> from nipype.interfaces import fsl
    >>> ldir = ['seeds_to_M1.nii', 'seeds_to_M2.nii']
    >>> fBig = fsl.FindTheBiggest(in_files=ldir, out_file='biggestSegmentation')
    >>> fBig.cmdline
    'find_the_biggest seeds_to_M1.nii seeds_to_M2.nii biggestSegmentation'

    Zfind_the_biggestc                s.   t | jjs| jddd| j_tt| j|S )NbiggestSegmentationr   )r0   )r   r1   r   r8   rg   r   rh   )r9   rk   )rl   r(   r)   rh   1  s    zFindTheBiggest._run_interfacec             C   sN   | j  j }| jj|d< t|d s6| jddd|d< tjj|d |d< |S )Nr   r   r   )r0   )	r4   r5   r1   r   r   r8   rd   rn   ro   )r9   r;   r(   r(   r)   r=   6  s    zFindTheBiggest._list_outputsc             C   s   |dkr| j  | S d S d S )Nr   )r=   )r9   r   r(   r(   r)   r   >  s    zFindTheBiggest._gen_filename)r   r   r   r>   r?   r   r@   r   r4   rh   r=   r   rv   r(   r(   )rl   r)   r     s   r   c               @   s   e Zd ZedddddZdddgZejded	d
Zej	ddZ
edddZeddgddZejdddgddZedddZeddddZeddddZeddZejejedddZdS ) TractSkeletonInputSpecTz-i %sz&input image (typcially mean FA volume))r   r   r   r   r   distance_map	data_filez-p %.3f %s %s %s %szproject data onto skeleton)r   r   r   zskeleton threshold value)r   zdistance map image)r   r   use_cingulum_maskz*mask in which to use alternate search rule)r   rH   r   search_mask_filez5perform alternate search using built-in cingulum mask)r   rH   r   z-4D data to project onto skeleton (usually FA)z-a %sz'4D non-FA data to project onto skeleton)r   r   r   z-s %szalternate skeleton to usez"input data projected onto skeletonz-o %szwrite out skeleton image)r   r   N)r   r   r   r	   r   Z_proj_inputsr   r$   project_datar   r   r   r   r   r   alt_data_fileZalt_skeletonprojected_datar   skeleton_filer(   r(   r(   r)   r   E  s8   

r   c               @   s    e Zd ZeddZeddZdS )TractSkeletonOutputSpecz"input data projected onto skeleton)r   ztract skeleton imageN)r   r   r   r	   r   r   r(   r(   r(   r)   r   k  s   
r   c                   s4   e Zd ZdZdZeZeZ fddZ	dd Z
  ZS )TractSkeletona  Use FSL's tbss_skeleton to skeletonise an FA image or project arbitrary
    values onto a skeleton.

    There are two ways to use this interface.  To create a skeleton from an FA
    image, just supply the ``in_file`` and set ``skeleton_file`` to True (or
    specify a skeleton filename. To project values onto a skeleton, you must
    set ``project_data`` to True, and then also supply values for
    ``threshold``, ``distance_map``, and ``data_file``. The
    ``search_mask_file`` and ``use_cingulum_mask`` inputs are also used in data
    projection, but ``use_cingulum_mask`` is set to True by default.  This mask
    controls where the projection algorithm searches within a circular space
    around a tract, rather than in a single perpindicular direction.

    Example
    -------

    >>> import nipype.interfaces.fsl as fsl
    >>> skeletor = fsl.TractSkeleton()
    >>> skeletor.inputs.in_file = "all_FA.nii.gz"
    >>> skeletor.inputs.skeleton_file = True
    >>> skeletor.run() # doctest: +SKIP

    Ztbss_skeletonc                s   |dkrvt |r|r| j}t |jr6|jr6tjd}n|j}t |jsT| j d }n|j}|j|j	|j
||j|f S n.|dkrt|tr|j| j d  S |j| S tt| j|||S )Nr   zLowerCingulum_1mm.nii.gzr   r   )r   r1   r   r   Zstandard_imager   r   r=   r   r   r   r   r   boolrg   r   r   )r9   r   r   rD   _si	mask_fileZ	proj_file)rl   r(   r)   r     s(    



zTractSkeleton._format_argc             C   s   | j  j }| j}t|jrf|jrf|j}||d< t|sf|j}t|jrN|j}t|dt	j
 dd|d< t|jr|jr|j|d< t|jtrt|jdt	j
 dd|d< |S )Nr   Z_skeletonisedT)r0   newpathuse_extr   Z	_skeleton)r4   r5   r1   r   r   r   r   r   r   rd   re   r   r   r   r   )r9   r;   r   Z	proj_dataZstemr(   r(   r)   r=     s"    

zTractSkeleton._list_outputs)r   r   r   r>   r?   r   r@   r   r4   r   r=   rv   r(   r(   )rl   r)   r   q  s   r   c               @   s^   e Zd ZedddddZeddddZejdd	d
Zej	ejeddddZ
edddddZdS )DistanceMapInputSpecTz--in=%sz&image to calculate distance values for)r   r   r   r   z	--mask=%sz$binary mask to contrain calculations)r   r   r   z--invertzinvert input image)r   r   z--localmax=%sz"write an image of the local maximaF)r   r   r   z--out=%szdistance map to write)r   r   r   r   N)r   r   r   r	   r   r   r   r$   Zinvert_inputr   local_max_filer   r(   r(   r(   r)   r     s    r   c               @   s"   e Zd ZedddZeddZdS )DistanceMapOutputSpecTz+value is distance to nearest nonzero voxels)r   r   zimage of local maxima)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	dd Z
dd Z  ZS )	DistanceMapa%  Use FSL's distancemap to generate a map of the distance to the nearest
    nonzero voxel.

    Example
    -------

    >>> import nipype.interfaces.fsl as fsl
    >>> mapper = fsl.DistanceMap()
    >>> mapper.inputs.in_file = "skeleton_mask.nii.gz"
    >>> mapper.run() # doctest: +SKIP

    Zdistancemapc                s8   |dkr$t |tr$|j| j d  S tt| j|||S )Nr   )r   r   r   r=   rg   r   r   )r9   r   r   rD   )rl   r(   r)   r     s    
zDistanceMap._format_argc             C   s   | j  j }| j}|j|d< t|js@t|jddtj d|d< tj	j
|d |d< t|jr|j|d< t|jtrt|jddtj d|d< tj	j
|d |d< |S )Nr   Z_dstmapT)r0   r   r   r   Z_lclmax)r4   r5   r1   r   r   r   r   rd   re   rn   ro   r   r   r   )r9   r;   r   r(   r(   r)   r=     s    



zDistanceMap._list_outputsc             C   s   |dkr| j  d S d S )Nr   )r=   )r9   r   r(   r(   r)   r     s    zDistanceMap._gen_filename)r   r   r   r>   r?   r   r@   r   r4   r   r=   r   rv   r(   r(   )rl   r)   r     s   r   c               @   s\   e Zd ZedddddZedddddZeddddZedd	ddd
dZej	ddddZ
dS )MakeDyadicVectorsInputSpecTr   z%s)r   r   r   r   r   r   )r   r   r   r[   r   F)r   r   r   r   zOthe {perc}% angle of the output cone of uncertainty (output will be in degrees)r   z%f)r   r   r   N)r   r   r   r	   Z	theta_volZphi_volr    r:   r   r   percr(   r(   r(   r)   r     s   r   c               @   s    e Zd ZeddZeddZdS )MakeDyadicVectorsOutputSpecT)r   N)r   r   r   r	   r[   
dispersionr(   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 )MakeDyadicVectorsziCreate vector volume representing mean principal diffusion direction
    and its uncertainty (dispersion)Zmake_dyadic_vectorsc             C   s8   | j  j }| j| jj|d< | j| jjdd|d< |S )Nr[   Z_dispersion)r0   r   )r4   r5   r8   r1   r:   )r9   r;   r(   r(   r)   r=   (  s
    zMakeDyadicVectors._list_outputsN)
r   r   r   r>   r?   r   r@   r   r4   r=   r(   r(   r(   r)   r      s
   r   )8r>   rd   r   Zutils.filemanipr   r   r   baser   r   r	   r
   r   r   r   r   r   r   r   r*   r,   rA   rZ   rc   rw   r{   r   r   r   ZXFibresZBEDPOSTXr   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)   <module>   s\   $	/) 2:p 3" e9A0#*&M0