U
    f»{jZ‰ ã                   @   s‚  d dl mZ d dlmZmZ d dlZd dlZd dlm	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 dd	lmZmZ dd
lm Z m!Z!m"Z"m#Z#m$Z$m%Z% ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1 dd„ Z2dd„ Z3dZdd„Z4e.G dd„ dƒƒZ5dd„ Z6G dd„ de7ƒZ8e*d[ddœdd„ƒZ9e*d\dd„ƒZ:d]dd „Z;d^d!d"„Z<e.d_d$d%„ƒZ=d&d'„ Z>e*d`d)d*„ƒZ?d+d,„ Z@d-d.„ ZAe.dad0d1„ƒZBd2d3„ ZCe.dbd4d5„ƒZDdcd6d7„ZEddd8d9„ZFd:d;„ ZGd<d=„ ZHded?d@„ZIe*dfdCdD„ƒZJdEdF„ ZKe*dgdGdH„ƒZLe*dhdIdJ„ƒZMdKdL„ ZNdMdN„ ZOdOZPePfdPdQ„ZQdRdS„ ZRe*dddddddBd(ePdf
dTdU„ƒZSe.didXdY„ƒZTdS )jé    )Údefaultdict)Ú
hsv_to_rgbÚ
rgb_to_hsvNé   )Úread_morph_map)Úparallel_func)ÚSourceEstimateÚVolSourceEstimateÚ_center_of_massÚextract_label_time_courseÚspatial_src_adjacency)Úadd_source_space_distancesÚSourceSpacesÚ_ensure_src)Ú_find_clustersÚ_get_components)Úcomplete_surface_infoÚread_surfaceÚfast_cross_3dÚ_mesh_bordersÚ
mesh_edgesÚ	mesh_dist)Úget_subjects_dirÚ_check_subjectÚloggerÚverboseÚwarnÚcheck_random_stateÚ_validate_typeÚfill_docÚ_check_optionÚcheck_versionÚ_check_fnamec                 C   sô   | dkr|dkrdS | dkr |S |dkr,| S | \}}}}t |||ƒ\}}}|\}	}
}}t |	|
|ƒ\}}}t|| ƒ}|dk r�t||ƒ|d  }nt||ƒd| d  }|d; }|| d }|| d }t|||ƒ\}}}|| d }||||f}|S )a  Blend two colors in HSV space.

    Parameters
    ----------
    color_1, color_2 : None | tuple
        RGBA tuples with values between 0 and 1. None if no color is available.
        If both colors are None, the output is None. If only one is None, the
        output is the other color.

    Returns
    -------
    color : None | tuple
        RGBA tuple of the combined color. Saturation, value and alpha are
        averaged, whereas the new hue is determined as angle half way between
        the two input colors' hues.
    Nç      à?g       @ç      ð?)r   ÚabsÚminÚmaxr   )Zcolor_1Zcolor_2Zr_1Zg_1Zb_1Za_1Zh_1Zs_1Zv_1Zr_2Zg_2Zb_2Za_2Zh_2Zs_2Zv_2Zhue_diffÚhÚsÚvÚrÚgÚbÚaÚcolor© r0   úH/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/label.pyÚ_blend_colors   s*    r2   c                    s¼   | \}}}‰ t |||ƒ\‰‰}t |d ¡}|dkrVtd||d  ƒ}td|| ƒ}n td||d  ƒ}td|| ƒ}‡‡fdd„t |||¡D ƒ}	dd„ |	D ƒ}
‡ fd	d„|
D ƒ}t|ƒS )
aœ  Create n colors in HSV space that occupy a gradient in value.

    Parameters
    ----------
    color : tuple
        RGBA tuple with values between 0 and 1.
    n : int >= 2
        Number of colors on the gradient.

    Returns
    -------
    colors : tuple of tuples, len = n
        N RGBA tuples that occupy a gradient in value (low to high) but share
        saturation and hue with the input color.
    g      $@r#   gffffffî?é   gš™™™™™©?c                 3   s   | ]}ˆ ˆ|fV  qd S ©Nr0   )Ú.0Úv_)r(   r)   r0   r1   Ú	<genexpr>c   s     z _split_colors.<locals>.<genexpr>c                 s   s    | ]\}}}t |||ƒV  qd S r4   )r   )r5   Zh_Zs_r6   r0   r0   r1   r7   d   s     c                 3   s    | ]\}}}|||ˆ fV  qd S r4   r0   )r5   Úr_Zg_Zb_)r.   r0   r1   r7   e   s     )r   ÚnpÚsqrtr&   r'   ÚlinspaceÚtuple)r/   Únr+   r,   r-   r*   Zgradient_rangeZv_maxZv_minZ
hsv_colorsZ
rgb_colorsZrgba_colorsr0   )r.   r(   r)   r1   Ú_split_colorsI   s    r>   FÚhsvc           
      C   s’   d}| |krt d| ƒ‚ddlm} |||ƒ}t dd| d¡}|||d�}|rŽt|ƒD ]6\}}	t t |d|… |	kd¡¡rVtd	| |f ƒ‚qV|S )
a‡  Produce a list of n unique RGBA color tuples based on a colormap.

    Parameters
    ----------
    n : int
        Number of colors.
    bytes : bool
        Return colors as integers values between 0 and 255 (instead of floats
        between 0 and 1).
    cmap : str
        Which colormap to use.

    Returns
    -------
    colors : array, shape (n, 4)
        RGBA color values.
    i   z(Can't produce more than %i unique colorsr   )Úget_cmapr   F)ÚbytesNzPCould not get %d unique colors from %s colormap. Try using a different colormap.)	ÚNotImplementedErrorZmatplotlib.cmr@   r9   r;   Ú	enumerateÚanyÚallÚRuntimeError)
r=   Úbytes_ÚcmapZn_maxr@   ÚcmÚposÚcolorsÚiiÚcr0   r0   r1   Ú	_n_colorsi   s     ÿ
þrN   c                
   @   sô   e Zd ZdZed3ddœdd„ƒZdd	„ Zd
d„ Zdd„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zd4dd„Zd5dd„Zed6dd„ƒZed7d d!„ƒZed8d#d$„ƒZd9d%d&„Zd:d'd(„Zed;d*d+„ƒZed<ddœd-d.„ƒZed=ddœd/d0„ƒZd1d2„ ZdS )>ÚLabelaü  A FreeSurfer/MNE label with vertices restricted to one hemisphere.

    Labels can be combined with the ``+`` operator:

        * Duplicate vertices are removed.
        * If duplicate vertices have conflicting position values, an error
          is raised.
        * Values of duplicate vertices are summed.

    Parameters
    ----------
    vertices : array, shape (N,)
        Vertex indices (0 based).
    pos : array, shape (N, 3) | None
        Locations in meters. If None, then zeros are used.
    values : array, shape (N,) | None
        Values at the vertices. If None, then ones are used.
    hemi : 'lh' | 'rh'
        Hemisphere to which the label applies.
    comment : str
        Kept as information but not used by the object itself.
    name : str
        Kept as information but not used by the object itself.
    filename : str
        Kept as information but not used by the object itself.
    %(subject_label)s
    color : None | matplotlib color
        Default label color and alpha (e.g., ``(1., 0., 0., 1.)`` for red).
    %(verbose)s

    Attributes
    ----------
    color : None | tuple
        Default label color, represented as RGBA tuple with values between 0
        and 1.
    comment : str
        Comment from the first line of the label file.
    hemi : 'lh' | 'rh'
        Hemisphere.
    name : None | str
        A name for the label. It is OK to change that attribute manually.
    pos : array, shape (N, 3)
        Locations in meters.
    subject : str | None
        The label subject.
        It is best practice to set this to the proper
        value on initialization, but it can also be set manually.
    values : array, shape (N,)
        Values at the vertices.
    vertices : array, shape (N,)
        Vertex indices (0 based)
    r0   NÚ ©r   c
                C   s>  t |tƒstdt|ƒ ƒ‚t |t¡}t t | 	t¡¡dk¡rHtdƒ‚|	d k	rfddl
m} | |	¡}	|d kr~t t|ƒ¡}n
t |¡}|d kr¤t t|ƒdf¡}n
t |¡}t|ƒt|ƒ  krÎt|ƒksØn tdƒ‚|d krú|d k	rút |d d… ¡}|| _|| _|| _|| _|| _td |dd	�| _|	| _|| _|| _d S )
Nzhemi must be a string, not %sr   z-Vertices must be ordered in increasing order.)ÚcolorConverteré   zFvertices, values and pos need to have same length (number of vertices)éúÿÿÿF©Úraise_error)Ú
isinstanceÚstrÚ
ValueErrorÚtyper9   ÚasarrayÚintrD   ÚdiffÚastypeZmatplotlib.colorsrR   Zto_rgbaÚonesÚlenÚzerosÚopÚbasenameÚverticesrJ   ÚvaluesÚhemiÚcommentr   Úsubjectr/   ÚnameÚfilename)Úselfrd   rJ   re   rf   rg   ri   rj   rh   r/   r   rR   r0   r0   r1   Ú__init__Å   s6    



"zLabel.__init__c                 C   sf   |d | _ |d | _|d | _|d | _|d | _| dd ¡| _| dd ¡| _|d | _|d	 | _	d S )
Nrd   rJ   re   rf   rg   rh   r/   ri   rj   )
rd   rJ   re   rf   rg   Úgetrh   r/   ri   rj   )rk   Ústater0   r0   r1   Ú__setstate__ð   s    





zLabel.__setstate__c                 C   s0   t | j| j| j| j| j| j| j| j| j	d�	}|S )N)	rd   rJ   re   rf   rg   rh   r/   ri   rj   )
Údictrd   rJ   re   rf   rg   rh   r/   ri   rj   )rk   Úoutr0   r0   r1   Ú__getstate__û   s    ø	zLabel.__getstate__c                 C   sL   | j d krdn| j d }|| jd k	r.t| jƒnd7 }t| ƒ}d|| j|f S )Nú	unknown, ú, Úunnamedz<Label | %s, %s : %i vertices>)rh   ri   Úreprr`   rf   )rk   ri   Zn_vertr0   r0   r1   Ú__repr__  s    zLabel.__repr__c                 C   s
   t | jƒS ©z…Return the number of vertices.

        Returns
        -------
        n_vertices : int
            The number of vertices.
        )r`   rd   ©rk   r0   r0   r1   Ú__len__  s    zLabel.__len__c              
      s¨  t ˆttfdƒ tˆtƒr"ˆˆ S ˆjˆjkrBtdˆjˆjf ƒ‚ˆjˆjkrªdˆjˆjf }ˆjdkr|ˆ ¡ ˆ ¡  }}nˆ ¡ ˆ ¡  }}t	ˆj
ˆj
ƒ}t||||ƒS t ˆjˆj¡‰ tˆ ƒ}|�rÖ‡fdd„ˆ D ƒ}‡fdd„ˆ D ƒ}t ˆj| ˆj| k¡�s dˆjˆjf }	t|	ƒ‚t ‡ fd	d„ˆjD ƒ¡}
t ˆjˆj|
 f¡‰t ˆjˆj|
 f¡}‡fd
