3
d/                 @   s  d dl jZd dlZd dlZd dlmZ ddl	m
Z
 ddlmZmZmZmZmZ ddlmZmZmZmZmZ e
jd	Zered
ee   koedkn  ryd dlmZ W n  ek
r   d dlmZ Y nX edeZeoee ed
krFd dlmZm Z  eeee  Z!x.e!D ]&\Z"Z#e"j$ddZ%ee%e#e& e%< qW [!n
ej'd 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-dS )    N)LooseVersion   )logging   )TraitedSpecBaseInterfaceInputSpecFile	isdefinedtraits   )DipyBaseInterface	HAVE_DIPYdipy_versiondipy_to_nipype_interfaceget_dipy_workflowsznipype.interfacez0.15z0.16)LocalFiberTrackingPAMFlow)DetTrackPAMFlowDeterministicTracking)segmenttrackingZFlow zUWe advise you to upgrade DIPY version. This upgrade will open access to more functionc               @   sp   e Zd ZeddddZedddZejddddd	d
Zej	ej
ddddZej	ejddddZedddd
ZdS )TrackDensityMapInputSpecTzThe input TrackVis track file)exists	mandatorydescz0A reference file to define RAS coordinates space)r   r   rasmmZvoxelNzcoordinates of trk file)
usedefaultr   r   zThe size of each voxel in mm.)Zminlenmaxlenr   z The size of the image in voxels.ztdi.niiz<The output filename for the tracks in TrackVis (.trk) format)__name__
__module____qualname__r   in_file	referencer
   Enumpoints_spaceListFloat
voxel_dimsInt	data_dimsout_filename r+   r+   ?/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/dipy/tracks.pyr   1   s   
r   c               @   s   e Zd ZeddZdS )TrackDensityMapOutputSpecT)r   N)r   r   r    r   out_filer+   r+   r+   r,   r-   F   s   r-   c               @   s(   e Zd ZdZeZeZdd Zdd Z	dS )TrackDensityMapaL  
    Creates a tract density image from a TrackVis track file using functions
    from dipy

    Example
    -------

    >>> import nipype.interfaces.dipy as dipy
    >>> trk2tdi = dipy.TrackDensityMap()
    >>> trk2tdi.inputs.in_file = 'converted.trk'
    >>> trk2tdi.run()                                   # doctest: +SKIP

    c             C   s6  ddl m} ddlm} dd lj}|j| jj\}}dd |D }t	| jj
r|tj| jj
}|j}	|jd d }
t|	d}nXtjd t	| jjs|d	 }
n| jj}
t	| jjs|d
 }n| jj}|d }	t|d}|||
f|}|j||j }tj||	}tj| jj}tj|| tjd||j|jj  |S )Nr   )min_scalar_type)density_mapc             s   s   | ]}|d  V  qdS )r   Nr+   ).0iir+   r+   r,   	<genexpr>b   s    z1TrackDensityMap._run_interface.<locals>.<genexpr>r   )affinez\voxel_dims and data_dims are deprecated as of dipy 0.7.1. Please use reference input insteadZdim
voxel_sizeZ
vox_to_ras)r6   z5Track density map saved as %s, size=%s, dimensions=%s)numpyr0   Zdipy.tracking.utilsr1   Znibabel.trackvistrackvisreadinputsr!   r	   r"   nbloadr5   shapedictIFLOGGERwarningr)   r'   astypemaxNifti1Imageopabspathr*   saveinfoheaderZ	get_zooms)selfruntimer0   r1   ZnbttracksrH   ZstreamsZrefniir5   r)   kwargsr6   dataimgr.   r+   r+   r,   _run_interface\   s>    



zTrackDensityMap._run_interfacec             C   s"   | j  j }tj| jj|d< |S )Nr.   )_outputsgetrD   rE   r:   r*   )rI   outputsr+   r+   r,   _list_outputs   s    zTrackDensityMap._list_outputsN)
r   r   r    __doc__r   
input_specr-   output_specrO   rS   r+   r+   r+   r,   r/   J   s
   .r/   c               @   s   e Zd Zed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
jd
ddddZe
jdddddZe
jdddddZe
jdddddZe
jdddddZe
jdddddZe
jddZdS )StreamlineTractographyInputSpecTzinput diffusion data)r   r   r   z#input f/d-ODF model extracted from.)r   r   z(input mask within which perform trackingz'input mask within which perform seedingzpeaks computed from the odfz8file containing the list of seed voxel coordinates (N,3)g?z&GFA threshold to compute tracking mask)r   r   r   g      ?z&threshold to consider peaks from modelg      9@zminimum separation anglezuse multiprocessingFzsave seeding voxels coordinatesi'  z(desired number of tracks in tractographyzoutput prefix for file names)r   N)r   r   r    r   r!   in_modeltracking_mask	seed_maskin_peaks
seed_coordr
   r&   
gfa_threshpeak_threshold	min_angleZBoolmultiprocess
save_seedsr(   	num_seedsStr
out_prefixr+   r+   r+   r,   rW      s<   rW   c               @   s4   e Zd ZeddZeddZeddZeddZdS ) StreamlineTractographyOutputSpecz.TrackVis file containing extracted streamlines)r   zFThe resulting GFA (generalized FA) computed using the peaks of the ODFzpeaks computed from the odfz>file containing the (N,3) *voxel* coordinates used in seeding.N)r   r   r    r   rK   gfa	odf_peaks	out_seedsr+   r+   r+   r,   re      s   

