3
dZ                 @   sL  d dl Z d dljZd dl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mZmZmZ ejdZd+d	d
Zdd Zdd Zdd Zdd Zd,ddZd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%d#d$ Z&G d%d& d&eZ'G d'd( d(eZ(G d)d* d*eZ)dS )-    N   )logging)split_filename   )BaseInterfaceBaseInterfaceInputSpectraitsFileTraitedSpec	DirectoryOutputMultiPath	isdefinedznipype.interfaceFc             C   sd   t j| } | jd dk r,|r(t jdgS dS t jt j| ddd jdd}|rZt j|S t j|S )a  
    Euclidean length of track line

    Parameters
    ----------
    xyz : array-like shape (N,3)
       array representing x,y,z of N points in a track
    along : bool, optional
       If True, return array giving cumulative length along track,
       otherwise (default) return scalar giving total length.

    Returns
    -------
    L : scalar or array shape (N-1,)
       scalar in case of `along` == False, giving total length, array if
       `along` == True, giving cumulative lengths.

    Examples
    --------
    >>> xyz = np.array([[1,1,1],[2,3,4],[0,0,0]])
    >>> expected_lens = np.sqrt([1+2**2+3**2, 2**2+3**2+4**2])
    >>> length(xyz) == expected_lens.sum()
    True
    >>> len_along = length(xyz, along=True)
    >>> np.allclose(len_along, expected_lens.cumsum())
    True
    >>> length([])
    0
    >>> length([[1, 2, 3]])
    0
    >>> length([], along=True)
    array([0])
    r   r   )axis   )npZasarrayshapearraysqrtZdiffsumZcumsum)xyzZalongdists r   =/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/cmtk/cmtk.pylength   s    "
 
r   c       	      C   s   t | }g }xtd|D ]~}t| |df t|d  }t| |df t|d  }t| |df t|d  }||||f dks|j||||f  qW ttj|j }|S )Nr   r   r   )	lenrangeintfloatappendlistdictfromkeyskeys)	ZpointsmmroiData	voxelSizeZn_pointsrois_crossedjxyzr   r   r   get_rois_crossedI   s    r*   c             C   s   t j| | ft jd}xd|D ]\}xVt|D ]J\}}x@t|D ]4\}}||kr:||ks:||d |d f  d7  < q:W q(W qW ||j }|S )N)dtyper   )r   zerosuint	enumerateT)n_roislist_of_roi_crossed_listsconnectivity_matrixr%   Zidx_iZroi_iZidx_jZroi_jr   r   r   get_connectivity_matrixY   s    
(
r3   c             C   s   t | }d	}g }g }xt| D ]x\}}	tttd| | }
|
|krb|
d dkrb|
}td|  t|	d ||}t |dkr|jt| |j| qW t	||}|t | }t
jd||d | | t
jd|| d|d |   t
jd ||fS )
z-Create the intersection arrays for each fiberr   d   r   z%4.0f%%zpFound %i (%f percent out of %i fibers) fibers that start or terminate in a voxel which is not labeled. (orphans)g      Y@zValid fibers: %i (%f percent)z4Returning the intersecting point connectivity matrix)r   r.   r   roundr   printr*   r   r   r3   ifloggerinfo)Zstreamlinesr#   r$   r0   Zn_fibZpcfinal_fiber_idsr1   iZfiberZpcNr%   r2   disr   r   r   create_allpoints_cmate   s0    