d„ˆjD ƒ}tˆjƒ}tˆjƒ}|| | }tj|ˆjjd�}|d|…  ˆj7  < ||  ˆj7  < n6t ˆjˆjf¡‰t ˆjˆjf¡}t ˆjˆjf¡}t ˆ¡}ˆ| ||dd…f ||   ‰}}dˆjˆjf }ˆj�rXˆjnd}ˆj�rjˆjnd}d||f }t	ˆj
ˆj
ƒ}tˆ||ˆj||dˆj|ƒ	}|S )zAdd Labels.Úotherú¬Label subject parameters must match, got "%s" and "%s". Consider setting the subject parameter on initialization, or setting label.subject manually before combining labels.ú%s + %sÚlhc                    s$   g | ]}t  ˆ j|k¡d  d  ‘qS ©r   ©r9   Úwhererd   ©r5   Údry   r0   r1   Ú
<listcomp>1  s   ÿz!Label.__add__.<locals>.<listcomp>c                    s$   g | ]}t  ˆ j|k¡d  d  ‘qS r   r€   r‚   )r{   r0   r1   r„   3  s   ÿz@Labels %r and %r: vertices overlap but differ in position valuesc                    s   g | ]}|ˆ k‘qS r0   r0   ©r5   r*   )Ú
duplicatesr0   r1   r„   :  s     c                    s"   g | ]}t  ˆ |k¡d  d  ‘qS r   )r9   r�   r…   ©rd   r0   r1   r„   @  s     ©ÚdtypeNru   )r   rO   ÚBiHemiLabelrW   rh   rY   rf   ri   Úcopyr2   r/   r9   Úintersect1drd   r`   rE   rJ   ÚarrayZhstackÚvstackre   ra   r‰   Úargsortrg   )rk   r{   ri   r~   Úrhr/   Zn_dupZself_dupZ	other_dupÚerrZisnewrJ   Ztgt_idxZn_selfZn_otherZnew_lenre   Zindcsrg   Zname0Zname1Úlabelr0   )r†   r{   rk   rd   r1   Ú__add__  sn    
ÿü

ÿ
ÿ
ÿ


$ ÿzLabel.__add__c              
   C   sØ   t |ttfdƒ t|tƒr:| jdkr.| |j S | |j S n | j|jkrZtd| j|jf ƒ‚| j|jkr~t	j
| j|jddd�}nt	 t| jƒ¡}d| jp˜d|jp df }t| j| | j| | j| | j| j|d| j| jƒ	S )	zSubtract Labels.r{   r~   r|   T)Úinvertú%s - %sru   N)r   rO   rŠ   rW   rf   r~   r�   rh   rY   r9   Úin1drd   Úaranger`   ri   rJ   re   rg   r/   )rk   r{   Zkeepri   r0   r0   r1   Ú__sub__[  s.    


ÿü    þzLabel.__sub__c                 C   s   t || ƒ dS )a:  Write to disk as FreeSurfer \*.label file.

        Parameters
        ----------
        filename : str
            Path to label file to produce.

        Notes
        -----
        Note that due to file specification limitations, the Label's subject
        and color attributes are not saved to disk.
        N)Úwrite_label)rk   rj   r0   r0   r1   Úsavev  s    z
Label.savec                 C   s
   t  | ¡S )z‚Copy the label instance.

        Returns
        -------
        label : instance of Label
            The copied label.
        )ÚcpÚdeepcopyry   r0   r0   r1   r‹   …  s    z
Label.copyc              
   C   s  t | jƒdkr|  ¡ S t| |ƒ}t t | j|d ¡¡sDd}t|ƒ‚|d dkr‚tdƒ t	ddƒrhd}ntd	ƒ tj
}t||d
� |d }t || jd¡}t |¡d }t || | jd¡}	| j|	 }
|d | }|dkrà| jn|}t|||
| j| j|d| j| jƒ	}|S )av  Fill the surface between sources for a source space label.

        Parameters
        ----------
        src : SourceSpaces
            Source space in which the label was defined. If a source space is
            provided, the label is expanded to fill in surface vertices that
            lie between the vertices included in the source space. For the
            added vertices, ``pos`` is filled in with positions from the
            source space, and ``values`` is filled in from the closest source
            space vertex.
        name : None | str
            Name for the new Label (default is self.name).

        Returns
        -------
        label : Label
            The label covering the same vertices in source space but also
            including intermediate surface vertices.

        See Also
        --------
        Label.restrict
        Label.smooth
        r   Úvertnoz9Source space does not contain all of the label's verticesÚnearestNz·Source space is being modified in place because patch information is needed. To avoid this in the future, run mne.add_source_space_distances() on the source space and save it to disk.Úscipyú1.3zeSciPy < 1.3 detected, adding source space patch information will be slower. Consider upgrading SciPy.)Ú
dist_limitFTÚrr)r`   rd   r‹   Ú_get_label_srcr9   rE   r–   rY   r   r!   Úinfr   ÚnonzeroZdigitizere   ri   rO   rf   rg   rh   r/   )rk   Úsrcri   Úhemi_srcÚmsgr¡   rž   Úincluderd   Znearest_in_labelre   rJ   r’   r0   r0   r1   Úfill�  s4    


  ÿz
Label.fillc              
   C   sz   t | jƒdkr|  ¡ S t| |ƒ}t | j|d ¡}|dkr@| jn|}t| j| | j| | j	| | j
| j|d| j| jƒ	}|S )a  Restrict a label to a source space.

        Parameters
        ----------
        src : instance of SourceSpaces
            The source spaces to use to restrict the label.
        name : None | str
            Name for the new Label (default is self.name).

        Returns
        -------
        label : instance of Label
            The Label restricted to the set of source space vertices.

        See Also
        --------
        Label.fill

        Notes
        -----
        .. versionadded:: 0.20
        r   r�   N)r`   rd   r‹   r£   r9   r–   ri   rO   rJ   re   rf   rg   rh   r/   )rk   r¦   ri   r§   Úmaskr’   r0   r0   r1   ÚrestrictÏ  s    
    þzLabel.restrictr3   c              	   C   s$   t | j|ƒ}| j|||||||d�S )aE  Smooth the label.

        Useful for filling in labels made in a
        decimated source space for display.

        Parameters
        ----------
        %(subject_label)s
        smooth : int
            Number of iterations for the smoothing of the surface data.
            Cannot be None here since not all vertices are used. For a
            grade of 5 (e.g., fsaverage), a smoothing of 2 will fill a
            label.
        grade : int, list of shape (2,), array, or None
            Resolution of the icosahedral mesh (typically 5). If None, all
            vertices will be used (potentially filling the surface). If a list,
            values will be morphed to the set of vertices specified in grade[0]
            and grade[1], assuming that these are vertices for the left and
            right hemispheres. Note that specifying the vertices (e.g.,
            grade=[np.arange(10242), np.arange(10242)] for fsaverage on a
            standard grade 5 source space) can be substantially faster than
            computing vertex locations. If one array is used, it is assumed
            that all vertices belong to the hemisphere of the label. To create
            a label filling the surface, use None.
        %(subjects_dir)s
        %(n_jobs)s
        %(verbose)s

        Returns
        -------
        label : instance of Label
            The smoothed label.

        Notes
        -----
        This function will set label.pos to be all zeros. If the positions
        on the new surface are required, consider using mne.read_surface
        with ``label.vertices``.
        rQ   )r   rh   Úmorph)rk   rh   ÚsmoothÚgradeÚsubjects_dirÚn_jobsr   r0   r0   r1   r®   ð  s
    * ÿzLabel.smoothé   c              	   C   s–  ddl m}m}	 t| j|ƒ}t|tƒs.tdƒ‚t|tƒs@tdƒ‚t	 
| jdk¡rXtdƒ‚| jdkrfdnd}
t|t	jƒr–t	 g t¡gd }|||
< |}~|	|||d	�}t	 g t¡gd }||
 ||
< t	 g t¡gd }| j||
< | jd
d
…t	jf }t|ƒtdd„ |D ƒƒk�st‚t||dd|d�}|||||||dd� |¡}t	 |j¡d }|j|d
d
…f  ¡ | _t	 t|ƒdf¡| _|j|
 | | _|| _| S )aP  Morph the label.

        Useful for transforming a label from one subject to another.

        Parameters
        ----------
        subject_from : str | None
            The name of the subject of the current label. If None, the
            initial subject will be taken from self.subject.
        subject_to : str
            The name of the subject to morph the label to. This will
            be put in label.subject of the output label file.
        smooth : int
            Number of iterations for the smoothing of the surface data.
            Cannot be None here since not all vertices are used.
        grade : int, list of shape (2,), array, or None
            Resolution of the icosahedral mesh (typically 5). If None, all
            vertices will be used (potentially filling the surface). If a list,
            values will be morphed to the set of vertices specified in grade[0]
            and grade[1], assuming that these are vertices for the left and
            right hemispheres. Note that specifying the vertices (e.g.,
            ``grade=[np.arange(10242), np.arange(10242)]`` for fsaverage on a
            standard grade 5 source space) can be substantially faster than
            computing vertex locations. If one array is used, it is assumed
            that all vertices belong to the hemisphere of the label. To create
            a label filling the surface, use None.
        %(subjects_dir)s
        %(n_jobs)s
        %(verbose)s

        Returns
        -------
        label : instance of Label
            The morphed label.

        See Also
        --------
        mne.morph_labels : Morph a set of labels.

        Notes
        -----
        This function will set label.pos to be all zeros. If the positions
        on the new surface are required, consider using `mne.read_surface`
        with ``label.vertices``.
        r   )Úcompute_source_morphÚgrade_to_verticesz("subject_to" must be entered as a stringzsmooth must be an integerr   z†Morphing label with all zero values will result in the label having no vertices. Consider using something like label.values.fill(1.0).r~   r3   )r°   Nc                 s   s   | ]}t |ƒV  qd S r4   ©r`   r…   r0   r0   r1   r7   d  s     zLabel.morph.<locals>.<genexpr>)ÚtminÚtsteprh   F)Úspacingr®   r°   r   rS   )r­   r³   r´   r   rh   rW   rX   Ú	TypeErrorr\   r9   rE   re   rY   rf   Zndarrayr�   rd   Únewaxisr`   ÚsumÚAssertionErrorr   Úapplyr¥   ÚdataÚravelra   rJ   )rk   Úsubject_fromÚ
subject_tor®   r¯   r°   r±   r   r³   r´   ÚidxZgrade_r¸   rd   r¾   ÚstcZindsr0   r0   r1   r­     sR    0


 
ÿ     þþzLabel.morphFc                 C   sP   t |tƒr|dkrt| ||ƒS t |ttfƒr<t| ||||ƒS tdt|ƒ ƒ‚dS )a;  Split the Label into two or more parts.

        Parameters
        ----------
        parts : int >= 2 | tuple of str | str
            Number of labels to create (default is 2), or tuple of strings
            specifying label names for new labels (from posterior to anterior),
            or 'contiguous' to split the label into connected components.
            If a number or 'contiguous' is specified, names of the new labels
            will be the input label's name with div1, div2 etc. appended.
        %(subject_label)s
        %(subjects_dir)s
        freesurfer : bool
            By default (``False``) ``split_label`` uses an algorithm that is
            slightly optimized for performance and numerical precision. Set
            ``freesurfer`` to ``True`` in order to replicate label splits from
            FreeSurfer's ``mris_divide_parcellation``.

        Returns
        -------
        labels : list of Label, shape (n_parts,)
            The labels, starting from the lowest to the highest end of the
            projection axis.

        Notes
        -----
        If using 'contiguous' split, you must ensure that the label being split
        uses the same triangular resolution as the surface mesh files in
        ``subjects_dir`` Also, some small fringe labels may be returned that
        are close (but not connected) to the large components.

        The spatial split finds the label's principal eigen-axis on the
        spherical surface, projects all label vertex coordinates onto this
        axis, and divides them at regular spatial intervals.
        Ú
contiguouszANeed integer, tuple of strings, or string ('contiguous'). Got %s)N)rW   rX   Ú_split_label_contigr<   r\   Úsplit_labelrY   rZ   )rk   Úpartsrh   r°   Ú
freesurferr0   r0   r1   Úsplitq  s    &ÿzLabel.splitc                 C   s(   |dkrt  d¡}|t  || j¡ }|S )aÅ  Get the source space's vertices inside the label.

        Parameters
        ----------
        vertices : ndarray of int, shape (n_vertices,) | None
            The set of vertices to compare the label to. If None, equals to
            ``np.arange(10242)``. Defaults to None.

        Returns
        -------
        label_verts : ndarray of in, shape (n_label_vertices,)
            The vertices of the label corresponding used by the data.
        Ni(  )r9   r—   r–   rd   )rk   rd   Úlabel_vertsr0   r0   r1   Úget_vertices_usedŸ  s    
zLabel.get_vertices_usedc           	      C   sÌ   |   |¡}tjt ||¡ |j¡dd�}|| }tt |¡ƒt|ƒk rÈt 	d¡ t 
||¡}t|ƒ}|t|ƒtt |¡ƒ ks‚t‚|tjt|ƒdftd�j }tj||jf }tt |¡ƒt|ƒksÈt‚|S )a9  Get the source space's triangles inside the label.

        Parameters
        ----------
        tris : ndarray of int, shape (n_tris, 3)
            The set of triangles corresponding to the vertices in a
            source space.
        vertices : ndarray of int, shape (n_vertices,) | None
            The set of vertices to compare the label to. If None, equals to
            ``np.arange(10242)``. Defaults to None.

        Returns
        -------
        label_tris : ndarray of int, shape (n_tris, 3)
            The subset of tris used by the label.
        r   ©Úaxisz7Surprising label structure. Trying to repair triangles.rS   rˆ   )rË   r9   rE   r–   ÚreshapeÚshaper`   Úuniquer   ÚinfoÚ	setdiff1dr¼   ra   r\   ÚTr8   )	rk   Útrisrd   Ú	vertices_Z	selectionZ
