3
dm                 @   s   d dl Z d dljZd dlZd dlZd dlZd dl	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 ddlmZ ejdZd	d
 Zdd Zdd Zdd 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   )BaseInterfaceLibraryBaseInterfaceBaseInterfaceInputSpectraitsFileTraitedSpec	Directory	isdefined   )have_cmpznipype.interfacec             C   s$  dd l }ddlm} tjd tjd tjtj|| d}tjtj}g }|j	j
 }	d|	_x,dQD ]$}
|	jd| d	 |
 }|j| qbW x0|D ](}ytjtjd
| W q   Y qX qW d|k rdRdSdTdUg} nfd|k rdVdWg} nPd|krdXdYdZd[g}n8d#|krd\d]d^d_g}n d`dadbdcdddedfdgdhdidjdkdldmg}|	j }x|D ]}d<| |d tj|| |d |	j|d= tj||d> f }||| tjd? d@|dA  }dB| |d tj||dC |f }tj| ||| tjd? tjtjdD  tj|dE}tj|dF}tj|dG}tj|dH}qJW tjtj|ddE| tjtj|ddF| tjtj|ddG| tjtj|ddH| dI||||tjtj|| dJdKtj|dLf }||| |dM|  | dNtj|| tj|| f }||| dOtj|| tj|| f }||| tjdP d S )nNr   )runCmdz1Create the cortical labels necessary for our ROIsz1=================================================labelLausanne2008lhrhfs_label_subdir_name.Z33myatlas_36_rh.gcsrh.myaparc_36.annotregenerated_rh_36
myaparc_36myatlas_60_rh.gcsrh.myaparc_60.annotregenerated_rh_60
myaparc_60myatlas_36_lh.gcslh.myaparc_36.annotregenerated_lh_36myatlas_60_lh.gcslh.myaparc_60.annotregenerated_lh_60Z60Z125myatlas_125_rh.gcsrh.myaparc_125.annotregenerated_rh_125myaparc_125myatlas_125_lh.gcslh.myaparc_125.annotregenerated_lh_125Z250myatlas_250_rh.gcsrh.myaparc_250.annotregenerated_rh_250myaparc_250myatlas_250_lh.gcslh.myaparc_250.annotregenerated_lh_250myatlasP1_16_rh.gcsrh.myaparcP1_16.annotregenerated_rh_500myaparcP1_16myatlasP17_28_rh.gcsrh.myaparcP17_28.annotmyaparcP17_28myatlasP29_36_rh.gcsrh.myaparcP29_36.annotmyaparcP29_36myatlasP1_16_lh.gcslh.myaparcP1_16.annotregenerated_lh_500myatlasP17_28_lh.gcslh.myaparcP17_28.annotmyatlasP29_36_lh.gcslh.myaparcP29_36.annotz6mris_ca_label %s %s "%s/surf/%s.sphere.reg" "%s" "%s" r   r   z-----------z--annotation "%s"   z<mri_annotation2label --subject %s --hemi %s --outdir "%s" %sr   SUBJECTS_DIRzrh.unknown.labelzlh.unknown.labelzrh.corpuscallosum.labelzlh.corpuscallosum.labelzcmri_label2vol --label "%s" --label "%s" --label "%s" --label "%s" --temp "%s" --o  "%s" --identity mrizorig.mgzzcc_unknown.nii.gzzmris_volmask %sz<mri_convert -i "%s/mri/ribbon.mgz" -o "%s/mri/ribbon.nii.gz"z8mri_convert -i "%s/mri/aseg.mgz" -o "%s/mri/aseg.nii.gz"z[ DONE ])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"   r#   r   )r   r+   r,   r-   r.   )r   r   r   r   r   )r   r/   r0   r1   r.   )r   r!   r"   r#   r   )r   r   r   r   r   )r   r2   r3   r4   r5   )r   r6   r7   r4   r8   )r   r9   r:   r4   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>   r5   )r   r?   r@   r>   r8   )r   rA   rB   r>   r;   )r   r!   r"   r#   r   )r   r(   r)   r*   r'   )r   r/   r0   r1   r.   )cmpcmp.utilr   ifloggerinfoopjoinabspathcurdirconfigurationPipelineConfigurationparcellation_scheme_get_lausanne_parcellationappendosmakedirs
get_loggerZget_lausanne_atlasenvironshutilcopy)
subject_idsubjects_dirfs_dirparcellation_namerF   r   Zfs_label_dir
output_dirpaths
cmp_confighemiZspathpcomplogoutZmris_cmdZannotZ
mri_an_cmdZrhunZlhunZrhcoZlhcomri_cmd rf   E/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/cmtk/parcellation.pycreate_annot_label   s   






                

        

                
                                                                        