r=   c             C   s  t | }tj|ddf}tj|ddf}xt| D ]x\}}|d }|dddf ||dddf< |dddf ||dddf< |dddf ||dddf< |dddf ||dddf< t||ddf t|d  ||ddf< t||ddf t|d  ||ddf< t||ddf t|d  ||ddf< t||ddf t|d  ||ddf< t||ddf t|d  ||ddf< t||ddf t|d  ||ddf< q4W tjd ||fS )	a  Create the endpoints arrays for each fiber.

    Parameters
    ----------
    fib : array-like
      the fibers data
    voxelSize : tuple
      3-tuple containing the voxel size of the ROI image

    Returns
    -------
    endpoints : ndarray of size [#fibers, 2, 3]
      containing for each fiber the index of its first and last point in the voxelSize volume
    endpointsmm : ndarray of size [#fibers, 2, 3]
      endpoints in millimeter coordinates

    r   r   r   Nr   zReturning the endpoint matrixr5   r5   )r   r   r,   r.   r   r   r8   r9   )fibr$   n	endpointsendpointsmmr;   fifr   r   r   create_endpoints_array   s"    (((((,
rD   c       F      C   s  ddl j}i }tjd tj|d }	tj|d }
tjd|  tjj| d\}}t	||d< tj
|}tj|j}|jj }t||\}}tjd	|	 tj|	| tjd
|
 tj|