label_trisZdropped_verticesZ	n_droppedZadd_trisr0   r0   r1   Úget_tris³  s     
ÿ
ÿzLabel.get_trisÚspherec                 C   sv   t |tƒstdt|ƒf ƒ‚t| j|ƒ}t | jdk ¡r@t	dƒ‚t 
| jdk¡rXt	dƒ‚t| j| j| j||||ƒ}|S )a€  Compute the center of mass of the label.

        This function computes the spatial center of mass on the surface
        as in :footcite:`LarsonLee2013`.

        Parameters
        ----------
        %(subject_label)s
        restrict_vertices : bool | array of int | instance of SourceSpaces
            If True, returned vertex will be one from the label. Otherwise,
            it could be any vertex from surf. If an array of int, the
            returned vertex will come from that array. If instance of
            SourceSpaces (as of 0.13), the returned vertex will be from
            the given source space. For most accuruate estimates, do not
            restrict vertices.
        %(subjects_dir)s
        surf : str
            The surface to use for Euclidean distance center of mass
            finding. The default here is "sphere", which finds the center
            of mass on the spherical surface to help avoid potential issues
            with cortical folding.

        Returns
        -------
        vertex : int
            Vertex of the spatial center of mass for the inferred hemisphere,
            with each vertex weighted by its label value.

        See Also
        --------
        SourceEstimate.center_of_mass
        vertex_to_mni

        Notes
        -----
        .. versionadded:: 0.13

        References
        ----------
        .. footbibliography::
        zsurf must be a string, got %sr   z'Cannot compute COM with negative valueszqCannot compute COM with all values == 0. For structural labels, consider setting to ones via label.values[:] = 1.)rW   rX   r¹   rZ   r   rh   r9   rD   re   rY   rE   r
   rd   rf   )rk   rh   Úrestrict_verticesr°   ÚsurfZvertexr0   r0   r1   Úcenter_of_massØ  s    ,
  ÿzLabel.center_of_massÚwhitec                C   s    ddl m} tddƒstdƒ‚|  |||¡\}}t||ƒ}t t|ƒ¡}	d|	| j	< t
||	ƒ}
t |
| j	¡}|||ddd�\}}}|| j	 d	 }|| j	 }||fS )
a}  Compute the distance from each vertex to outside the label.

        Parameters
        ----------
        %(subject_label)s
        %(subjects_dir)s
        %(surface)s
        %(verbose)s

        Returns
        -------
        dist : ndarray, shape (n_vertices,)
            The distance from each vertex in ``self.vertices`` to exit the
            label.
        outside_vertices : ndarray, shape (n_vertices,)
            For each vertex in the label, the nearest vertex outside the
            label.

        Notes
        -----
        Distances are computed along the cortical surface.

        .. versionadded:: 0.24
        r   )ÚdijkstrarŸ   r    z;scipy >= 1.3 is required to calculate distances to the edger   T)ÚindicesZmin_onlyZreturn_predecessorsçü©ñÒMbP?)Zscipy.sparse.csgraphrÜ   r!   rF   Ú_load_surfacer   r9   ra   r`   rd   r   rÒ   )rk   rh   r°   Úsurfacer   rÜ   r¢   rÔ   Ú	adjacencyr«   Zborder_vertZoutside_vertÚdistÚ_Zoutsider0   r0   r1   Údistances_to_outside  s(    
ÿ


  þ
zLabel.distances_to_outsidec          	      C   s‚   | j |||dd�\}}}t|dddd� t |d | j¡ |d j¡}t | d¡¡d }t	|ƒdkrnt
dƒ |d	 |  ¡ d
 S )uL  Compute the surface area of a label.

        Parameters
        ----------
        %(subject_label)s
        %(subjects_dir)s
        %(surface)s
        %(verbose)s

        Returns
        -------
        area : float
            The area (in mÂ²) of the label.

        Notes
        -----
        ..versionadded:: 0.24
        T)Zreturn_dictF)Zdo_neighbor_vertZdo_neighbor_trir‹   rÔ   éÿÿÿÿr   z9No complete triangles found, perhaps label is not filled?Ztri_areag�íµ ÷Æ°>)rß   r   r9   r–   rd   rÎ   rÏ   r�   rE   r`   r   r»   )	rk   rh   r°   rà   r   rã   rÙ   Zin_Ztidxr0   r0   r1   Úcompute_area>  s    
ÿ   ÿzLabel.compute_areac                 K   sP   t | j|ƒ}t|dd�}t ||d| j› d|› �¡}t|dddd� t|f|ŽS )NTrU   rÙ   Ú.ÚreadZSurface)Ú	overwriteZ
must_existri   )r   rh   r   rb   Újoinrf   r"   r   )rk   rh   r°   rà   ÚkwargsÚfnamer0   r0   r1   rß   ]  s       ÿzLabel._load_surface)	r0   NNNrP   NNNN)N)N)Nr3   NNNN)NNr²   NNNN)r3   NNF)N)N)NFNr×   )NNrÛ   )NNrÛ   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   rl   ro   rr   rw   rz   r“   r˜   rš   r‹   rª   r¬   r®   r­   r   rÉ   rË   rÖ   rÚ   rä   ræ   rß   r0   r0   r0   r1   rO   Ž   sn   5         þþ*
D

@
!      ÿ-      ÿR  ÿ-

%    ÿ8  ÿÿ,ÿrO   c                 C   sB   t |ƒ}|jdkr"td|jf ƒ‚| jdkr6|d }n|d }|S )Nrà   z@Cannot operate on SourceSpaces that are not surface type, got %sr~   r   r   )r   ÚkindrF   rf   )r’   r¦   r§   r0   r0   r1   r£   f  s    
ÿ

r£   c                   @   s:   e Zd ZdZddd„Zdd„ Zdd„ Zd	d
„ Zdd„ ZdS )rŠ   aÿ  A freesurfer/MNE label with vertices in both hemispheres.

    Parameters
    ----------
    lh : Label
        Label for the left hemisphere.
    rh : Label
        Label for the right hemisphere.
    name : None | str
        Name for the label.
    color : None | color
        Label color and alpha (e.g., ``(1., 0., 0., 1.)`` for red).
        Note that due to file specification limitations, the color isn't saved
        to or loaded from files written to disk.

    Attributes
    ----------
    lh : Label
        Label for the left hemisphere.
    rh : Label
        Label for the right hemisphere.
    name : None | str
        A name for the label. It is OK to change that attribute manually.
    subject : str | None
        The name of the subject.
    Nc                 C   sJ   |j |j kr td|j |j f ƒ‚|| _|| _|| _|j | _ || _d| _d S )Nz.lh.subject (%s) and rh.subject (%s) must agreeÚboth)rh   rY   r~   r�   ri   r/   rf   )rk   r~   r�   ri   r/   r0   r0   r1   rl   Ž  s    
ÿzBiHemiLabel.__init__c                 C   sR   d}| j d krdn| j d }|| jd k	r2t| jƒnd7 }||t| jƒt| jƒf S )Nz7<BiHemiLabel | %s, lh : %i vertices,  rh : %i vertices>rs   rt   ru   )rh   ri   rv   r`   r~   r�   )rk   Útempri   r0   r0   r1   rw   ™  s    zBiHemiLabel.__repr__c                 C   s   t | jƒt | jƒ S rx   )r`   r~   r�   ry   r0   r0   r1   rz   Ÿ  s    zBiHemiLabel.__len__c                 C   s”   t |tƒr8|jdkr&| j| }| j}qh| j}| j| }n0t |tƒr\| j|j }| j|j }ntd| ƒ‚d| j|jf }t| j	|j	ƒ}t||||ƒS )zAdd labels.r~   z#Need: Label or BiHemiLabel. Got: %rr}   )
rW   rO   rf   r~   r�   rŠ   r¹   ri   r2   r/   )rk   r{   r~   r�   ri   r/   r0   r0   r1   r“   ©  s    



zBiHemiLabel.__add__c                 C   s¨   t |ttfdƒ t|tƒrH|jdkr6| j| }| j}q`| j| }| j}n| j|j }| j|j }t|jƒdkrr|S t|jƒdkr„|S d| j	|j	f }t|||| j
ƒS dS )zSubtract labels.r{   r~   r   r•   N)r   rO   rŠ   rW   rf   r~   r�   r`   rd   ri   r/   )rk   r{   r~   r�   ri   r0   r0   r1   r˜   ¼  s    



zBiHemiLabel.__sub__)NN)	rí   rî   rï   rð   rl   rw   rz   r“   r˜   r0   r0   r0   r1   rŠ   r  s   