rh   c       0      C   s:  ddl }ddlm} tjd tjtj}tj|| }|j	j
 }d|_|j }	|jd| }
|
d }tjtj|dd}tj|j}tj|d	k}tj|d
k}tj|d |d f}tj|d |d f}tj|d |d f}d/}tj|d }tj|dd}xvt|d D ]f}x^t|d D ]N}xFt|d D ]6}||||g }tjtjtj||||||f< q4W q"W qW tjd tj|jd|  tjd tj|}tjd0tjd}d}x&|jddD ]\}}|d }tj| tj| |d dkr
d}n|d dkrd}|d dkrtj| tjd tjd|d  tjd|d  tjd ||j  tjd tj|t |d! k} t |d" || < n|d d#krtj| tjd tjd|d  tjd|d  tjd ||j  tjd tj||
d$ | }!d%||d f }"d&tj|!|"tj|dd'tj|d(f }#||#|	 tjtj|d(}$tj|$j}%tj|%dk} t |d" || < tjd)| }&|j!}'|'j" }(|(j#tj$ |	jd*|&  tj%||j&|(})tj'|)|& qW tjd+ |dkr6tjd, xt|j(D ]}*|||* ||* ||* f dkrt)||||* ||* ||* fdd-}+|+j" },d|,tj*|+dk< tj||,}-tj+|-|-tj*|-dk< tj,|+tj*|-tj-|-k }.|.j(dkrtj.|.}/tj/|/}.|.|||* ||* ||* f< qW tjd.| }&tjd*|& tj%||j&|(})tj'|)|& tjd+ dS )1zvCreates the ROI_%s.nii.gz files using the given parcellation information
    from networks. Iteratively create volume.r   N)r   zCreate the ROIs:r   node_information_graphmlrE   zaseg.nii.gzr   *   r   r      Zfloat32)dtypezWorking on parcellation: z========================   T)dataZdn_hemisphereleftr   rightr   	dn_regionZsubcorticalz---------------------zWork on brain region: %szFreesurfer Name: %sZ	dn_fsnamezRegion %s of %sZdn_fs_aseg_valdn_correspondence_idcorticalr   z%s.%s.labelz:mri_label2vol --label "%s" --temp "%s" --o "%s" --identityzorig.mgzz
