3
d*                 @   s   d dl jZd dlZd dljZd dlZ	d dlm
Z
 d dlmZ d dlmZ ddlmZ ddlmZ dd	lmZmZmZ dd
lmZmZ ejdZdd Zdd Zdd ZdddZ dd Z!d ddZ"G dd deZ#G dd deZ$G dd deZ%dS )!    N)HeaderError)native_code)aff2axcodes   )logging)split_filename   )TraitedSpecFile	isdefined)DipyBaseInterface	HAVE_DIPYznipype.interfacec             C   sT   dd l }t| tr| d } |j| }|j}|j }t|d t|d t|d gS )Nr      r   )nibabel
isinstancelistloadheaderZ	get_zoomsfloat)volumenbniihdrZvoxdims r   B/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/mrtrix/convert.pyget_vox_dims   s    

r   c             C   sT   dd l }t| tr| d } |j| }|j}|j }t|d t|d t|d gS )Nr   r   r   )r   r   r   r   r   Zget_data_shapeint)r   r   r   r   Zdatadimsr   r   r   get_data_dims   s    

r   c             C   s   yddl m} W n  tk
r0   ddl m} Y nX tjj|\}}|| |} tj|ddddf tjd|d  |ddddf< t	|dddf |dddf< || |} | S )Nr   )transform_tracking_output)move_streamlinesr   g      ?
voxel_size)
dipy.tracking.utilsr   ImportErrorr   npZlinalgZqrdotdiagabs)Zstreamsr   affiner   ZrotationZscaler   r   r   transform_to_affine*   s    
: 
r(   Tc             C   s   t | }t| ||}||fS )N)read_mrtrix_headerread_mrtrix_streamlines)in_fileas_generatorr   streamlinesr   r   r   read_mrtrix_tracks8   s    r.   c             C   s   t | d}i }tjd x||D ]t}|j }|dkr@tjd P qd|kr|jdd}|jdd}|jdd	 }|jdd
 }|||< tjd|| qW |j  t|d jdd|d< t|d jdd|d< |S )NrbzReading header data...zEND
zReached the end of the header!z: 
 'r   r   z%...adding "%s" to header for key "%s"countfile.offset)openifloggerinfodecodereplacesplitcloser   )r+   fileobjr   linekeyvaluer   r   r   r)   >   s&    



r)   c       
         s   |d }|d t | dj| t}tj|d dd   fdd} fd	d
}||\}}j| ||}	|st|	}	|	S )Nr6   r3   r/   f4r      c                s   g }t jd j }tt|  }tj|fd|d}tjtjtj	|d d df }t
|d dd }xJt|D ]>\}}|dkr|j||  qz|j|| ||d   d  qzW ||fS )Nz-Identifying the number of points per tract...rB   )shapedtypebufferr   r   r   )r8   r9   readr   lenr#   ndarraywhereinvertisfiniter   	enumerateappend)r6   track_pointsZall_strZnum_tripletsptsnonfinite_listidxrA   )bytesizer>   pt_colsr   r   points_per_track^   s    
"

"z1read_mrtrix_streamlines.<locals>.points_per_trackc       	      3   sp  d}t jd xZy| | }W n tk
r4   P Y nX j|  }j }t||  k r|kstd|f t jd| P tj|f|d}tjdf|d}tj	|d d rt
P |d d d df }|V  |d7 }|krt jd| ty@|td  dkr@tt|t d }t jd	|| W q tk
rf   t jd
| Y qX qW d S )Nr   zReading tracks...z"Expecting %s points, found only %s)rD   rE   rF   r   r   z100%% : %i tracks readd   z%i%% : %i tracks readz%i stream read out of %i)r8   r9   
IndexErrorrH   rI   r   errorr#   rJ   rM   
ValueErrorStopIterationr   r   ZeroDivisionError)	rP   Z	n_streamsZn_ptsZpts_strZnan_strrQ   Znan_ptZxyzpercent)rT   f4dtr>   rU   stream_countr   r   	track_geno   sB    