rŠ   rQ   c                C   sŠ  |dk	rt |tƒstdƒ‚t | ¡}| d¡s8| d¡r>d}n(| d¡sR| d¡rXd}ntd	|f ƒ‚| d
¡r”|dd… }| d¡r |dd… }n|dd… }d||f }t| dƒ�^}| 	¡  
dd¡dd… }	t| 	¡ ƒ}
t d|
f¡}t|ƒD ]\}}| ¡ |dd…|f< qòW 5 Q R X tj|d tjd�}d|dd… j }|d }t |¡}|| }|| }|| }t|||||	|| |||d�
}|S )a_  Read FreeSurfer Label file.

    Parameters
    ----------
    filename : str
        Path to label file.
    %(subject_label)s
        It is good practice to set this attribute to avoid combining
        incompatible labels and SourceEstimates (e.g., ones from other
        subjects). Note that due to file specification limitations, the
        subject name isn't saved to or loaded from files written to disk.
    color : None | matplotlib color
        Default label color and alpha (e.g., ``(1., 0., 0., 1.)`` for red).
        Note that due to file specification limitations, the color isn't saved
        to or loaded from files written to disk.
    %(verbose)s

    Returns
    -------
    label : Label
        Instance of Label object with attributes:

            - ``comment``: comment from the first line of the label file
            - ``vertices``: vertex indices (0 based, column 1)
            - ``pos``: locations in meters (columns 2 - 4 divided by 1000)
            - ``values``: values at the vertices (column 5)

    See Also
    --------
    read_labels_from_annot
    write_labels_to_annot
    Nzsubject must be a stringzlh.labelúlh.r~   zrh.labelúrh.r�   zQCannot find which hemisphere it is. File should end with lh.label or rh.label: %s)rô   rõ   rS   ú.labelrT   i÷ÿÿÿz%s-%sr+   Ú
rP   r   r²   r   rˆ   rÞ   é   rQ   )rW   rX   r¹   rb   rc   ÚendswithÚ
startswithrY   ÚopenÚreadlineÚreplacer\   r9   ÚemptyrC   rÉ   r�   Úint32rÓ   r�   rO   )rj   rh   r/   r   rc   rf   Z	basename_ri   Úfidrg   Únvr¾   ÚiÚlinerd   rJ   re   Úorderr’   r0   r0   r1   Ú
read_labelÓ  sF    "
ÿ

 
  ÿr  c           
   	   C   s  |j }t | ¡\}}| d¡r*|dd… }| |¡sJ| |¡sJ|d| 7 }t ||¡d } t d|  ¡ t| dƒ� }t	|j
ƒ}tj|dftjd�}|j
|dd…d	f< d
|j |dd…dd…f< |j|dd…df< | d|j ¡  ¡ | d| ¡ |D ]}	| dt|	ƒ ¡ qöW 5 Q R X dS )a~  Write a FreeSurfer label.

    Parameters
    ----------
    filename : str
        Path to label file to produce.
    label : Label
        The label object to save.
    %(verbose)s

    See Also
    --------
    write_labels_to_annot

    Notes
    -----
    Note that due to file specification limitations, the Label's subject and
    color attributes are not saved to disk.
    rö   NrT   ú-zSaving label to : %sÚwbr²   rˆ   r   ç     @�@r   rø   s   #%s
s   %d
s   %d %f %f %f %f
)rf   rb   rÉ   rù   rú   rê   r   rÑ   rû   r`   rd   r9   ra   Zfloat64rJ   re   Úwriterg   Úencoder<   )
rj   r’   r   rf   Z	path_headri   r   Ú
n_verticesr¾   rƒ   r0   r0   r1   r™   "  s$    

r™   c                 C   sŽ   t | tƒrtdƒ‚nt | tƒr&t| ƒ} t|dd�}| jdkrN|dkrNtdƒ‚n6|dkr^| j}n&| jdkrjn|| jkr„td| j |ƒ‚| ||fS )z;Get label and subject information prior to label splitting.z3Can only split labels restricted to one hemisphere.TrU   Nz"The subject needs to be specified.zMThe label specifies a different subject (%r) from the subject parameter (%r).)rW   rŠ   r¹   rX   r  r   rh   rY   )r’   rh   r°   r0   r0   r1   Ú_prep_label_splitM  s$    





þþr  c                    s®  t | ||ƒ\} }}d | jdf¡}t ||d|¡}t|ƒ\}}| j}t|ƒ}|| dd…|f  ¡ }	t||	ƒ}
g }|
D ]}| 	|| ¡ qvt
|ƒ}| j d¡r¼| jdd… }| jdd… }n
| j}d}d||f ‰ t‡ fd	d
„td|d ƒD ƒƒ}| jdk�rd| }nt| j|ƒ}|jdd„ dd� g }t|||ƒD ]r\}}}t tt|ƒƒt¡}tj||dd�}| j| }| j| }| j}| j}t||||||d||ƒ	}| 	|¡ �q6|S )al  Split label into contiguous regions (i.e., connected components).

    Parameters
    ----------
    label_to_split : Label | str
        Label which is to be split (Label object or path to a label file).
    %(subject_label)s
    %(subjects_dir)s

    Returns
    -------
    labels : list of Label
        The contiguous labels, in order of descending size.
    rç   r×   rÙ   N©r~   r�   éýÿÿÿrP   ú%s_div%%i%sc                 3   s   | ]}ˆ | V  qd S r4   r0   ©r5   r  ©Zname_patternr0   r1   r7   –  s     z&_split_label_contig.<locals>.<genexpr>r   r4   c                 S   s   t | ƒS r4   rµ   ©Úxr0   r0   r1   Ú<lambda>Ÿ  ó    z%_split_label_contig.<locals>.<lambda>T)ÚkeyÚreverse)Zassume_unique)r  rê   rf   rb   r   rd   r   Útocoor   Úappendr`   ri   rù   r<   Úranger/   r>   ÚsortÚzipr9   r�   ÚsortedÚlistr\   r–   rJ   re   rg   rO   )Zlabel_to_splitrh   r°   Ú
surf_fnameÚ	surf_pathÚsurface_pointsÚsurface_trisZ	verts_arrZ	edges_allZselect_edgesZcomp_labelsZ
label_divsÚcompÚn_partsrc   Úname_extÚnamesrK   ÚlabelsÚdivri   r/   ÚvertsZvert_indicesrJ   re   rf   rg   Úlblr0   r  r1   rÅ   e  sN    þ

 


ÿrÅ   r3   c           1         sL  ddl m} t| ||ƒ\} }}t |¡r’t|ƒ}| j d¡rZ| jdd… }| jdd… }n
| j}d}d||f ‰ t‡ fdd	„t	d
|d
 ƒD ƒƒ}	n|}	t
|	ƒ}|dk r²td| ƒ‚d | jdf¡}
t ||d|
¡}t|ƒ\}}|| j }tj|dd�}|| }|�rÎt tj|d d
d�¡}t |¡}| j| }tj||kd
d�}|| }||dd…df dd…f }||dd…d
f dd…f }||dd…df dd…f }t|| || ƒ}tj|dd�}|| |¡ }n|| |¡ }| |dd…tjf ¡\}}|dd…d
d…f }t ||¡}t |j|¡}| |¡\} }!t | ¡}"|!dd…|"f }#t ||#¡}$|$d
 dk �rp|$d9 }$t ||$¡}%|%|% ¡ 8 }%|%|% ¡ |  }%|%d
 }&|d
 |&|&|k< | j dk�rÆd| }'nt!| j |ƒ}'g }(t"t	|ƒ|	|'ƒD ]`\}"})}*|&|"k}| j| }+| j#| },| j$| }-| j}.| j%}/t&|+|,|-|.|/|)d||*ƒ	}0|( '|0¡ �qæ|(S )a¾  Split a Label into two or more parts.

    Parameters
    ----------
    label : Label | str
        Label which is to be split (Label object or path to a label file).
    parts : int >= 2 | tuple of str
        A sequence of strings specifying label names for the new labels (from
        posterior to anterior), or the number of new labels to create (default
        is 2). If a number is specified, names of the new labels will be the
        input label's name with div1, div2 etc. appended.
    %(subject_label)s
    %(subjects_dir)s
    freesurfer : bool
        By default (``False``) ``split_label`` uses an algorithm that is
        slightly optimized for performance and numerical precision. Set
        ``freesurfer`` to ``True`` in order to replicate label splits from
        FreeSurfer's ``mris_divide_parcellation``.

    Returns
    -------
    labels : list of Label, shape (n_parts,)
        The labels, starting from the lowest to the highest end of the
        projection axis.

    Notes
    -----
    Works by finding the label's principal eigen-axis on the spherical surface,
    projecting all label vertex coordinates onto this axis and dividing them at
    regular spatial intervals.
    r   ©Úlinalgr  Nr  rP   r  c                 3   s   | ]}ˆ | V  qd S r4   r0   r  r  r0   r1   r7   â  s     zsplit_label.<locals>.<genexpr>r   r3   zCan't split label into %i partsrç   r×   rÙ   rÌ   rå   r4   )(rŸ   r,  r  r9   Úisscalarr\   ri   rù   r<   r  r`   rY   rê   rf   rb   r   rd   Úmeanr:   r»   ÚargminrD   r   ZnormZqrrº   ÚdotrÓ   ZeigÚargmaxr&   r'   r/   r>   r  rJ   re   rg   rO   r  )1r’   rÇ   rh   r°   rÈ   r,  r$  rc   r%  r&  r  r   r!  r"  ÚpointsÚcenterZcentered_pointsZdistanceZ	i_closestZclosest_vertexrÂ   Ztris_for_normalÚr1Úr2Zr3Ztri_normalsÚnormalÚqrã   Z	tangent_uZm_obsZm_covÚwZvrr  ZeigendirrÍ   ZprojÚmarkrK   r'  ri   r/   ÚvertrJ   re   rf   rg   r*  r0   r  r1   rÆ   ²  s†    "ÿ

"