| t	|}tjd| tj|df}g }g }t|\}}}|dkr
tj|}n |dkr tj|}n
td|t	|j }d|jt|j d  kr\|j }ntj }x|jddD ]p\}}|jt|f| ttjtj tj!|t|d kdd}t|d |d |d  g|jt| d< qrW |rvtjd t"||||\}} tj|d }!t#|||!| |d< tj$|}|j }"tj%tj$|}#tj&|#dd }#|"j'dd |#j(ddD  d}$xt)|j*d D ]}%ydt|||%ddf ||%ddf ||%ddf f }&t|||%ddf ||%ddf ||%ddf f }'W n$ t+k
r   tj,d|% P Y nX |&dks0|'dkrH|$d7 }$dJ||%df< q|&|ks\|'|krtj,d tj,d tj,d |&|' tj,d! q|'|&k r|&}(|'}&|(}'|&||%df< |'||%df< |j-|&|'g |j-|% |j.|&|'rd"|j/|& |' kr|j/|& |' d" j-|% n|j0|&|'|%gd# qW g })|r6| }*n|}*x$|*D ]}+|)j-t1||+ d  q@W tj2|)},tj2|td$}-tjd%|$|$d& | | tjd'||$ d(|$d& |   tj }.|.j3| |.j }/|.j }0|.j }1xZ|j(ddD ]H\}}2}|j4||2 i }3d"|krt	|d" |3d)< tj |-dddf t|k|-dddf t|2k@ d }+t5tj|,|+ |3d*< t5tj6|,|+ |3d+< t5tj7|,|+ |3d,< n d|3d)< d|3d*< d|3d+< d|3d,< ||2ks|j0||2f|3 d"|kr|.j0||2|3d) d- |/j0||2|3d* d- |0j0||2|3d+ d- |1j0||2|3d, d- qW tjd.| tj8|tj| tj9|.td$}4d)|4i}5tj9|/tj:d$}6d/|6i}7tj9|0tj:d$}8d0|8i}9tj9|1tj:d$}:d,|:i};|rt|\}}}tj|d1 | }<tjd2|< tj8|"|< t|\}}}|d3ksd3}|| }tjd4| |j;||5 |rdd5|i}=tj|d1 | }>tjd6|> |j;|>|= tj|d7 | }?tjd8|? |j;|?|7 tj|d9 | }@tjd:|@ |j;|@|9 tj|d; | }Atjd<|A |j;|A|; tj|d= }Btjd>|B tj|B|, tj|d? }Ctjd@|C tj|Ctj2|tj<d$ tj|dA }DtjdB|D tj|D|- tjdC tj|dD }!t#|||!||dE< t5|dE t5|d  d( |dF< t5|d t5|d  d( |dG< tj|dH }EtjdI|E |j;|E| dS )KzGCreate the connection matrix for each resolution using fibers and ROIs.r   NzRunning cmat functionz_endpoints.npyz_endpointsmm.npyzReading Trackvis file %sFZ
orig_n_fibzSaving endpoint array: %szSaving endpoint array in mm: %szNumber of fibers: %ir   z.pckz.graphmlzUnable to read file:dn_positionT)datadn_correspondence_idr   )r   z)Filtering tractography from intersectionsz#_intersections_streamline_final.trkZintersections_n_fibc             S   s   | d S )Nr   r   )r'   r   r   r   <lambda>  s    zcmat.<locals>.<lambda>c             s   s"   | ]\}}}|||d  fV  qdS )weightNr   ).0uvdr   r   r   	<genexpr>  s    zcmat.<locals>.<genexpr>zNAN INDEXERROR EXCEPTION OCCURED FOR FIBER %s. PLEASE CHECK ENDPOINT GENERATIONzGStart or endpoint of fiber terminate in a voxel which is labeled higherz6than is expected by the parcellation node information.zStart ROI: %i, End ROI: %izThis needs bugfixing!fiblist)rO   )r+   zpFound %i (%f percent out of %i fibers) fibers that start or terminate in a voxel which is not labeled. (orphans)g      Y@zValid fibers: %i (%f%%)r4   Znumber_of_fibersZfiber_length_meanZfiber_length_medianZfiber_length_std)rI   zWriting network as %sZmean_fiber_lengthZmedian_fiber_lengthZ_intersectionsz"Writing intersection network as %sz.matzWriting matlab matrix as %sintersectionsz!Writing intersection matrix as %sZ_mean_fiber_lengthz-Writing matlab mean fiber length matrix as %sZ_median_fiber_lengthz/Writing matlab median fiber length matrix as %sZ_fiber_length_stdz2Writing matlab fiber length deviation matrix as %sz_final_fiberslength.npyz&Storing final fiber length array as %sz_filtered_fiberslabel.npyz-Storing all fiber labels (with orphans) as %sz_final_fiberslabels.npyz-Storing final fiber labels (no orphans) as %sz6Filtering tractography - keeping only no orphan fibersz_streamline_final.trkZendpoint_n_fibZendpoints_percentZintersections_percentz_statistics.matz'Saving matrix creation statistics as %sr5   )=Zscipy.ioior8   r9   opabspathnbtrackvisreadr   loadr   
asanyarraydataobjheaderZ	get_zoomsrD   saver,   r   nxZread_gpickleread_graphml	TypeErrornodesr   copyGraphadd_noder   tuplemeanwhereflipudr=   save_fibersZmatrixZfrom_numpy_matrixZrelabel_nodesZadd_weighted_edges_fromedgesr   r   
IndexErrorerrorr   Zhas_edgeZedgeZadd_edger   r   Zadd_nodes_fromZremove_edger   ZmedianZstdwrite_gpickleZto_numpy_matrixZfloat64ZsavematZint32)FZ
track_fileroi_fileresolution_network_fileZmatrix_nameZmatrix_mat_nameendpoint_namerP   siostatsZen_fnameZ
en_fnamemmr>   hdrZroir#   ZroiVoxelSizer@   rA   r?   ZfiberlabelsZfinal_fiberlabelsZfinal_fibers_idxpathnameextgpZnROIsGrK   rM   r   Zintersection_matrixr:   Zfinalfibers_fnameIHr<   r;   ZstartROIZendROItmpZfinalfiberlengthZfinal_fibers_indicesidxZfinal_fiberlength_arrayZfinal_fiberlabels_arrayZnumfibZfibmeanZ	fibmedianZfibdevrL   ZdiZnumfib_mlabZnumfib_dictZfibmean_mlabZfibmean_dictZfibmedian_mlabZfibmedian_dictZfibdev_mlabZfibdev_dictZintersection_matrix_nameZintersect_dictZintersection_matrix_mat_namemean_fiber_length_matrix_namemedian_fiber_length_matrix_namefiber_length_std_matrix_nameZfiberlengths_fnameZfiberlabels_fnameZfiberlabels_noorphans_fnameZout_stats_filer   r   r   cmat   st   









0


.2