tmp.nii.gzzROI_%s.nii.gzzSave output image to %sz[ DONE ]zDilating cortical regions...)positionfillzROIv_%s.nii.gz)rk   rk   rk   )rm   rm   rm   )0rF   rG   r   rH   rI   rJ   rL   rM   rK   rN   rO   rP   rU   rQ   nbloadnp
asanyarraydataobjwhereZconcatenatearrayzerosrangesqrtsummultiplynxread_graphmlZint16nodesZnumber_of_nodesintheaderrX   Zset_data_dtypeZuint16Nifti1ImageaffinesavesizeextractZnonzeroZamaxint_ZaminZbincountZargmax)0rY   rZ   r[   r\   dilationrF   r   r]   r_   rc   ZparvalpgpathasegasegdZidxrZidxlZxxyyzzshapecenterdistxyzZdistxyzpgZroiscountbrkbrvr`   idxZ	labelpathfnamere   tmpZtmpdZout_roihdrZhdr2imgjlocalmaskZthisdistvaluecountsrf   rf   rg   
create_roiM  s    

4















 "

 r   c       "   
   C   sv  dd l }dd ljj}tjd tj|| }|jj	 }d|_
|jd| d }tjtj|dd}tj|j}	tj|	j}
tj|	dk}tj|	dk}d	|
|< d	|
|< tjtj|dd
}tj|j}|j}tj|j}tj|j}tjd8}d	|d	d d df< d	|d d d	df< d	|d	d	d d f< tjd9}d	|d	d d d	f< d	|d d d	d	f< d	|d	d	d d f< tj|dk|dkB |dkB |dkB |dkB |dkB |dkB |dkB }d	||< |||||}tj|dk|dkB |dkB |dkB }d||< tj|dk|dkB |dkB |dkB |dkB |dkB |dkB |dkB |dkB |dkB }x$d:D ]}tj||k}d	||< qJW tj|j}xPd;D ]H}tj||k}tj|j}d	||< |||}tj|d	k}d	||< q|W x$d<D ]}tj||k}d	||< qW tj|j}tj|d)k}d	||< tj|dk|dkB |dkB |dkB }d|
|< tjd* tjtj|d+d,}tj|j}tj|dk}tjd- d	|
|< tjd.| tjtjtjd/| }tj|j}|jd |
jd ksttj|}x\|jd0d1D ]L\}}|d2 d3krtjd4|d2 |d5  tj|t|d5 k}d|
|< qW tj|dd6} tj|
|j|j}!tjd7|  tj|!|  d S )=Nr   zCreate white matter maskr   ri   rE   zribbon.nii.gzx      r   zaseg.nii.gzr      r   rC   +      2      ?   
   1            ,   H   K   L            3               4   5   6   :      zWRemoving lateral ventricles and eroded grey nuclei and brainstem from white matter maskr   zcc_unknown.nii.gzz*Add corpus callosum and unknown to wm maskzFLoading ROI_%s.nii.gz to subtract cortical ROIs from white matter maskzROI_%s.nii.gzT)rn   rq   rs   z-Subtracting region %s with intensity value %srr   zfsmask_1mm.nii.gzzSave white matter mask: %s)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   )rF   Zscipy.ndimage.morphologyZndimageZ
morphologyrH   rI   rJ   rK   rN   rO   rP   rQ   rv   rw   rx   ry   rz   r}   r   r{   Zbinary_erosionrM   AssertionErrorr   r   r   r   r   r   r   r   )"rY   rZ   r[   r\   rF   Zndr_   r   ZfsmaskZfsmaskdZwmmaskZidx_lhZidx_rhr   r   ZimerodeZcsfAZcsfBZse1ser   iZgr_nclr   	remainingZccunZccundZroiZroidr   r   r   Zwm_outr   rf   rf   rg   create_wm_mask  s    



B&
R



&


r   c             C   sZ  ddl m} tj|| }tjj }d|_|j }tj	tj
}	tjd|	 tj|ddtj	dftj|ddtj	dftj|ddtj	dftj|d	d
tj	d
fg}
|
jtj	d| tj	df |dkr|
jtj	d| tj	df tj|ddd}x\|
D ]T}tjd|d  tj|d s2td|d  d||d |d f }||| qW d S )Nr   )r   r   z"Cropping and moving datasets to %srE   zaseg.nii.gzzribbon.nii.gzzfsmask_1mm.nii.gzr   zcc_unknown.nii.gzzROI_%s.nii.gzzROI_HR_th.nii.gzTzROIv_%s.nii.gzzROIv_HR_th.nii.gzorigz001.mgzzProcessing %s:zFile %s does not exist.z.mri_convert -rl "%s" -rt nearest "%s" -nc "%s"r   )rG   r   rJ   rK   rF   rN   rO   rP   rU   rL   rM   rH   rI   rR   exists	Exception)rY   rZ   r[   r\   out_roi_filer   r   r_   rc   r]   Zdsr   dre   rf   rf   rg   crop_and_move_datasetsi  s4    

r   c             C   s8  t j|| jd| }t jt|jt}t jt|jjt}t jt| jjt}t jt	|jt}t jt|jt}	||d  }
t j
|
dj }|||
  }||d  |d  }t j||j }|	||  }	| |d |d |d |d |d |d f ||d |	d |d |	d |d |	d f< |S )a  Extract voxel neighbourhood

    Parameters
    ----------
    Z : array-like
        the original data
    shape : tuple
        tuple containing neighbourhood dimensions
    position : tuple
        tuple containing central point indexes
    fill : float
       value for the padding of Z

    Returns
    -------
    R : ndarray
        the neighbourhood of the specified point in Z

    )rl   r   r   r   )rx   Zonesrl   r|   listZastyper   r   r}   lenmaximumtolistZminimum)Zr   rt   ru   RPZRsZsZR_startZR_stopZZ_startZZ_start_corZZ_stopZ
Z_stop_corrf   rf   rg   r     s"    Br   c               @   sh   e Zd ZejdddZejddddddgdd	Zedd
dZ	edddZ
edddZejddddZdS )ParcellateInputSpecTz
Subject ID)	mandatorydescZscale500Zscale33Zscale60Zscale125Zscale250)
usedefaultzFreesurfer main directory)r   r   zFreesurfer subjects directoryz0Region of Interest file for connectivity mapping)Zgenfiler   Fz5Dilate cortical parcels? Useful for fMRI connectivity)r   r   N)__name__
__module____qualname__r   StringrY   Enumr\   r   freesurfer_dirrZ   r	   r   ZBoolr   rf   rf   rf   rg   r     s   
r   c               @   sh   e Zd ZedddZe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ZdS )ParcellateOutputSpecTz0Region of Interest file for connectivity mapping)r   r   z5Region of Interest file for fMRI connectivity mapping)r   zWhite matter mask filez?Image file with regions labelled as unknown cortical structures)r   r   z(Image file detailing the cortical ribbonzJAutomated segmentation file converted from Freesurfer "subjects" directoryzEROI image resliced to the dimensions of the original structural imagezMdilated ROI image resliced to the dimensions of the original structural imageN)r   r   r   r	   roi_file	roiv_filewhite_matter_mask_filecc_unknown_fileribbon_file	aseg_fileroi_file_in_structural_space$dilated_roi_file_in_structural_spacerf   rf   rf   rg   r     s    

r   c               @   s:   e Zd ZdZeZeZdZdZ	dd Z
dd Zdd	d
ZdS )
Parcellatea  Subdivides segmented ROI file into smaller subregions

    This interface implements the same procedure as in the ConnectomeMapper's
    parcellation stage (cmp/stages/parcellation/maskcreation.py) for a single
    parcellation scheme (e.g. 'scale500').

    Example
    -------

    >>> import nipype.interfaces.cmtk as cmtk
    >>> parcellate = cmtk.Parcellate()
    >>> parcellate.inputs.freesurfer_dir = '.'
    >>> parcellate.inputs.subjects_dir = '.'
    >>> parcellate.inputs.subject_id = 'subj1'
    >>> parcellate.inputs.dilation = True
    >>> parcellate.inputs.parcellation_name = 'scale500'
    >>> parcellate.run()                 # doctest: +SKIP
    rF   scipyc             C   s   | j jrtjjd| j ji tjjtj| j j| j j	s<t
tjd tjd t| j j	| j j| j j| j j t| j j	| j j| j j| j j| j j t| j j	| j j| j j| j j t| j j	| j j| j j| j j| j j| j j |S )NrD   z-ROI_HR_th.nii.gz / fsmask_1mm.nii.gz CREATIONz-=============================================)inputsrZ   rS   rV   updatepathr   rJ   rK   rY   r   rH   rI   rh   r   r\   r   r   r   r   r   )selfZruntimerf   rf   rg   _run_interface  s>    





zParcellate._run_interfacec             C   s   | j  j }t| jjr,tj| jj|d< ntj| jdd|d< | jjdkrdtj| jdd|d< tjd|d< tjd	|d
< tjd|d< tjd|d< tjd|d< | jjdkrtjd|d< |S )Nr   znii.gzROITZROIvr   zfsmask_1mm.nii.gzr   zcc_unknown.nii.gzr   zribbon.nii.gzr   zaseg.nii.gzr   zROI_HR_th.nii.gzr   zROIv_HR_th.nii.gzr   )	Z_outputsgetr   r   r   rJ   rL   _gen_outfilenamer   )r   outputsrf   rf   rg   _list_outputs/  s    
zParcellate._list_outputsr   c             C   s   |d | j j d | S )N_r   )r   r\   )r   extprefixrf   rf   rg   r   B  s    zParcellate._gen_outfilenameN)r   )r   )r   r   r   __doc__r   Z
input_specr   Zoutput_specZ_pkgZimportsr   r   r   rf   rf   rf   rg   r     s   'r   )!rS   os.pathr   rJ   rW   numpyrx   Znibabelrv   Znetworkxr    r   baser   r   r   r   r	   r
   r   r   r   	getLoggerrH   rh   r   r   r   r   r   r   r   rf   rf   rf   rg   <module>   s*   
(

  3  .-