ÿrÆ   c                 C   sT  ddl m} t|ƒdkr tdƒ‚|d d }|d d }tƒ }| jdkr‚| jdkrX| jn| jj}t 	||¡}| 
|d d	 | ¡ | jd
krÆ| jdkrœ| jn| jj}t 	||¡}| 
|d d	 | ¡ t|ƒdkrâtd| jf ƒ‚tj|dd�}t|ƒdk�r
t g t¡S |j|dd�\}}}	t ||	d ¡}
t |
¡dk �rF|
d9 }
t |
¡}|S )a  Compute sign for label averaging.

    Parameters
    ----------
    label : Label | BiHemiLabel
        A label.
    src : SourceSpaces
        The source space over which the label is defined.

    Returns
    -------
    flip : array
        Sign flip vector (contains 1 or -1).
    r   r+  r3   z1Only source spaces with 2 hemisphers are acceptedr�   r   )r~   rò   r~   Únn)r�   rò   r�   zUnknown hemisphere type "%s"rÌ   F)Zfull_matricesrå   )rŸ   r,  r`   rY   r  rf   rd   r~   r9   rŒ   r  r�   Ú	ExceptionÚconcatenater�   r\   Zsvdr0  r.  Úsign)r’   r¦   r,  Z	lh_vertnoZ	rh_vertnoZorird   Z
vertno_selrã   ZVhÚdotsÚflipr0   r0   r1   Úlabel_sign_flip4  s2    


rA  Tc           %         sd  t |tƒstd| ƒ‚|dkr$| jn|}|dkr8tdƒ‚t |tƒrH|}n| j}t | tƒs`tdƒ‚t |tƒrÚ|rvtdƒ‚|r†d}t|ƒ‚t|dd�}t ||d	¡}t	t |d
¡ƒ\}	}
t	t |d¡ƒ\}}|	|g}|
|g}nlt |t
ƒsìtdƒ‚t|ƒdk�rtdƒ‚d|d d  d|d d  g}|d d |d d g}t|ƒ ¡ }g }d}d}ttddg| j||ƒƒD �]ò\}\}}}}| j||t|ƒ … }|�r˜t || d ¡d ‰tt |ˆ¡ƒdk�sÌtdƒ‚t tˆƒ|jd f¡}t ˆ|¡}|||< |}|t|ƒ }|||…||…f  ¡ }t |¡jdd�‰tˆd|d�\‰ }|t|ƒ7 }t ‡fdd„ˆ D ƒ¡ddd… }‡ fdd„|D ƒ‰ ‡fdd„ˆ D ƒ‰ n|tj|dd� g‰ |t|ƒ7 }d d„ ˆ D ƒ‰ tˆ ƒdk�ræ|�sàd}ng }nlg }t tˆ ƒƒ} tˆ | ƒD ]B\}!}"|!}#t!|#||# d|d!||"d"�}$|�r6|$ "|¡}$| #|$¡ �q |�sR|d }| #|¡ �qj|S )#a  Compute a label from the non-zero sources in an stc object.

    Parameters
    ----------
    stc : SourceEstimate
        The source estimates.
    src : SourceSpaces | str | None
        The source space over which the source estimates are defined.
        If it's a string it should the subject name (e.g. fsaverage).
        Can be None if stc.subject is not None.
    smooth : bool
        Fill in vertices on the cortical surface that are not in the source
        space based on the closest source space vertex (requires
        src to be a SourceSpace).
    connected : bool
        If True a list of connected labels will be returned in each
        hemisphere. The labels are ordered in decreasing order depending
        of the maximum value in the stc.
    %(subjects_dir)s
    %(verbose)s

    Returns
    -------
    labels : list of Label | list of list of Label
        The generated labels. If connected is False, it returns
        a list of Labels (one per hemisphere). If no Label is available
        in a hemisphere, None is returned. If connected is True,
        it returns for each hemisphere a list of connected labels
        ordered in decreasing order depending of the maximum value in the stc.
        If no Label is available in an hemisphere, an empty list is returned.
    z'smooth should be True or False. Got %s.Nz)src cannot be None if stc.subject is Nonez1SourceEstimate should be surface source estimatesz[The option to return only connected labels is only available if source spaces are provided.zKstc_to_label with smooth=True requires src to be an instance of SourceSpaceTrU   rÙ   zlh.whitezrh.whitez.src must be a string or a set of source spacesr3   z-source space should contain the 2 hemispheresr  r   r¢   r   rÔ   r~   r�   ZinusezAstc contains vertices not present in source space, did you morph?rÌ   ç        )rá   c                    s   g | ]}t  ˆ | ¡‘qS r0   )r9   r'   ©r5   rM   )Úthis_data_abs_maxr0   r1   r„   Å  s   ÿz stc_to_label.<locals>.<listcomp>rå   c                    s   g | ]}ˆ | ‘qS r0   r0   )r5   Úk)Úclustersr0   r1   r„   Ç  s     c                    s   g | ]}ˆ | ‘qS r0   r0   rC  ©r�   r0   r1   r„   È  s     c                 S   s   g | ]}t |ƒd kr|‘qS r   rµ   rC  r0   r0   r1   r„   Î  s      zLabel from stc)rh   r/   )$rW   ÚboolrY   rh   rX   r   r   rb   rê   r   r   r¹   r`   r   ÚtocsrrC   r  rd   r¾   r9   r�   rÒ   rF   ra   rÏ   Zsearchsortedr  r%   r'   r   r�   rD   rN   rO   rª   r  )%rÃ   r¦   r®   Ú	connectedr°   r   rh   r¨   Zsurf_path_fromZrr_lhZtris_lhZrr_rhZtris_rhr¢   rÔ   Zsrc_connr'  ZcntZcnt_fullZhemi_idxrf   Zthis_vertnoZ	this_trisZthis_rrZ	this_dataÚtmpZthis_vertno_idxÚoffsetZthis_src_adjrã   Zclusters_maxZthis_labelsrK   rM   r/   Zidx_user’   r0   )rF  rD  r�   r1   Ústc_to_labelg  s¢    "





 ÿÿ
ÿ
ÿ þ
rM  c                    sø   i ‰ g }|D ]}dˆ |< |  |¡ qt|ƒdkr¼g }|D ]|}ˆ | }| |dd…f }|j}	|j}
t|	|
ƒD ]H\}}|| }|ˆ kr˜|ˆ | k r²|ˆ |< qj||krj|ˆ |< |  |¡ qjq8|}q$t t tˆ  	¡ ƒt
¡¡}t ‡ fdd„|D ƒt
¡}||fS )a·  Find all vertices wihin a maximum geodesic distance from source.

    Parameters
    ----------
    graph : scipy.sparse.csr_matrix
        Sparse matrix with distances between adjacent vertices.
    sources : list of int
        Source vertices.
    max_dist : float
        Maximum geodesic distance.

    Returns
    -------
    verts : array
        Vertices within max_dist.
    dist : array
        Distances from source vertex.
    r   Nc                    s   g | ]}ˆ | ‘qS r0   r0   r…   ©Zdist_mapr0   r1   r„     s     z&_verts_within_dist.<locals>.<listcomp>)r  r`   rÝ   r¾   r  r9   r  r�   r  Úkeysr\   )ÚgraphÚsourcesZmax_distZverts_added_lastÚsourceZverts_addedr  Zv_distÚrowZneighbor_vertZneighbor_distÚjrƒ   Zn_distr)  râ   r0   rN  r1   Ú_verts_within_distê  s0    
rU  c              
   C   s–   g }t | |||ƒD ]~\}}	}
}t||
 ||	ƒ\}}t|ƒdkrHt|ƒ}nd tt|ƒ¡}d||	f }t|||
 | ||
|t|ƒ|d�}| |¡ q|S )zParallelize grow_labels.r   ú,z'Circular label: seed=%s, extent=%0.1fmm)rd   rJ   re   rf   rg   ri   rh   )r  rU  r`   rX   rê   ÚmaprO   r  )ÚseedsÚextentsÚhemisr&  râ   r:  rh   r'  ÚseedÚextentrf   ri   rÊ   Z
label_distZ	seed_reprrg   r’   r0   r0   r1   Ú_grow_labels  s&    
ÿ
úr]  rÛ   c
                    s  t |dd�}t |¡r|g}dd„ |D ƒ}t |¡}t |¡}t|ƒ}
t|ƒdkrft|ƒ|
krftdƒ‚t|ƒdkr†t|ƒ|
kr†tdƒ‚|	dk	ròt|	jƒdkr¬d}|	jd	 }n
|	j\}}||
krÚ|dkrÚd
||
f }t|ƒ‚|dkròd| }t|ƒ‚t|ƒdk�rt ||
¡}t|ƒdk�r&t ||
¡}t dd„ |D ƒ¡}|dk�rXdd„ t	|ƒD ƒ}nbt |¡�rj|g}t|ƒ|
k�r€tdƒ‚t	|ƒD ]0\}}||  
|¡�sˆd || |f¡||< �qˆt |¡}i i i   }‰‰ t|ƒD ]H}t |ˆd|d | ¡}t|ƒ\ˆ|< ||< t|| ˆ| ƒˆ |< �qÜ|�r¤tt|ƒ\}‰}t tj|dd�|¡}t ||¡}t ||¡}t ||¡}t|‡ ‡‡‡fdd„t||||ƒD ƒƒg ƒ}ntˆ|||ˆˆ |ƒ}|	dk�rÐtt|ƒƒ}nt t|ƒdf¡}|	|dd…< t||ƒD ]\}}||_�qø|S )a  Generate circular labels in source space with region growing.

    This function generates a number of labels in source space by growing
    regions starting from the vertices defined in "seeds". For each seed, a
    label is generated containing all vertices within a maximum geodesic
    distance on the white matter surface from the seed.

    Parameters
    ----------
    %(subject)s
    seeds : int | list
        Seed, or list of seeds. Each seed can be either a vertex number or
        a list of vertex numbers.
    extents : array | float
        Extents (radius in mm) of the labels.
    hemis : array | int
        Hemispheres to use for the labels (0: left, 1: right).
    %(subjects_dir)s
    %(n_jobs)s
        Likely only useful if tens or hundreds of labels are being expanded
        simultaneously. Does not apply with ``overlap=False``.
    overlap : bool
        Produce overlapping labels. If True (default), the resulting labels
        can be overlapping. If False, each label will be grown one step at a
        time, and occupied territory will not be invaded.
    names : None | list of str
        Assign names to the new labels (list needs to have the same length as
        seeds).
    %(surface)s
    colors : array, shape (n, 4) or (, 4) | None
        How to assign colors to each label. If None then unique colors will be
        chosen automatically (default), otherwise colors will be broadcast
        from the array. The first three values will be interpreted as RGB
        colors and the fourth column as the alpha value (commonly 1).

    Returns
    -------
    labels : list of Label
        The labels' ``comment`` attribute contains information on the seed
        vertex and extent; the ``values``  attribute contains distance from the
        seed in millimeters.

    Notes
    -----
    "extents" and "hemis" can either be arrays with the same length as
    seeds, which allows using a different extent and hemisphere for
    label, or integers, in which case the same extent and hemisphere is
    used for each label.
    TrU   c                 S   s   g | ]}t  |¡‘qS r0   )r9   Ú