"








  r~   c             C   sX   | j  }g }x|D ]}|j||  qW t|}||d< tjd| tjj||| |S )z9Stores a new trackvis file fname using only given indicesZn_countz%Writing final non-orphan fibers as %s)r`   r   r   r8   r9   rT   rU   write)ZoldhdrZoldfibfnameindicesZhdrnewZ
outstreamsr;   Z	n_fib_outr   r   r   rg     s    
rg   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jddddZ	edd	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dS )CreateMatrixInputSpecTzFreesurfer aparc+aseg file)exists	mandatorydesczTrackvis tract filez2Parcellation files from Connectome Mapping ToolkitFzuCounts all of the fiber-region traversals in the connectivity matrix (requires significantly more computational time))
usedefaultr   z*NetworkX graph describing the connectivity)genfiler   zcmatrix.matz)Matlab matrix describing the connectivityzBMatlab matrix describing the mean fiber lengths between each node.zMMatlab matrix describing the deviation in fiber lengths connecting each node.zIMatlab connectivity matrix if all region/fiber intersections are counted.z&Name for the generated endpoint arraysN)__name__
__module____qualname__r	   rl   
tract_filerm   r   Boolcount_region_intersectionsout_matrix_fileout_matrix_mat_file%out_mean_fiber_length_matrix_mat_file'out_median_fiber_length_matrix_mat_file$out_fiber_length_std_matrix_mat_file out_intersection_matrix_mat_fileout_endpoint_array_namer   r   r   r   r     s8   
r   c               @   s   e Zd ZedddZedddZeedddZeedddZedddZ	edddZ
edddZedddZed	ddZed
ddZedddZedddZedddZedddZedddZedddZeedddZedddZdS )CreateMatrixOutputSpecz*NetworkX graph describing the connectivityT)r   r   z:All of the gpickled network files output by this interfacez5All of the MATLAB .mat files output by this interfacez)Matlab matrix describing the connectivityzBMatlab matrix describing the mean fiber lengths between each node.zDMatlab matrix describing the median fiber lengths between each node.zMMatlab matrix describing the deviation in fiber lengths connecting each node.z2Saved Numpy array with the endpoints of each fiberzCSaved Numpy array with the endpoints of each fiber (in millimeters)z0Saved Numpy array with the lengths of each fiberz0Saved Numpy array with the labels for each fiberz;Saved Numpy array with the labels for each non-orphan fiberz[TrackVis file containing only those fibers originate in one and terminate in another regionz=TrackVis file containing all fibers which connect two regionszDSaved Matlab .mat file with the number of fibers saved at each stageN)r   r   r   r	   matrix_fileintersection_matrix_filer   matrix_filesmatlab_matrix_filesmatrix_mat_fileintersection_matrix_mat_file!mean_fiber_length_matrix_mat_file#median_fiber_length_matrix_mat_file fiber_length_std_matrix_mat_fileendpoint_fileendpoint_file_mmfiber_length_filefiber_label_filefiber_labels_noorphansfiltered_tractography&filtered_tractography_by_intersectionsfiltered_tractographies
stats_filer   r   r   r   r     s^   







r   c               @   s0   e Zd ZdZeZeZdd Zdd Z	dd Z
dS )	CreateMatrixac  
    Performs connectivity mapping and outputs the result as a NetworkX graph and a Matlab matrix

    Example
    -------

    >>> import nipype.interfaces.cmtk as cmtk
    >>> conmap = cmtk.CreateMatrix()
    >>> conmap.roi_file = 'fsLUT_aparc+aseg.nii'
    >>> conmap.tract_file = 'fibers.trk'
    >>> conmap.run()                 # doctest: +SKIP
    c             C   sN  t | jjr.t| jj\}}}tj|d }n
| jd}tj| jj}t|\}}}|dkshd}|| }t | jjrtj| jj}ntj| jd}	t | jj	rtj| jj	}
ntj| jd}t | jj
rtj| jj
}ntj| jd}t | jjst| jj\}}}tj|}ntj| jj}t| jj| jj| jj|||| jj |S )Nz.pckz.matz_mean_fiber_length.matz_median_fiber_length.matz_fiber_length_std.mat)r   inputsr   r   rR   rS   _gen_outfilenamer   r   r   r   r   r   r~   rl   rm   r   )selfruntimerr   rs   _r   r   rt   r   r{   r   r|   r   r}   rn   r   r   r   _run_interfaceY  sJ    

zCreateMatrix._run_interfacec       
      C   s.  | j  j }t| jjrHt| jj\}}}tj|d }tj|d }n tj| jd}tj| jd}||d< ||d< tj| jj	}t|\}}}|dksd}|| }||d< t| jj
rtj| jj
|d< ntj| jd|d< t| jjrtj| jj|d	< ntj| jd
|d	< t| jjr<tj| jj|d< ntj| jd|d< t| jjrrtj| jj|d< ntj| jd|d< t| jjr| jj}	tj| jjd |d< tj| jjd |d< tj| jjd |d< tj| jjd |d< tj| jjd |d< nlt| jj\}}	}tj|	d |d< tj|	d |d< tj|	d |d< tj|	d |d< tj|	d |d< | jjr||g|d< |d |d |d	 |d |d g|d< n*|g|d< |d |d |d	 |d g|d< tj|	d |d< tj|	d |d< |d |d g|d< tj|	d  |d!< |S )"Nz.pckz_intersections.pckr   r   z.matr   r   z_mean_fiber_length.matr   z_median_fiber_length.matr   z_fiber_length_std.matr   z_intersections.matz_endpoints.npyr   z_endpointsmm.npyr   z_final_fiberslength.npyr   z_filtered_fiberslabel.npyr   z_final_fiberslabels.npyr   r   r   z_streamline_final.trkr   z#_intersections_streamline_final.trkr   r   z_statistics.matr   )output_specgetr   r   r   r   rR   rS   r   r   r   r   r   r   r   r   r   )
r   outputsrr   rs   r   r   Zout_intersection_matrix_filer   rt   rn   r   r   r   _list_outputs  s    

zCreateMatrix._list_outputsc             C   sd   |j dr*t| jjr*t| jj\}}}n2t| jjrJt| jj\}}}nt| jj\}}}|| S )Nmat)endswithr   r   r   r   r   r   )r   rt   r   rs   r   r   r   r   
  s    zCreateMatrix._gen_outfilenameN)r   r   r   __doc__r   
input_specr   r   r   r   r   r   r   r   r   r   H  s   9xr   c               @   s`   e Zd ZeddddZeddgddZejdgdd	Ze	dgd
dZ
edddZedddZdS )ROIGenInputSpecTzFreesurfer aparc+aseg file)r   r   r   use_freesurfer_LUTz0Custom lookup table (cf. FreeSurferColorLUT.txt))r   xorr   LUT_filezNBoolean value; Set to True to use default Freesurfer LUT, False for custom LUT)r   r   zFreesurfer main directory)requiresr   z0Region of Interest file for connectivity mapping)r   r   z'Label dictionary saved in Pickle formatN)r   r   r   r	   aparc_aseg_filer   r   r   r   r   freesurfer_dirout_roi_fileout_dict_filer   r   r   r   r     s   
r   c               @   s    e Zd ZeddZeddZdS )ROIGenOutputSpecz0Region of Interest file for connectivity mapping)r   z'Label dictionary saved in Pickle formatN)r   r   r   r	   rl   	dict_filer   r   r   r   r   *  s   
r   c               @   s0   e Zd ZdZeZeZdd Zdd Z	dd Z
dS )	ROIGena  
    Generates a ROI file for connectivity mapping and a dictionary file containing relevant node information

    Example
    -------

    >>> import nipype.interfaces.cmtk as cmtk
    >>> rg = cmtk.ROIGen()
    >>> rg.inputs.aparc_aseg_file = 'aparc+aseg.nii'
    >>> rg.inputs.use_freesurfer_LUT = True
    >>> rg.inputs.freesurfer_dir = '/usr/local/freesurfer'
    >>> rg.run() # doctest: +SKIP

    The label dictionary is written to disk using Pickle. Resulting data can be loaded using:

    >>> file = open("FreeSurferColorLUT_adapted_aparc+aseg_out.pck", "r")
    >>> file = open("fsLUT_aparc+aseg.pck", "r")
    >>> labelDict = pickle.load(file) # doctest: +SKIP
    >>> labelDict                     # doctest: +SKIP
    c           T   C   s  | j j}t|\}}}tjd||  tj|}tj|j	}tj