z*read_mrtrix_streamlines.<locals>.track_gen)r7   seekr   r#   rE   r   )
r+   r   r,   r6   Z
endiannessrV   r`   rP   rR   r-   r   )rT   r^   r>   rU   r_   r   r*   T   s     

%
r*   c               @   sN   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d	d
ZdS )MRTrix2TrackVisInputSpecTz5The input file for the tracks in MRTrix (.tck) format)exists	mandatorydescz(The image the tracks were generated from)rc   re   zA transformation matrix to apply to the tracts after they have been generated (from FLIRT - affine transformation from image_file to registration_image_file)z3The final image the tracks should be registered to.zconverted.trkz<The output filename for the tracks in TrackVis (.trk) format)ZgenfileZ
usedefaultre   N)	__name__
__module____qualname__r
   r+   
image_filematrix_fileregistration_image_fileout_filenamer   r   r   r   rb      s   
rb   c               @   s   e Zd ZeddZdS )MRTrix2TrackVisOutputSpecT)rc   N)rf   rg   rh   r
   out_filer   r   r   r   rm      s   rm   c               @   s8   e Zd ZdZeZeZdd Zdd Z	dd Z
dd	 Zd
S )MRTrix2TrackVisa  
    Converts MRtrix (.tck) tract files into TrackVis (.trk) format
    using functions from dipy
    Example
    -------
    >>> import nipype.interfaces.mrtrix as mrt
    >>> tck2trk = mrt.MRTrix2TrackVis()
    >>> tck2trk.inputs.in_file = 'dwi_CSD_tracked.tck'
    >>> tck2trk.inputs.image_file = 'diffusion.nii'
    >>> tck2trk.run()                                   # doctest: +SKIP
    c             C   s  ddl m} yddl m} W n  tk
r<   ddl m} Y nX t| jj\}}}t| jj\}}}	t	j
| jj}
|
j}tj| jj}t| jjdd\}}tjd tj| t	jj }|||g|d< |||	g|d	< |d
 |d< t| jjot| jjrTtjd| jj tj| jj}tj| t	j
| jj}|j}t| jj\}}}t| jj\}}}tjd| jj tj| ||d< |||g|d< |||g|d	< tj|tjdtj|||	dg }t|||}|||||	g|||g}tj| t|}|d |d  |d  |d< |||}dd |D }tj ||| tjd| tjd tj| ntjd| jj t|}|d |d  |d  |d< ||d< t|||}dd |D }tj ||| tjd| tjd tj| |S )Nr   )affine_from_fsl_mat_file)r   )r   T)r,   zMRTrix Header:Zdimr    r3   Zn_countz+Applying transformation from matrix file %sz,Using affine from registration image file %sZ
vox_to_rasg      ?r   r   Zvoxel_orderc             s   s   | ]}|d d fV  qd S )Nr   ).0iir   r   r   	<genexpr>  s    z1MRTrix2TrackVis._run_interface.<locals>.<genexpr>z&Saving transformed Trackvis file as %szNew TrackVis Header:z6Applying transformation from scanner coordinates to %sc             s   s   | ]}|d d fV  qd S )Nr   )rq   rr   r   r   r   rs     s    zSaving Trackvis file as %szTrackVis Header:)!r!   rp   r   r"   r   r   inputsri   r   r   r   r'   opabspathrl   r.   r+   r8   r9   trackvisZempty_headerr   rj   rk   r#   Z
genfromtxtr$   r%   arrayr(   r   trkwrite)selfZruntimerp   r   ZdxZdyZdzZvxZvyZvzri   r'   rl   r   r-   Z
trk_headerZxfmrk   Z
reg_affineZr_dxZr_dyZr_dzZr_vxZr_vyZr_vzZtransformed_streamlinesZaffZaxcodeZfinal_streamlinesZ
trk_tracksr   r   r   _run_interface   sz    





$







zMRTrix2TrackVis._run_interfacec             C   s"   | j  j }tj| jj|d< |S )Nrn   )Z_outputsgetru   rv   rt   rl   )r{   outputsr   r   r   _list_outputs  s    zMRTrix2TrackVis._list_outputsc             C   s   |dkr| j  S d S d S )Nrl   )_gen_outfilename)r{   namer   r   r   _gen_filename  s    zMRTrix2TrackVis._gen_filenamec             C   s   t | jj\}}}|d S )Nz.trk)r   rt   r+   )r{   _r   r   r   r   r   #  s    z MRTrix2TrackVis._gen_outfilenameN)rf   rg   rh   __doc__rb   Z
input_specrm   Zoutput_specr|   r   r   r   r   r   r   r   ro      s   Rro   )T)T)&os.pathpathru   r   r   Znibabel.trackvisrw   ry   numpyr#   r   Znibabel.volumeutilsr   Znibabel.orientationsr   r1   r   Zutils.filemanipr   baser	   r
   r   Z	dipy.baser   r   Z	have_dipy	getLoggerr8   r   r   r(   r.   r)   r*   rb   rm   ro   r   r   r   r   <module>   s(   




H