atleast_1d)r5   r[  r0   r0   r1   r„   n  s     zgrow_labels.<locals>.<listcomp>r   z9The extents parameter has to be of length 1 or len(seeds)z7The hemis parameter has to be of length 1 or len(seeds)Nr   z8Number of colors (%d) and seeds (%d) are not compatible.rø   z2Colors must have 4 values (RGB and alpha), not %d.c                 S   s   g | ]}|d krdnd‘qS )r   r~   r�   r0   )r5   r(   r0   r0   r1   r„   ‘  s     c                 S   s   g | ]}d | ‘qS )zLabel_%i-%sr0   )r5   Úitemsr0   r0   r1   r„   •  s     z<The names parameter has to be None or have length len(seeds)r  rÙ   rç   ÚOrˆ   c              	   3   s*   | ]"\}}}}ˆ||||ˆ ˆˆƒV  qd S r4   r0   )r5   r)   Úer(   r=   ©râ   Zmy_grow_labelsrh   r:  r0   r1   r7   °  s   
ÿzgrow_labels.<locals>.<genexpr>)r   r9   r-  r^  r`   rY   rÏ   Ztiler�   rC   rù   rê   Úsetrb   r   r   r   r]  Zarray_splitr»   r  Ú_grow_nonoverlapping_labelsrN   rþ   r/   )rh   rX  rY  rZ  r°   r±   Úoverlapr&  rà   rK   Zn_seedsZn_colorsr=   r¨   r  rf   rÔ   r  Úparallelr'  Zlabel_colorsr’   r/   r0   rb  r1   Úgrow_labels5  sŠ    4



ÿ

ÿþþ
  ÿ

rg  c           "         s   g }t |ƒD �]ì‰ |ˆ k}‡ fdd„t||ƒD ƒ}	|| }
|| }|ˆ  }t|ˆ  ƒ}t|	ƒ}tj|dd�}d|dd…< i }g }t|	ƒD ]P\}}t || dk¡rªtdƒ‚|||< t |¡D ]}|d	f||< | 	|¡ q¼qˆ|�r²| 
d¡}|| \}}||dd…f }t|j|jƒD ]š\}}||	| k ¡ �r2�q|| }||
| k�rL�q|| }|dk�rŽ|| \}}||k�rz�qn||k�rŽ| |¡ |||< ||f||< | 	|¡ �qqÚt|ƒD ]>}t ||k¡d }t|| ƒ} t|ˆ | | d
�}!| 	|!¡ �qºq|S )z3Grow labels while ensuring that they don't overlap.c                    s   g | ]\}}|ˆ kr|‘qS r0   r0   )r5   r[  r(   ©rf   r0   r1   r„   Ì  s      z/_grow_nonoverlapping_labels.<locals>.<listcomp>rÿ   rˆ   rå   Nr   zOverlapping seedsrB  ©rf   ri   rh   )rc  r  r`   r9   rþ   rC   rD   rY   r^  r  ÚpoprÝ   r¾   Úremover  r¥   rX   rO   )"rh   Zseeds_Zextents_rZ  rÕ   ÚgraphsZnames_r'  Z
hemi_indexrX  rY  r&  rP  r  Ún_labelsÚparcrQ  Úedger’   r[  r)   Ú	vert_fromZold_distrS  Úvert_torâ   Znew_distÚvert_to_labelrã   Zvert_to_distr  rd   ri   Úlabel_r0   rh  r1   rd  Æ  s\    




rd  c                 C   sÂ   t |dd�}|dkrddg}t |¡}i i i   }}}	t|ƒD ]F}t || d|d | ¡}
t|
ƒ\||< ||< t|| || ƒ|	|< q>t| ||||	|ƒ}t	t
|ƒƒ}t||ƒD ]\}}||_q®|S )a‡  Generate random cortex parcellation by growing labels.

    This function generates a number of labels which don't intersect and
    cover the whole surface. Regions are growing around randomly chosen
    seeds.

    Parameters
    ----------
    %(subject)s
    n_parcel : int
        Total number of cortical parcels.
    hemi : str
        Hemisphere id (ie 'lh', 'rh', 'both'). In the case
        of 'both', both hemispheres are processed with (n_parcel // 2)
        parcels per hemisphere.
    %(subjects_dir)s
    %(surface)s
    %(random_state)s

    Returns
    -------
    labels : list of Label
        Random cortex parcellation.
    TrU   rò   r~   r�   rÙ   rç   )r   r9   r^  rc  rb   rê   r   r   Ú_cortex_parcellationrN   r`   r  r/   )rh   Ún_parcelrf   r°   rà   Úrandom_staterZ  rÔ   r:  râ   r  r'  rK   r’   r/   r0   r0   r1   Úrandom_parcellation  s$    
ÿÿrw  c           &      C   sŒ  g }t |ƒ}t|ƒD �]p}t|ƒt|| ƒ | }	|| }
t|| ƒ}tj|ddd�}| t|ƒ¡}d}|g}|||< d}t|ƒd }|�rˆ|sÎt |dk ¡d }| |¡}|g}|d7 }d}|||< |d8 }| d¡}t	|
j
| |
j
|d  ƒ}|
j| |
j|  }}t||ƒD ]r\}}|| }|dk�r0�q||	k�r`|d7 }d}|g}|||< |d8 } q†|||< |d7 }| |¡ |d8 }�qq†|d }tj|td�}tj||gdd�}t|ƒD ]V}t ||k¡d }t|ƒ||< |
|dd…f j}t t || ¡¡} d||| f< �q¸t |d¡ t|ƒ}!||t|ƒ k�r:t |¡}t ||dd…f ¡d }"|"t ||" ¡ }#||#dd…f  ||dd…f 7  < |dd…|#f  |dd…|f 7  < t ||d¡}t ||d¡}d||#|#f< ||#  || 7  < t ||d¡}|d8 }t ||!| k¡d }|!|# ||< t |!|d¡}!�q$t|ƒD ]B}t ||!| k¡d }dt|ƒ }$t|||$| d	�}%| |%¡ �qBq|S )
zRandom cortex parcellation.rå   rÿ   rˆ   r   r   rH  Nrs  ri  )r   rc  r`   r9   ÚfullÚchoicer  r�   rj  ÚsliceZindptrrÝ   r¾   r  r  rþ   r\   ra   r¥   rÐ   r�   Zfill_diagonalr/  ÚdeleterX   rO   )&rh   ru  rZ  rÕ   rl  rv  r'  Úrngrf   Zparcel_sizerP  r  rn  r)   Z	label_idxro  Z
label_sizeÚrestZrest_idxrp  ÚslZrow_indicesZrow_datarq  râ   rr  rm  Zlabel_sizesZ
label_connr  rd   Zneighbor_verticesZneighbor_labelsÚlabel_idZ	neighborsrT  ri   rs  r0   r0   r1   rt  @  s�    





$$rt  c                 C   sX   t  | ¡s|stƒ S td| ƒ‚t | ¡}ttdd„ |D ƒƒdd„ d�}dd„ |D ƒ}|S )	z!List the candidate parcellations.z+Directory for annotation does not exist: %sc                 s   s2   | ]*}d |kr|  dd¡  dd¡  d d¡V  qdS )z.annotrô   rP   rõ   N)rý   rC  r0   r0   r1   r7   ±  s    þ ÿz$_read_annot_cands.<locals>.<genexpr>c                 S   s   |   ¡ S r4   )Úlowerr  r0   r0   r1   r  ´  r  z#_read_annot_cands.<locals>.<lambda>©r  c                 S   s   g | ]}d |kr|‘qS )z.ctabr0   rC  r0   r0   r1   r„   ¶  s      z%_read_annot_cands.<locals>.<listcomp>)rb   Úisdirr  ÚIOErrorÚosÚlistdirr  rc  )Údir_namerV   Úcandsr0   r0   r1   Ú_read_annot_cands©  s    
ÿ

þýrˆ  c              	   C   s  t  | ¡sPt  | ¡d }t|ƒ}t|ƒdkr:td|  ƒ‚ntd| d |¡f ƒ‚t| dƒ��–}t 	|dd¡d }t 	|d|d ¡ 
|d¡}||d	d	…df df }t 	|dd¡d }|sÀtd
ƒ‚t 	|dd¡d }|dk�r¸t 	|dd¡d }	t 	|d|	¡ tƒ }
t |dftj¡}t|ƒD ]–}t 	|dd¡d }t 	|d| d¡d }|
 |¡ t 	|dd¡||d	d…f< ||df ||df d  ||df d  ||df d  ||df< �q�n| }|dk�rÐtdƒ‚t 	|dd¡d }t |dftj¡}t 	|dd¡d }	t 	|d|	 d¡ t 	|dd¡d }tƒ }
t|ƒD ]”}t 	|dd¡ t 	|dd¡d }t 	|d| d¡d }|
 |¡ t 	|dd¡||d	d…f< ||df ||df d  ||df d  ||df< �q8d|d	d	…df  |d	d	…df< W 5 Q R X |||
fS )a´  Read a Freesurfer annotation from a .annot file.

    Note : Copied from PySurfer

    Parameters
    ----------
    fname : str
        Path to annotation file

    Returns
    -------
    annot : numpy array, shape=(n_verts)
        Annotation id at each vertex
    ctab : numpy array, shape=(n_entries, 5)
        RGBA + label id colortable array
    names : list of str
        List of region names as stored in the annot file

    r   z>No such file %s, no candidate parcellations found in directoryz>No such file %s, candidate parcellations in that directory:
%sr÷   Úrbú>i4r   r3   Nz(Color table not found in annotation filez>cr²   z|S%drø   é   é   rS   i   z!Color table version not supportedéÿ   )rb   ÚisfilerÉ   rˆ  r`   rƒ  rê   rû   r9   ÚfromfilerÎ   r<  r  ra   Úint64r  r  )rì   r†  r‡  r   Ún_vertsr¾   ÚannotZctab_existsÚ	n_entriesÚlengthr&  Úctabr  Zname_lengthri   Zctab_versionZentries_to_readr0   r0   r1   Ú_read_annotº  sj    
ÿÿ

ÿþ