|}tj|}	tjd|	 d}
| j jr| j jd | _tjd| j d}nT| j j rt| j jrtj| j j| _t| j\}}}tjd||  |}nd}d	}
t| j jrtj| j j}ntj|d
 | d }t| j jr.tj| j j}ntj|d
 | d }|
r*tjdtj| j tj| jdddddddgddddd}tj|}||	k rtjd tjd  tjd!| i }xVtd|D ]H}|| d || d || d || d || d g||| d < qW tjd" tj| i }dd#gdd$gdd%gdd&gdd'gd(d)gd*d+gd,d-gd.d/gd0d1gd2d3gd4d5gd6d7gd8d9gd:d;gd<d=gd>d?gd@dAgdBdCgdDdEgdFdGgdHdIgdJdKgdLdMgdNdOgdPdQgdRdSgdTdUgdVdWgdXdYgdZd[gd\d]gd^d_gd`dagdbdcgdddegdfdggdhdigdjdkgdldmgdndogdpdqgdrdsgdtdugdvdwgdxdygdzd{gd|d}gdcd~gdedgdgdgdidgdmdgdodgddgddgddgdkdgddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgdd0gdd2gdd4gdd6gddPgdd>gdd@gdd<ggS}tj|jtjd}x2|D ]*}|d |||d k< |d ||d < q<W tjd tj
|}tj|}tjd| i }i }x|D ]}y||  |
r|| |d< W n   tjd| Y nX |
r~i }|| d |d< || d || d || d g|d< || d |d< |||< qW tj||j|j}tjd| tj|| |
rtjd| t|d}tj || W d Q R X |S )NzUsing Aparc+Aseg file: %szNumber of labels in image: %sTz/FreeSurferColorLUT.txtzUsing Freesurfer LUT: %sfsLUTzUsing Custom LUT file: %s	hardcodedFr   z.niiz.pckzLookup table: %s   r   r   r   r      #indexlabelRrv   BAr   |S30)namesformats)ZskiprowsZusecolscommentsr+   zBLUT file provided does not contain all of the regions in the imagezRemoving unmapped regionszNumber of labels in LUT: %szPrinting LUT label dictionaryi  i  i  i  i     i     i     i  	   i  
   i     i     i     i     i     i     i     i     i     i     i     i     i     i     i     i     i     i     i     i     i     i      i  !   i  "   i  #   1   $   2   %   3   &   4   '   :   (   5   )   6   *   i  +   i  ,   i  -   i  .   i  /   i  0   i  i  i  i   i  i  i  7   i  8   i  9   i  i  ;   i  <   i  =   i  >   i  ?   i  @   i  A   i  B   i  C   i  D   i  E   i	  F   i  G   i  H   i  I   i  J   i
  K   i  L   M   N   O   P   Q   R   S   )r+   zGrey matter mask createdz Number of grey matter labels: %sZ