re   c               @   s2   e Zd ZdZeZeZdd Zdd Z	d	ddZ
dS )
StreamlineTractographyu  
    Streamline tractography using EuDX [Garyfallidis12]_.

    .. [Garyfallidis12] Garyfallidis E., “Towards an accurate brain
      tractography”, PhD thesis, University of Cambridge, 2012

    Example
    -------

    >>> from nipype.interfaces import dipy as ndp
    >>> track = ndp.StreamlineTractography()
    >>> track.inputs.in_file = '4d_dwi.nii'
    >>> track.inputs.in_model = 'model.pklz'
    >>> track.inputs.tracking_mask = 'dilated_wm_mask.nii'
    >>> res = track.run() # doctest: +SKIP
    c             C   s  ddl m} ddlm} ddlm} dd l}dd l}t| j	j
pJt| j	jsTtdtj| j	j}tj|d }|j}	|jtjd}
|jj }|jtj d|d< |d	}d
| _t| j	jrtjd |j| j	jd}|j|}|j  n~d| _tjd |j| j	j
d}|j|}|j  |||
|| j	j| j	j| j	jd}|j| j dddd}|j!||d( |j  |j"|j#j$ tj%|j#j&tj|	|j'| j d tjd t| j	j(rtj)tj| j	j(j*}d||dk< d||dk < ntj+|j$}|j#| }| j	j,}t| j	j-r tj.| j	j-}n8t| j	j/rXtj)tj| j	j/j*}|j$|
j$d d ks^t0d||dk< d||dk < tj1tj2|dktjdj3}|j$d }|| d }tjd|| |dkrXtjd|| tj4tj1|g| }|tj5j6d)d|j$d }|j$d }|	j7tj4|j3tj+d|ffd dd d f j3}| j	j8rXtj9| j ddd| t| j	j(rp|}d}n|}| j	j:}|||j;d* ||	|j<|d}d d! |D }tj=j>d"d! |D d#tj?d$d%}|j@| j d&d'd |S )+Nr   )peaks_from_model)EuDX)
get_spherez7At least one of in_model or in_peaks should be supplied)Zdtype   Z	data_typeZsymmetric724Fz.Peaks file found, skipping ODF peaks search...rbTz%Loading model and computing ODF peaks)modelrM   sphereZrelative_peak_thresholdZmin_separation_angleparallelpeaksz.pklz)extwbr   rf   zPerforming tractographyr   zPSeed mask is provided (%d voxels inside mask), computing seeds (%d seeds/voxel).z.Needed %d seeds per selected voxel (total %d).)sizeseedsz.txtg?.)rv   r5   Zodf_verticesa_lowc             S   s   g | ]}t j|qS r+   )nparray)r2   sr+   r+   r,   
<listcomp>M  s    z9StreamlineTractography._run_interface.<locals>.<listcomp>c             S   s   g | ]}|d d fqS )Nr+   )r2   rz   r+   r+   r,   r{   P  s    r      )r$   r5   trackedz.trkr~   ).r   )AZdipy.reconst.peaksrj   Zdipy.tracking.eudxrk   Z	dipy.datarl   picklegzipr	   r:   rX   r[   RuntimeErrorr;   r<   r!   Zfour_to_threer5   Z	get_fdatarx   Zfloat32rH   copyZset_data_dtype_save_peaksr?   rG   opencloser^   r_   r`   _gen_filenamedumpZset_data_shaperf   r=   rC   rA   to_filenamerY   Z
asanyarrayZdataobjZonesrb   r\   ZloadtxtrZ   AssertionErrorry   whereTZvstackrandomuniformdotra   Zsavetxtr]   Zpeak_indicesZverticesr8   ZTrackvisFileZeyeZto_file)rI   rJ   rj   rk   rl   r   r   rN   Zimrefr5   rM   hdrrp   frr   Z	odf_modelZmskrf   rv   ZseedmskZseedpsZvseedsZnspervZvoxcoordZnseedsZtmaskrw   euZss_mmZtrkfilevr+   r+   r,   rO      s    











 
z%StreamlineTractography._run_interfacec             C   s|   | j  j }| jddd|d< | jd|d< | jrD| jddd|d< | jjrxt| jjrf| jj|d	< n| jd
dd|d	< |S )Nr}   z.trk)rs   rK   rf   rr   z.pklzrg   rh   rv   z.txt)rP   rQ   r   r   r:   ra   r	   r\   )rI   rR   r+   r+   r,   rS   U  s    z$StreamlineTractography._list_outputsNc             C   sr   t jt j| jj\}}|dkr6t j|\}}|| }t| jjsNt j|}n| jj}|d krb|}|d | | S )Nz.gz_)rD   splitextbasenamer:   r!   r	   rd   rE   )rI   namers   fnameZfextZfext2rd   r+   r+   r,   r   c  s    z$StreamlineTractography._gen_filename)N)r   r   r    rT   rW   rU   re   rV   rO   rS   r   r+   r+   r+   r,   ri      s   {ri   ).os.pathpathrD   r7   rx   Znibabelr;   distutils.versionr   r   r   baser   r   r   r	   r
   r   r   r   r   r   	getLoggerr?   Zdipy.workflows.trackingr   ZDetTrackFlowImportErrorr   r   Zdipy.workflowsr   r   Zl_wkflwr   objreplacenew_nameglobalsrG   r   r-   r/   rW   re   ri   r+   r+   r+   r,   <module>   s<   

&F(