ÿ*r–  c                    sœ   | dk	r8t  | ¡dd… g}|d dkr0tdƒ‚| g} n\td|ddd	gƒ |d	kr\ddg}n|g}t|d
d�}t  ||dd| ¡‰ ‡ fdd„|D ƒ} | |fS )z)Get the .annot filenames and hemispheres.Nr3   r   r  zVCould not determine hemisphere from filename, filename has to start with "lh" or "rh".rf   r~   r�   rò   TrU   r’   z%%s.%s.annotc                    s   g | ]}ˆ | ‘qS r0   r0   )r5   Zhemi_©Údstr0   r1   r„     s     z$_get_annot_fname.<locals>.<listcomp>)rb   rc   rY   r    r   rê   )Úannot_fnamerh   rf   rn  r°   rZ  r0   r—  r1   Ú_get_annot_fname  s    
rš  rP   c           	      C   sT   t  || dd||f ¡}t|ƒ\}}|d }t|ƒ|krPtdt|ƒ| ||f ƒ‚|S )NrÙ   z%s.%sr  zcNumber of surface vertices (%s) for subject %s does not match the expected number of vertices(%s)%s)rb   rê   r   r`   rF   )	rh   r°   Ú	surf_namerf   Z
n_expectedÚextraZ
fname_surfÚvert_posrã   r0   r0   r1   Ú_load_vert_pos  s    

ÿýrž  Úaparcrò   c	              
   C   sì  t  d¡ t|ƒ}t|| |||ƒ\}}	|dk	rPt | dd¡ ¡ rJd| n|¡}
d}tƒ }t	ƒ }t
||	ƒD �]\}}t|ƒ\}}}|dd…dd…f d }|dd…d	f }t| |||t|ƒd
| d�}t
|||ƒD ]”\}}}t ||k¡d }t|ƒdkrüqÒ| ¡ }| |¡ |› d|› �}|dk	�r4|
 |¡�s4qÒ||dd…f }t||||| t|ƒd�}| |¡ qÒt|ƒ| }t  d||f ¡ qj|�ržt|dd„ d�}t|ƒdk�rèd}|dk	�ràd t|ƒ¡}|dt|ƒ› d|› �7 }t|ƒ‚|S )aZ  Read labels from a FreeSurfer annotation file.

    Note: Only cortical labels will be returned.

    Parameters
    ----------
    %(subject)s
    parc : str
        The parcellation to use, e.g., 'aparc' or 'aparc.a2009s'.
    hemi : str
        The hemisphere from which to read the parcellation, can be 'lh', 'rh',
        or 'both'.
    surf_name : str
        Surface used to obtain vertex locations, e.g., 'white', 'pial'.
    annot_fname : str or None
        Filename of the .annot file. If not None, only this file is read
        and 'parc' and 'hemi' are ignored.
    regexp : str
        Regular expression or substring to select particular labels from the
        parcellation. E.g. 'superior' will return all labels in which this
        substring is contained.
    %(subjects_dir)s
    sort : bool
        If true, labels will be sorted by name before being returned.

        .. versionadded:: 0.21.0
    %(verbose)s

    Returns
    -------
    labels : list of Label
        The labels, sorted by label name (ascending).

    See Also
    --------
    write_labels_to_annot
    morph_labels
    z#Reading labels from parcellation...Nrã   rP   z.*%s.*r   rø   g     ào@rå   zfor annotation file %s)rœ  r  )rf   ri   rh   r/   z   read %d labels from %sc                 S   s   | j S r4   ©ri   )Úlr0   r0   r1   r  †  r  z(read_labels_from_annot.<locals>.<lambda>r�  zNo labels found.r÷   z Maybe the regular expression z did not match any of:
)r   rÑ   r   rš  ÚreÚcompilerý   Úisalnumr  rc  r  r–  rž  r`   r9   r�   ÚdecodeÚaddÚmatchrO   r<   r  r  rê   rv   rF   )rh   rn  rf   r›  r™  Úregexpr°   r  r   rZ  r8   Zn_readr'  Z
orig_namesrì   r’  r•  Zlabel_namesZlabel_rgbasZ	label_idsr�  r  Z
label_nameZ
label_rgbard   ri   rJ   r’   r¨   r0   r0   r1   Úread_labels_from_annot,  sf    *

ÿÿ    þ
ÿ

 ÿ
r©  c                 C   sr   t | ttfdƒ | D ]D}t |tdƒ |d kr2|j}|d k	r||jkrtd|||jf ƒ‚q|d krntd| ƒ‚|S )Nr'  zeach entry in labelsz$Got multiple values of %s: %s and %sz<if label.subject is None for all labels, %s must be provided)r   r  r<   rO   rh   rY   )r'  rh   ri   r’   r0   r0   r1   Ú_check_labels_subject“  s    

ÿÿrª  c                    sÊ   t ˆdd�‰t| |dƒ}t|ˆ ˆƒ}‡ ‡‡fdd„td|ƒD ƒ}dd„ |D ƒ}tƒ }	d }
}| D ]d}td	d
d�|j }t t 	|| |j
¡¡d	 }|| | }|	 t|||
|j|j|j|ˆ |jƒ	¡ q`|	S )aã  Morph a set of labels.

    This is useful when morphing a set of non-overlapping labels (such as those
    obtained with :func:`read_labels_from_annot`) from one subject to
    another.

    Parameters
    ----------
    labels : list
        The labels to morph.
    subject_to : str
        The subject to morph labels to.
    subject_from : str | None
        The subject to morph labels from. Can be None if the labels
        have the ``.subject`` property defined.
    %(subjects_dir)s
    surf_name : str
        Surface used to obtain vertex locations, e.g., 'white', 'pial'.
    %(verbose)s

    Returns
    -------
    labels : list
        The morphed labels.

    See Also
    --------
    read_labels_from_annot
    mne.Label.morph

    Notes
    -----
    This does not use the same algorithm as Freesurfer, so the results
    morphing (e.g., from ``'fsaverage'`` to your subject) might not match
    what Freesurfer produces during ``recon-all``.

    .. versionadded:: 0.18
    TrU   rÀ   c              	      s&   g | ]\}}t ˆ ˆˆ||jd  ƒ‘qS r   )rž  rÏ   )r5   rf   Úmmap©rÁ   r°   r›  r0   r1   r„   Ï  s   þ
ÿz morph_labels.<locals>.<listcomp>r  c                 S   s   g | ]}|j d d�‘qS )r   rÌ   )r1  )r5   r«  r0   r0   r1   r„   Ò  s     Nr   r   )r   rª  r   r  r  rp   rf   r9   r�   r–   rd   r  rO   rg   ri   r/   )r'  rÁ   rÀ   r°   r›  r   ZmmapsZ	vert_possZidxsZ
out_labelsre   rj   r’   Úlird   rJ   r0   r¬  r1   Úmorph_labels£  s*    )þ  ÿÿr®  c                 C   sR  t  |t¡}|jdkr(|dd…t jf }|jdkrBtd|jf ƒ‚t|tdfƒ |dkrtt| ||||ƒ\}}}t	}	nÊ|j
}
t|j|ddd�}td|
d	ƒ |
d
kr¦t}	nt	}	dd„ |D ƒ}|	t  tdd„ |D ƒƒ¡|dd|ƒ}t|| |ddd�}t||jd ƒ t  |jddd… ¡}d|t  |jd ¡t j|dd�f< || }|	||||||d�S )aÕ  Convert a set of labels and values to a STC.

    This function is meant to work like the opposite of
    `extract_label_time_course`.

    Parameters
    ----------
    %(labels_eltc)s
    values : ndarray, shape (n_labels, ...)
        The values in each label. Can be 1D or 2D.
    tmin : float
        The tmin to use for the STC.
    tstep : float
        The tstep to use for the STC.
    %(subject)s
    %(src_eltc)s
        Can be omitted if using a surface source space, in which case
        the label vertices will determine the output STC vertices.
        Required if using a volumetric source space.

        .. versionadded:: 0.22
    %(verbose)s

    Returns
    -------
    stc : instance of SourceEstimate | instance of VolSourceEstimate
        The values-in-labels converted to a STC.

    See Also
    --------
    extract_label_time_course

    Notes
    -----
    Vertices that appear in more than one label will be averaged.

    .. versionadded:: 0.18
    r   Nr3   z*values must have 1 or 2 dimensions, got %szsource space subjectF)Z
first_kindrV   zsource space kind)rà   Úvolumer¯  c                 S   s   g | ]}|d    ¡ ‘qS rG  )r‹   )r5   r)   r0   r0   r1   r„   	  s     z!labels_to_stc.<locals>.<listcomp>c                 s   s   | ]}t |ƒV  qd S r4   rµ   r…   r0   r0   r1   r7    	  s     z labels_to_stc.<locals>.<genexpr>r   r.  T)r¦   ÚmodeZallow_emptyrå   r$   rÌ   rQ   )r9   r�   ÚfloatÚndimrº   rY   r   r   Ú_labels_to_stc_surfr   rñ   r   Z_subjectr    r	   Úeyer»   r   Ú_check_values_labelsrÏ   ra   r—   r1  )r'  re   r¶   r·   rh   r¦   r   r¾   rd   Úklassrñ   rÃ   Zlabel_opZrev_opr0   r0   r1   Úlabels_to_stcß  s`    )

ÿ    ÿ
  þ    ÿ    ÿ"r·  c                 C   s,   |t | ƒkr(td| jd › d|› d�ƒ‚d S )Nzvalues.shape[0] (r   z#) must match the number of labels (ú))r`   rY   rÏ   )re   rm  r0   r0   r1   rµ  *	  s    ÿrµ  c              
      s�  ddl m} t| |dƒ}t|t| ƒƒ tg g d�‰tg g d�‰ t| ƒD ]F\}}ˆ |j  t	j
|| t	j t|jƒdd�¡ ˆ|j  |j¡ qFd}|D ]À}	t	jˆ|	 dd�ˆ|	< t	jˆ |	 dd� t¡ˆ |	< t	 tˆ|	 ƒ¡}
t	jˆ|	 dd�\ˆ|	< }| t	 t|ƒ¡||
ff¡ ¡ }|| dt	 |jd	d�¡d d …df  ¡ }| ˆ |	 ¡ˆ |	< q–‡fd
d„|D ƒ‰t	j‡ fdd„|D ƒdd�‰ ˆ ˆ|fS )Nr   )Úsparserh   r  rÌ   T)Zreturn_inverser$   rå   c                    s   g | ]}ˆ | ‘qS r0   r0   ©r5   rf   r‡   r0   r1   r„   D	  s     z'_labels_to_stc_surf.<locals>.<listcomp>c                    s   g | ]}ˆ | ‘qS r0   r0   rº  )r¾   r0   r1   r„   E	  s     )rŸ   r¹  rª  rµ  r`   rp   rC   rf   r  r9   Úrepeatrº   rd   r=  r^   r±  r—   rÐ   Z
coo_matrixr_   rI  Zdiagsr[   r»   r0  )r'  re   r¶   r·   rh   r¹  r­  r’   rZ  rf   ÚcolsÚrowsZmatr0   )r¾   rd   r1   r³  1	  s,    
ÿ ,r³  zMNE-Python Colortablec              	   C   sJ  t |ƒt |ƒkst‚t| dƒ�� }t |ƒ}tj|dd� |¡ tj|dfdd�}t |¡|dd…df< ||dd…df< | ¡  |¡ tjddd� |¡ tjddd� |¡ t |ƒ}tj|dd� |¡ t	||ƒ tj|dd� |¡ t
t||ƒƒD ]F\}	\}
}tj|	dd� |¡ t	||
ƒ tj|dd	… dd� |¡ qôW 5 Q R X dS )
z/Write a Freesurfer annotation to a .annot file.r  rŠ  rˆ   r3   Nr   r   éþÿÿÿrø   )r`   r¼   rû   r9   r�   Útofilera   r—   r¿   Ú_write_annot_strrC   r  )rì   r’  r•  r&  Ú
table_namer   r‘  r¾   r“  rL   ri   r/   r0   r0   r1   Ú_write_annotL	  s$    

rÂ  c                 C   s2   |  d¡d }t t|ƒd¡ | ¡ |  |¡ d S )NÚasciió    rŠ  )r
  r9   r�   r`   r¿  r	  )r   r)   r0   r0   r1   rÀ  o	  s    rÀ  c           .   	      s�  t  d¡ t|ƒ}t||ˆ||ƒ\}}|sJ|D ]}t |¡r.td| ƒ‚q.g }g }g }g }d‰d}t||ƒD �]X\‰}‡fdd„| D ƒ‰tˆƒ}|dkrÀt	j