originalIDz Label %s not in provided mappinglabelscolorsazSaving ROI File to %sz-Saving Dictionary File to %s in Pickle formatw)r   r   r   rv   r   r   )r   r   r   r   r   r   )!r   r   r   r8   r9   rT   rW   r   rX   rY   uniquesizer   r   r   r   rR   rS   r   r   Zloadtxtrj   r   r,   r   r-   ZNifti1ImageZaffinerZ   r[   openpickledump) r   r   r   Z	aparcpathZ	aparcnameZaparcextZniiAPARCimgZniiAPARCdataZniiDataLabelsZnumDataLabels
write_dictprefixlutpathlutnamelutextrl   r   ZLUTlabelsRGBAZnumLUTLabelsZLUTlabelDictr  ZmapDictZMAPPINGZniiGMmaZgreyMaskLabelsZnumGMLabelsZ	labelDictZGMlabelDictr   	roi_imagerC   r   r   r   r   H  sP   









 









zROIGen._run_interfacec             C   sx   | j  j }t| jjr,tj| jj|d< ntj| jd|d< t| jjr`tj| jj|d< ntj| jd|d< |S )Nrl   Zniir   Zpck)	_outputsr   r   r   r   rR   rS   r   r   )r   r   r   r   r   r     s    zROIGen._list_outputsc             C   sf   t | jj\}}}| jjr d}n2| jj rNt| jjrNt | jj\}}}|}nd}|d | d | S )Nr   r   r   .)r   r   r   r   r   r   )r   rt   r   rs   r)  r*  r+  r,  r   r   r   r     s    zROIGen._gen_outfilenameN)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   /  s    Dr   c       
      C   s   t j }t j|}tj| }tj|j}x~|jddD ]n\}}|j	t
|f| ttjtjtj|t
|d kdd}	t|	d |	d |	d  g|jt
| d< q6W t j|| |S )	NT)rF   rG   r   )r   r   r   rE   )r\   ra   r]   rT   rW   r   rX   rY   r_   rb   r   rc   rd   re   rf   rk   )
rl   rm   out_filenamerv   ru   r.  r#   rK   rM   r   r   r   r   create_nodes#  s    

$.r2  c               @   s6   e Zd ZeddddZeddddZeddddZdS )	CreateNodesInputSpecTzRegion of interest file)r   r   r   z1Parcellation file from Connectome Mapping Toolkitznodenetwork.pckz/Output gpickled network with the nodes defined.)r   r   N)r   r   r   r	   rl   rm   r1  r   r   r   r   r3  5  s   r3  c               @   s   e Zd ZeddZdS )CreateNodesOutputSpecz/Output gpickled network with the nodes defined.)r   N)r   r   r   r	   node_networkr   r   r   r   r4  C  s   r4  c               @   s(   e Zd ZdZeZeZdd Zdd Z	dS )CreateNodesam  
    Generates a NetworkX graph containing nodes at the centroid of each region in the input ROI file.
    Node data is added from the resolution network file.

    Example
    -------

    >>> import nipype.interfaces.cmtk as cmtk
    >>> mknode = cmtk.CreateNodes()
    >>> mknode.inputs.roi_file = 'ROI_scale500.nii.gz'
    >>> mknode.run() # doctest: +SKIP
    c             C   s<   t jd t| jj| jj| jj t jdtj| jj |S )NzCreating nodes...zSaving node network to %s)	r8   r9   r2  r   rl   rm   r1  rR   rS   )r   r   r   r   r   r   X  s    

zCreateNodes._run_interfacec             C   s"   | j  j }tj| jj|d< |S )Nr5  )r/  r   rR   rS   r   r1  )r   r   r   r   r   r   b  s    zCreateNodes._list_outputsN)
r   r   r   r   r3  r   r4  r   r   r   r   r   r   r   r6  G  s
   
r6  )F)F)*r&  os.pathrr   rR   numpyr   ZnibabelrT   Znetworkxr\    r   Zutils.filemanipr   baser   r   r   r	   r
   r   r   r   	getLoggerr8   r   r*   r3   r=   rD   r~   rg   r   r   r   r   r   r   r2  r3  r4  r6  r   r   r   r   <module>   s:   
(

-!9
  (E M u