dt	jd	�}|d
d
…d
d…f }�n�|rÔˆjdd„ d� ‡fdd„ˆD ƒ}t	j|t	jd	�}|d
d
…d
d…f }ttƒ}tˆ|ƒD ]\}}|t|ƒ  |j¡ �q| ¡ D ]ˆ\}}||k�rZ�qD|dk�rltdƒ tdd„ |D ƒƒ�ržd|d |¡ˆf }| |¡ t|ƒdk�rDd|d |¡ˆf }| |¡ �qD|| �rPt|d|d�}d}t|ƒD ]\}||df dk�rò|| }t	 t	 |d
d… |kd¡¡�rD|| }|d7 }�q|||< �qò|d
k	�rŽ|d
k	�rŽt ||ddˆ ¡}t|ƒ\}} t|ƒ}!n6tˆƒdk�r¸tdd„ ˆD ƒƒ}"|"d }!nd}!tdƒ t	j
|!t	jd	�}#d|#d
d
…< t	 d¡}$tt	j||$ dd�ƒ‰ tˆˆ ƒD ]Š\}}%t	 |#|j dk¡�rˆt|#|j ƒ}&|&  d¡ ‡ fd d„|&D ƒ}'‡fd!d„|'D ƒ}(d |(¡})d"ˆ|j|)f }| |¡ |%|#|j< �q
d#d„ ˆD ƒ}*d
|*k�rÄd$|* !d
¡ }t|ƒ‚|#dk}+t	 |+¡�r‚d%|+ ¡ ˆf }t  |¡ tdd&ƒD ]*}t	 t	 |||f|kd¡¡�sü �q(�qü|d'k �r@|||df}nd(},t|,ƒ‚t	 |$|d
d…  ¡}%|%|#|+< t	 "||f¡}|* d)¡ d*|d
d
…df  |d
d
…df< ‡fd+d„|*D ƒ}*| ||#||*f¡ qlg }-|�ròd,}| #d|¡ |- d- |¡¡ |�rd.}| #d|¡ |- d- |¡¡ |�r>d/}| #d|¡ |- d- |¡¡ |-�rRtd0 |-¡ƒ‚|D ]4\}}#}}*t  d1t|*ƒ|f ¡ t$||#||*|	ƒ �qVd
S )2aº  Create a FreeSurfer annotation from a list of labels.

    Parameters
    ----------
    labels : list with instances of mne.Label
        The labels to create a parcellation from.
    %(subject)s
    parc : str | None
        The parcellation name to use.
    overwrite : bool
        Overwrite files if they already exist.
    %(subjects_dir)s
    annot_fname : str | None
        Filename of the .annot file. If not None, only this file is written
        and 'parc' and 'subject' are ignored.
    colormap : str
        Colormap to use to generate label colors for labels that do not
        have a color specified.
    hemi : 'both' | 'lh' | 'rh'
        The hemisphere(s) for which to write \*.annot files (only applies if
        annot_fname is not specified; default is 'both').
    sort : bool
        If True (default), labels will be sorted by name before writing.

        .. versionadded:: 0.21.0
    table_name : str
        The table name to use for the colortable.

        .. versionadded:: 0.21.0
    %(verbose)s

    See Also
    --------
    read_labels_from_annot

    Notes
    -----
    Vertices that are not covered by any of the labels are assigned to a label
    named "unknown".
    z!Writing labels to parcellation...z4File %s exists. Use "overwrite=True" to overwrite it)rå   rå   rå   rå   )rå   rå   rå   c                    s   g | ]}|j ˆ kr|‘qS r0   rh  ©r5   r’   rh  r0   r1   r„   ¹	  s     
 z)write_labels_to_annot.<locals>.<listcomp>r   )r   rø   rˆ   NrS   c                 S   s   | j S r4   r   ©r’   r0   r0   r1   r  Á	  r  z'write_labels_to_annot.<locals>.<lambda>r�  c                    s.   g | ]&}|j d krˆ ntdd„ |j D ƒƒ‘qS )Nc                 s   s   | ]}t td | ƒƒV  qdS ©r�  N)r\   Úroundr  r0   r0   r1   r7   Å	  s     z3write_labels_to_annot.<locals>.<listcomp>.<genexpr>)r/   r<   rÅ  )Úno_colorr0   r1   r„   Ä	  s   þ)r   r   r   zxAt least one label contains a color with, "r=0, g=0, b=0" value. Some FreeSurfer tools may fail to read the parcellationc                 s   s   | ]}|d kV  qdS rÇ  r0   r  r0   r0   r1   r7   Û	  s     z(write_labels_to_annot.<locals>.<genexpr>z%s: %s (%s)rt   r   T)rG   rH   rå   rÙ   z%s.whitec                 s   s   | ]}t  |j¡V  qd S r4   )r9   r'   rd   rÅ  r0   r0   r1   r7   ú	  s     z‘Number of vertices in the surface could not be verified because the surface file could not be found; specify subject and subjects_dir parameters.)r   r‹  rŒ  rÌ   c                 3   s   | ]}ˆ   |¡V  qd S r4   )Úindexr  )Ú	annot_idsr0   r1   r7   
  s     c                 3   s   | ]}ˆ | j V  qd S r4   r   r  )Úhemi_labelsr0   r1   r7   
  s     z%s: %s overlaps %sc                 S   s   g | ]
}|j ‘qS r0   r   rÅ  r0   r0   r1   r„   
  s     zNFound %i labels with no name. Writing annotation filerequires all labels namedz/Assigning %i unlabeled vertices to 'unknown-%s'i  r‹  z„Need one free shade of gray for 'unknown' label. Please modify your label colors, or assign the unlabeled vertices to another label.Úunknownr�  c                    s&   g | ]}|  ˆ ¡r|d d… n|‘qS )Nr  )rù   )r5   ri   rh  r0   r1   r„   =
  s   ÿz_Some labels have the same color values (all labels in one hemisphere must have a unique color):r÷   zdSome labels have invalid color values (all colors should be RGBA tuples with values between 0 and 1)z”Some labels occupy vertices that are also occupied by one or more other labels. Each vertex can only be occupied by a single label in *.annot files.z

z   writing %d labels to %s)%r   rÑ   r   rš  rb   ÚexistsrY   r  r`   r9   rþ   rÿ   r  r�   r   r  r<   r  ri   r_  r   rD   rê   rN   r  rE   r   r'   r�  r»   rd   rc  ÚdiscardÚcountrŽ   ÚinsertrÂ  ).r'  rh   rn  ré   r°   r™  Zcolormaprf   r  rÁ  r   rZ  rì   Zto_saveZduplicate_colorsZinvalid_colorsre  Zno_color_rgbZn_hemi_labelsr•  Zctab_rgbZhemi_colorsZlabels_by_colorr’   r/   r&  r¨   Zdefault_colorsZsafe_color_ir  Zfpathr2  rã   r  Zmax_vertr’  Zannot_id_codingZannot_idZ	other_idsZother_indicesZother_namesZ
other_reprZ
hemi_namesZ	unlabeledr‘   Zissuesr0   )rË  rf   rÌ  rÉ  r1   Úwrite_labels_to_annotu	  sú    -

ÿ
ÿ
þ



ÿ 






ÿ
ÿ



 
ÿrÒ  r3  rB  c	                    s   t ˆ tƒrZtdˆ ddgƒ t || dˆ d ¡}	t|	ƒ\}
}tjt|
ƒt	d�}t
||
ˆ d�‰ t |tƒr¦td|d	d
gƒ |d	kr�ˆ j| d||d�}q°t|ƒ}| ˆ j¡}n
ˆ j| }ˆ jdkr¾dnd}t| ||||ƒd }||_|�st ‡ fdd„|jD ƒ¡}t
|j| |j| |j|| d�}|S )a´  Select sources from a label.

    Parameters
    ----------
    %(subject)s
    label : instance of Label | str
        Define where the seed will be chosen. If str, can be 'lh' or 'rh',
        which correspond to left or right hemisphere, respectively.
    location : 'random' | 'center' | int
        Location to grow label from. If the location is an int, it represents
        the vertex number in the corresponding label. If it is a str, it can be
        either 'random' or 'center'.
    extent : float
        Extents (radius in mm) of the labels, i.e. maximum geodesic distance
        on the white matter surface from the seed. If 0, the resulting label
        will contain only one vertex.
    grow_outside : bool
        Let the region grow outside the original label where location was
        defined.
    %(subjects_dir)s
    name : None | str
        Assign name to the new label.
    %(random_state)s
    surf : str
        The surface used to simulated the label, defaults to the white surface.

    Returns
    -------
    label : instance of Label
        The label that contains the selected sources.

    Notes
    -----
    This function selects a region of interest on the cortical surface based
    on a label (or a hemisphere). The sources are selected by growing a region
    around a seed which is selected randomly, is the center of the label, or
    is a specific vertex. The selected vertices can extend beyond the initial
    provided label. This can be prevented by setting grow_outside to False.

    The selected sources are returned in the form of a new Label object. The
    values of the label contain the distance from the seed in millimeters.

    .. versionadded:: 0.18
    r’   r~   r�   rÙ   z.whiterˆ   rh  Úlocationr3  ÚrandomT)rØ   r°   rÙ   r   r   c                    s   g | ]}|ˆ j k‘qS r0   r‡   r…   rÆ  r0   r1   r„   ®
  s     z"select_sources.<locals>.<listcomp>ri  )rW   rX   r    rb   rê   r   r9   r—   r`   r\   rO   rÚ   r   ry  rd   rf   rg  ri   r�   rJ   )rh   r’   rÓ  r\  Zgrow_outsider°   ri   rv  rÙ   Zsurf_filenamerd   rã   rÝ   r[  r|  rf   Z	new_labelZto_keepr0   rÆ  r1   Úselect_sources]
  s>    2

ÿ
  þ
  ÿrÕ  )Fr?   )NN)N)NN)NN)r3   NNF)NTFNN)NNTNrÛ   N)NrÛ   N)N)T)rP   )rŸ  rò   rÛ   NNNTN)NNrÛ   N)r   r   NNN)r3  rB  TNNNrÛ   )UÚcollectionsr   Úcolorsysr   r   r‹   r›   r„  Úos.pathÚpathrb   r¢  Únumpyr9   Z	morph_mapr   rf  r   Zsource_estimater   r	   r
   r   r   Zsource_spacer   r   r   Zstats.cluster_levelr   r   rà   r   r   r   r   r   r   Úutilsr   r   r   r   r   r   r   r   r    r!   r"   r2   r>   rN   rO   r£   ÚobjectrŠ   r  r™   r  rÅ   rÆ   rA  rM  rU  r]  rg  rd  rw  rt  rˆ  r–  rš  rž  r©  rª  r®  r·  rµ  r³  Z_DEFAULT_TABLE_NAMErÂ  rÀ  rÒ  rÕ  r0   r0   r0   r1   Ú<module>   sÚ    4* 
%     \aN*

M  ÿ 3    ÿ 3        ÿ F    ÿ4 ÿ
i
L ÿ
           þf    ÿ;  ÿJ#    ý h         þ