U
    f»{jAà ã                   @   sp  d Z ddlZddlZddlm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 dd	l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 ddl m!Z!m"Z"m#Z#m$Z$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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z: ddlm;Z; ddl<m=Z=m>Z> ddl?m@Z@mAZA dZBdd„ ZCd†dd„ZDdd„ ZEdd„ ZFd‡dd„ZGd d!„ ZHe%dd"d#d$dd"d%d&edd'deefd(d)„ƒZIdd"d#d$dd"d%d&edd'deefd*d+„ZJd,d-„ ZKd.d/„ ZLd0d1„ ZMG d2d3„ d3eNƒZOd4d5„ ZPdˆd6d7„ZQe%dddd"d$ddd#ddd%d&ed"deded8dfd9d:„ƒZRd;d<„ ZSd=ZTd>d?„ ZUd@dA„ ZVdddd"d$ddd#ddd%d&ed"deded8dfdBdC„ZWddd$dddDd#dd"d%d&edd"d#edefdEdF„ZXe#ddd$dddDd"d#dd"d%d&edd"ddddGdfddHœdIdJ„ƒZYe%d‰dMdN„ƒZZe%dGddddd"d"ddd$ddOdPdd#d"d#dddd%d&eddededdGfdQdR„ƒZ[dŠdSdT„Z\dUdV„ Z]d‹dXdY„Z^e#dŒd[d\„ƒZ_e%d�d^d_„ƒZ`e%dŽd`da„ƒZad�dbdc„Zbd�ddde„Zcdfdg„ Zddhdi„ Zee#djdk„ ƒZfdldm„ Zgdndo„ Zhdpdq„ ZiddHœdrds„Zjdtdu„ Zkd‘dvdw„Zldxdy„ Zme%ddzdddd"d$ddd#ddd%d&ed"dedfd{d|„ƒZne%d’d}d~„ƒZod“d€d�„Zpd”d‚dƒ„Zqd„d…„ ZrdS )•z/Functions to plot M/EEG data e.g. topographies.é    N)Úpartial)ÚIntegralé   )Úrescale)Ú_get_ch_type)Ú_find_topomap_coordsÚfind_layoutÚ_pair_grad_sensorsÚ_merge_ch_data)Ú_INTERPOLATION_DEFAULTÚ_EXTRAPOLATE_DEFAULTÚ_BORDER_DEFAULT)Ú
pick_typesÚ_picks_by_typeÚ	pick_infoÚpick_channelsÚ_pick_data_channelsÚ_picks_to_idxÚ_get_channel_typesÚ_MEG_CH_TYPES_SPLIT)
Ú_clean_namesÚ
_time_maskÚverboseÚloggerÚfill_docÚ_validate_typeÚ_check_sphereÚ_check_optionÚ_is_numericÚwarné   )Útight_layoutÚ_setup_vmin_vmaxÚ_prepare_trellisÚ_check_delayed_sspÚ_draw_proj_checkboxÚfigure_nobarÚplt_showÚ_process_timesÚDraggableColorbarÚ_validate_if_list_of_axesÚ_setup_cmapÚ_check_time_unitÚ_set_3d_axes_equalÚ_check_type_projs)Úpsd_multitaper)Ú_handle_default)Úapply_transÚinvert_transform)ÚInfoÚ_simplify_info)ÚhboÚhbrÚfnirs_cw_amplitudeÚfnirs_odc                 C   sv   t | |ƒ} |d k	st‚|dkr^|d d k	rXt|d ƒ}t|| d d… ƒ| d d…< d| d< d}n| d d…  ¡ }| |fS )N)ÚmagÚgradZplanar1Zplanar2Z
dev_head_té   ç        r   ©r<   r<   )r   ÚAssertionErrorr2   r1   Úcopy)ÚsphereÚinfoÚch_typeZ
head_dev_tÚclip_origin© rD   úN/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/viz/topomap.pyÚ_adjust_meg_sphere.   s    
	rF   c                    s   t  t| tƒr| n| j¡‰t|ˆ|ƒ\}}tˆd ƒ}tˆd ƒD ]\}}|| |d< qBtˆd ƒˆd< ˆd D ]}t|d d ƒ|d d< qpˆ ¡  ˆ 	¡  t
ˆƒ}|dkrú|d	k	rú|j d
¡sÎ|j d¡rútˆ|ƒ\}	}
tˆ|	d	d	d… |d�}d}nÔ|tk�rtˆ||ƒ\}	}}}n´d}|dk�r<tˆddddd�}	nj|dk�rZtˆddddd�}	nL|dk�rxtˆddddd�}	n.|dk�r–tˆddddd�}	ntˆ|ddd�}	t|	ƒdk�rÀtd| ƒ‚tˆ|	|d�}‡fdd„|	D ƒ‰ |tk�rødd„ ˆ D ƒ‰ |�rt|dk�r(‡ fdd„tdtˆ ƒdƒD ƒ‰ nL|tk�s6t‚|D ]8}ˆ  |d d	d… ¡}d  d!d"„ |D ƒ¡}|ˆ |< �q:t |¡d	d	…d	d…f }|	||ˆ |||fS )#zPrepare topo plot.Úch_namesÚchsÚch_nameÚbadsÚcompsÚdataÚ	col_namesr:   NZ
VectorviewZNeuromag_122r   ©r@   TFÚeeg)ÚmegrO   Úref_megÚexcludeÚcsd)rP   rS   rQ   rR   Údbs)rP   rT   rQ   rR   Úseeg)rP   rU   rQ   rR   )rP   rQ   rR   r   zNo channels of type %rc                    s   g | ]}ˆ d  | ‘qS ©rG   rD   ©Ú.0Úk©rA   rD   rE   Ú
<listcomp>w   s     z)_prepare_topomap_plot.<locals>.<listcomp>c                 S   s   g | ]}|d d… ‘qS ©NéüÿÿÿrD   rW   rD   rD   rE   r[   z   s     c                    s    g | ]}ˆ | d d… d ‘qS )NéÿÿÿÿÚxrD   rW   rV   rD   rE   r[   €   s     r]   r_   c                 s   s   | ]}|d d… V  qd S r\   rD   )rX   ÚsrD   rD   rE   Ú	<genexpr>‰   s     z(_prepare_topomap_plot.<locals>.<genexpr>)r?   ÚdeepcopyÚ
isinstancer3   rA   rF   r   Ú	enumerateZ_update_redundantZ_check_consistencyr   ÚkindÚ
startswithr	   r   Ú_fnirs_typesÚ_average_fnirs_overlapsr   ÚlenÚ
ValueErrorÚranger>   ÚindexÚjoinÚnpÚarray)ÚinstrB   r@   rC   Zclean_ch_namesÚiiZthis_chÚcompÚlayoutÚpicksÚ_ÚposÚmerge_channelsÚoverlapping_channelsÚsetÚidxÚnew_namerD   )rG   rA   rE   Ú_prepare_topomap_plotE   sx    
ÿ
þ

ÿ

ÿ

ÿ

ÿ

ÿÿ


ÿr|   c                    sª  ddl m}m} tˆdd|dd�}‡fdd„|D ƒ‰ t dd„ ˆ D ƒ¡}||ƒ}tƒ }tƒ }	t|ƒd	k�rzt |¡d
k �rzt 	||d
k ƒ¡}
t
|
jd ƒD ]‚}ttj |¡ƒ}|
|  ¡ ršˆ | d |krš‡ fdd„t |
| ¡d D ƒ}t |dˆ | d ¡}| |¡ |	 |d	d … ¡ qšttj |	¡ƒ‰‡fdd„ˆd D ƒ tˆdd|ˆd�}tˆ||d�}tˆdd|d�}|}n$tˆdd|dd�}d}tˆ||d�}||||fS )Nr   )ÚpdistÚ
squareformFrJ   )rP   rQ   ÚfnirsrR   c                    s   g | ]}ˆ d  | ‘qS ©rH   rD   ©rX   ÚirZ   rD   rE   r[   –   s     z+_average_fnirs_overlaps.<locals>.<listcomp>c                 S   s   g | ]}|d  dd… ‘qS )ÚlocNr;   rD   )rX   ÚchrD   rD   rE   r[   —   s     r    g»½×Ùß|Û=rI   c                    s   g | ]}ˆ | d  ‘qS )rI   rD   r�   r€   rD   rE   r[   ©   s     c                    s   g | ]}ˆ   |¡‘qS rD   )Úappend)rX   Úbad©rR   rD   rE   r[   ±   s     rN   )rP   rQ   r   )Zscipy.spatial.distancer}   r~   r   rn   ro   Úlistri   ÚminZtriurk   ÚshapeÚ	itertoolsÚchainÚfrom_iterableÚanyÚwhereÚinsertr…   r   )rA   rB   r@   r}   r~   rt   Zlocs3dÚdistrx   Zchannels_to_excludeZoverlapping_maskZchan_idxZalready_overlappedZoverlapping_setrv   rw   rD   )rH   rR   rA   rE   rh   �   sR     ÿÿÿ
ÿ
ÿ

ÿ
ÿrh   c              	      sœ  ‡ fdd„t | d ƒD ƒ}ˆ | d< | d  ¡ }|j ¡ � g |jd< W 5 Q R X | |¡ | ¡  |jdd…| d f | d  }| d	 r–t|d
g ƒ\}}| d }tƒ }t	| d | d | d |j
ƒD ]À\}}	}
}| |¡ƒ }|
 |¡ d}t|jƒdk�r |jd }| ¡ }| ¡ }| ¡ }| ¡ }|jD ]}| ¡  �q&|	j|j|j|| d ||d�}|jD ]}| |¡ | |¡ �qZ| |¡ qÀ|| d< | d j ¡  dS )zUpdate topomaps.c                    s&   g | ]\}}|t  ˆ ¡d  kr|‘qS )r   )rn   r�   )rX   rq   Úproj©ÚboolsrD   rE   r[   Å   s    ÿz/_plot_update_evoked_topomap.<locals>.<listcomp>ÚprojsZ
proj_boolsÚevokedNÚtime_idxÚscalerw   r:   ÚinterpÚ	contours_ÚaxesÚimagesrY   r   Úcontours©ÚcolorsÚ
linewidthsÚfig)rd   r?   rA   Ú_unlockZadd_projÚ
apply_projrL   r
   rˆ   ÚzipÚTÚ
set_valuesÚset_datari   ÚcollectionsZget_visibleZget_clip_pathZget_edgecolorsZget_linewidthÚremoveÚcontourÚXiÚYiZset_visibleÚset_clip_pathr…   ÚcanvasÚdraw)Úparamsr”   r•   Z
new_evokedrL   ru   r™   Znew_contoursÚcontÚaxÚimÚdÚZiÚcolorÚtpÚvisibleÚpatch_ÚlwrD   r“   rE   Ú_plot_update_evoked_topomapÃ   sJ    
 ÿ


 ÿ

r»   Úrightçš™™™™™©?ú5%c                 C   s|   ddl m} ddlm}	 |	| ƒ}
|
j|||d�}|j|||d�}|dk	r\|d r\t||ƒ| _|dk	rt|j|ddd	� ||fS )
zAdd a colorbar to an axis.r   N)Úmake_axes_locatable)ÚsizeÚpad)ÚcaxÚformatr    gÍÌÌÌÌÌð?é
   )ÚyÚfontsize)	Úmatplotlib.pyplotÚpyplotZmpl_toolkits.axes_grid1r¿   Zappend_axesÚcolorbarr)   ÚCBÚ	set_title)r²   r³   ÚcmapÚsiderÁ   ÚtitlerÃ   rÀ   Úpltr¿   ÚdividerrÂ   ÚcbarrD   rD   rE   Ú_add_colorbarî   s    rÒ   c                    sä   d}d}t  | ¡} t | d d ¡| d d< ||fD ]’‰ | d d }‡ fdd„t|ƒD ƒ}| d d d |  ¡ s4t t |¡|¡ ¡ }t t | d d d ¡|¡}|| d d< t |g¡| d d< q4t	| d d ƒ| d d< | S )	z6Remove grad or mag data if only contains 0s (gh 5641).)Ú2Ú3Ú1rL   rM   c                    s   g | ]\}}|  ˆ ¡r|‘qS rD   )Úendswith)rX   r‚   Úname©ÚendingrD   rE   r[     s     
 z$_eliminate_zeros.<locals>.<listcomp>r   Zncol)
r?   rb   rn   Ú
atleast_2drd   rŽ   Údeletero   Útolistri   )r’   ZGRAD_ENDINGZ
MAG_ENDINGÚnamesrz   Znew_col_namesZnew_datarD   rØ   rE   Ú_eliminate_zerosý   s    
rÞ   TFé@   Úheadé   ©NNc                 C   s^   t | ||||||||	|
|||||d�}tjdd�� t d¡ t|d� W 5 Q R X t|ƒ |S )a—  Plot topographic maps of SSP projections.

    Parameters
    ----------
    projs : list of Projection
        The projections.
    %(info_not_none)s Must be associated with the channels in the projectors.

        .. versionchanged:: 0.20
            The positional argument ``layout`` was deprecated and replaced
            by ``info``.
    %(proj_topomap_kwargs)s
    %(sphere_topomap_auto)s
    %(extrapolate_topomap)s

        .. versionadded:: 0.20
    %(border_topomap)s

    Returns
    -------
    fig : instance of matplotlib.figure.Figure
        Figure with a topomap subplot for each projector.

    Notes
    -----
    .. versionadded:: 0.9.0
    )rÌ   ÚsensorsrÉ   ÚresrÀ   Úoutlinesr�   Úimage_interpr›   Úvlimr@   ÚextrapolateÚborderT©ÚrecordÚignore©r¡   )Ú_plot_projs_topomapÚwarningsÚcatch_warningsÚsimplefilterr!   r'   )r•   rA   rÌ   rã   rÉ   rä   rÀ   Úshowrå   r�   ræ   r›   rç   r@   rè   ré   r¡   rD   rD   rE   Úplot_projs_topomap  s,    #           ü
ró   c           <         s„  dd l m} t||ƒ}t| ƒ} t|ddƒ g g g g g g f\}}}}}}| D �]\}t|ƒ}t|d d dd�}ˆdkrÆt t 	|d |d d ¡¡d }t
||dd	�}t|ƒd
ks´t‚| t|ƒd ¡ |d d  ¡ }t|d dd�}t||ƒ}t|ƒdk�rtd|› �ƒ‚t||ƒ}t|t|d ƒ|d�\}} }!}"}#}$}%t|| ||%ƒ}&|| }|!�rlt|dg ƒ\}}'| ¡ }| |¡ | | ¡ | |$¡ | |&¡ | |#¡ ~~ ~$~&~#qJ~t| ƒ}(|d k�rÚt|(ddddd�\})}}*}+nt||jƒ�rî|g}t||(ƒ dd„ tt|ƒƒD ƒ},ˆdk�r t|ƒD ]d}-t t 	||-¡¡d }.t tj|td�|. ¡}/t |/dkƒ}0t!|/d d |0d�}1|.D ]}2|1|,|2< �qr�q t dd„ |,D ƒƒ�sºt‚n‡fdd„tt|ƒƒD ƒ},t"| ||||,|||ƒD ]¦\}}3}4}5}6}7}8}-|d ‰ d #‡ fdd„tdtˆ ƒdƒD ƒ¡‰ |3j$ˆ dd� |6\}9}:t%|4|5d d …d d…f |9|:||||3|8|	|
d||7||-d�d };|�rÐt&|3|;|ƒ �qÐ|3 '¡ })|)S ) Nr   rA   rL   rM   T)Zremove_whitespaceÚjointrG   ©Úuniquer    z)No channel names in info match projector rN   r:   Úauto)ÚncolsÚnrowsZsharexZshareyc                 S   s   g | ]}d ‘qS ©NrD   ©rX   ru   rD   rD   rE   r[   €  s     z'_plot_projs_topomap.<locals>.<listcomp>©Zdtype)ÚvminÚvmaxÚnormc                 S   s   g | ]}|d k	‘qS rú   rD   )rX   ZvlrD   rD   rE   r[   Š  s     c                    s   g | ]}ˆ ‘qS rD   rD   rû   )rç   rD   rE   r[   Œ  s     ÚdescÚ
c                 3   s   | ]}ˆ ||d  … V  qdS )é   NrD   ©rX   rq   )rÎ   rD   rE   ra   “  s     z&_plot_projs_topomap.<locals>.<genexpr>r  rÄ   ©rÆ   r   F)rý   rþ   rÌ   rã   rä   r›   rå   r�   ræ   rò   rè   r@   ré   rB   )(rÇ   rÈ   r   r.   r   rÞ   r   rn   r�   Zin1dr   ri   r>   r…   rˆ   Úravelr   rj   r   r|   r   Ú_make_head_outlinesr
   r#   rc   ÚAxesr*   rk   ry   Úconcatenatero   ÚobjectÚallr"   r¤   rm   rË   Úplot_topomaprÒ   Ú
get_figure)<r•   rA   rÌ   rã   rÉ   rä   rÀ   rò   rå   r�   ræ   r›   rç   r@   rè   ré   rÏ   ÚtypesZdatasZpossZspheresZ	outlinessZ	ch_typessr’   rG   Zch_idxsZthese_ch_typesrL   Z
info_namesrt   Zuse_infoÚ
data_picksrv   rw   rÝ   rB   Zthis_sphererC   Zthese_outlinesru   Zn_projsr¡   rø   rù   ÚvlimsZ_ch_typerz   Z
these_datarÿ   Z_vlZ_idxr²   Ú_dataÚ_posZ_vlimZ_sphereZ	_outlinesrý   rþ   r³   rD   )rÎ   rç   rE   rî   C  sÖ    

ÿ
ÿÿ
ÿ
  ÿÿ   ÿ





    ÿ

       ÿ$      ûûrî   c                 C   sÞ  t | tjƒst‚| \}}}}~ |dk�r²t ddtj d¡}t |¡| | }	t |¡| | }
t t 	t 
d¡¡d ¡}|j|j }}t | d|g¡| | }t |d|g¡| | }t dd	d
dddddd	dg
¡|d  }t ddddddddddg
¡|d  | }|dk	�r@t|	|
f||f|| |f| | |fd�}ntƒ }|dk�rTdnd}t|tjj|dd � ¡ d! | ƒ}||	 ||
 f|d"< || }|fd |d#< ||d$< |}n(t |tƒ�rÒd"|k�rÚtd%ƒ‚ntd&ƒ‚|S )'z&Check or create outlines for topoplot.)rà   ÚskirtNr   r   ée   é   y              ð?çffffffò?g+‡ÙÎß?gR¸…ëQà?gú~j¼t“à?gÐDØðôà?gz6«>Wá?gHáz®Gá?g/Ý$�á?g /Ý$á?g²�ï§ÆKß?gÑ"Ûù~j¬?g×£p=
×³?g]ÜFx´?gðHPü³?gºI+‡v¿g$¹ü‡ôÛ·¿g‘~û:pÎÀ¿geâX·Á¿g¨WÊ2Ä±¾¿N)rà   ÚnoseZear_leftZ	ear_rightr  g      ô?ç      ð?r    ©Úaxisg)\�Âõ(ð?Úmask_posÚclip_radiusrC   z3You must specify the coordinates of the image mask.zInvalid value for `outlines`.)rc   rn   Úndarrayr>   ÚlinspaceÚpiÚcosÚsinÚexpZarccosZdeg2radÚrealÚimagro   ÚdictÚmaxÚlinalgrÿ   rj   )r@   rv   rå   rC   r_   rÅ   ru   ZradiusZllZhead_xZhead_yÚdxÚdyZnose_xZnose_yZear_xZear_yZoutlines_dictZ
mask_scaler  rD   rD   rE   r  ¥  s`    
  ÿÿ  ÿÿÿ

þ ÿ

r  c                 C   sb   ddl m} dd„ | ¡ D ƒ}| ¡ D ]6\}\}}d|ks&|dkrDq&| j|||d dd	d
� q&|S )z Draw the outlines for a topomap.r   )ÚrcParamsc                 S   s   i | ]\}}|d kr||“qS ))ÚpatchrD   )rX   rY   ÚvrD   rD   rE   Ú
<dictcomp>Ù  s    ÿ z"_draw_outlines.<locals>.<dictcomp>Úmask)r  rC   zaxes.edgecolorr    F©r¶   Ú	linewidthÚclip_on)Ú
matplotlibr)  ÚitemsÚplot)r²   rå   r)  Ú	outlines_ÚkeyZx_coordZy_coordrD   rD   rE   Ú_draw_outlinesÖ  s     ÿr6  c           5   	      s@  ddl m} t |t¡}|jdks&t‚|\}}td|dƒ d}|dk�rt ˆ jdd�ˆ j	dd�g¡}|d	 |d  }	|d  |	8  < |d	  |	7  < t t
tjdgˆ jd	 d	  d	g gˆ jd	  Ž ƒ¡}
t t ˆ jd	 ¡tj t|
ƒd	f¡}||
|f }|||t ˆ |f¡ƒfS tjˆ dd�}	tjd
d��& |	dd…d	f |	dd…df  }W 5 Q R X ||d k ¡ �pzt |¡ ¡ }|�s’ˆ jd dk �r|	dd…d	f  ¡ |	dd…df  ¡ k�rÀd	nd}t ˆ dd…|f ¡}ˆ |dd…f }tj|dd�}	tjj|	d	d�}t |¡}nJ|ˆ dd�}|jj\}}}t ‡ fdd„t||g||gƒD ƒ¡}t |¡}|dk�rN|�s~ˆ jd dk �r–|ddg }tjˆ |dd…f dd�}|tj |¡ | }|dd…ddd…f dd	gg }ˆ |dd…f tj| |gdd� }tjˆ | ˆ | |gdd�}ˆ jd dk�rvˆ dtjf |jtjdd…f  }tjj|d	d�}|d| kjdd�}|| }|tjˆ |gdd�ƒ}|||fS ˆ |j } ˆ jdd�}!| |! }"|"tjj|"ddd� }#| |#|  }$| |#| d  }tj| d	d�dd…df }%tjj|%dd�}&~!tj | !dd¡dd�}tj|dd�}'||'8 }|t t "|dd…d	f |dd…df ¡¡ }||'7 }t
ƒ }(t #d¡j$})t %d|& | ¡ &d¡}*t'd|* 	¡ d	 ƒD ]v}+|*|+k},t d	|+ d	|) d	|+ ¡dd…tjtjf }-|%|, tjdf |- }.|( (|$|,df tjdf |.  !d¡¡ �q°tj |$ !d¡dd�}$t |$g|( ¡}nÞ|dk�s\t‚t )t|t |¡ d	ƒ¡}/t	dt*t %dtj+ |/ ¡ƒƒ}0tj,ddtj+ |0dd�}1|d  | }2t -|1¡|2d  | }3t .|1¡|2d	  | }4tj/|3|4gd	d�}|�sˆ jd dk�r,|tjˆ |gdd�ƒ}|||fS | 0|¡ |||fS )!z3Get coordinates of additional interpolation points.r   )ÚDelaunay)r   rè   )rà   ÚboxÚlocalNr8  r  r    rì   )Údivideé   T)Úincrementalc                    s<   g | ]4\}}t jjˆ |d d …f ˆ |d d …f  dd�‘qS ©Nr    r  )rn   r&  rÿ   )rX   Úi1Úi2©rv   rD   rE   r[     s   ÿz%_get_extra_points.<locals>.<listcomp>r9  r^   r;   .ç      à?©r  Zkeepdimsr   Úfloatç      Ð?Úint)r^   r   rà   r  F©Zendpointgš™™™™™ñ?)1Úscipy.spatialr7  rn   ro   rC  rŠ   r>   r   r‰   r%  rˆ   r‹   ÚproductÚtileÚarangeÚnewaxisri   r  ÚdiffZerrstater
  ÚisinfÚsumZargsortr&  rÿ   ÚmedianZ	simplicesr¥   r¤   Zconvex_hullÚmeanrö   ÚreshapeZarctan2ZfinfoÚepsÚroundÚastyperk   r…   ZarcsinrE  r  r  r  r   ÚstackÚ
add_points)5rv   rè   ÚoriginÚradiir7  r_   rÅ   r  ZextremesZdiffsZeidxZpidxÚ	outer_ptsZslopesZcolinearÚdimZsortingZ
pos_sortedZ	distancesZdistanceÚtriÚidx1Zidx2Zidx3Zedge_pointsÚline_lenZunit_vecZunit_vec_parZedge_posÚnew_posZnew_pos_diffZ
good_extraZhull_posZchannels_centerZ
radial_dirZunit_radial_dirZhull_extendedZ	hull_diffZhull_distancesZmask_centerrV  rR  Zn_times_distÚnr-  ZmultZstepsZangleZn_pntsZpoints_lZ	use_radiiZpoints_xZpoints_yrD   r@  rE   Ú_get_extra_pointsã  sÎ    

$ÿ&* 2
ÿÿ

 ÿ
 ÿÿ"

ÿ(ÿ,ÿÿ


r`  c                   @   s0   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
S )Ú	_GridDatazÚUnstructured (x,y) data interpolator.

    This class allows optimized interpolation by computing parameters
    for a fixed set of true points, and allowing the values at those points
    to be set independently.
    c                 C   s¨   ddl m}m}m}	 |jdkr,|jd dks6t|jƒ‚t|dtfdƒ t	|tƒr`t
d|ddd	� t||||ƒ\}
}}|
jd | _|| _|| _|| _|||	d
œ| | _d S )Nr   )ÚCloughTocher2DInterpolatorÚNearestNDInterpolatorÚLinearNDInterpolatorr   r    Únumericré   )rP  zwhen a string)Úextra)ÚcubicÚnearestÚlinear)Zscipy.interpolaterb  rc  rd  ÚndimrŠ   r>   r   Ústrrc   r   r`  Ún_extraÚmask_ptsré   r[  r™   )Úselfrv   ræ   rè   rW  rX  ré   rb  rc  rd  rY  rm  r[  rD   rD   rE   Ú__init__f  s*    "
   ÿ
þþz_GridData.__init__c                 C   s  t | jtƒrÎ|jd }t | j¡}| jj\}}t	||| j ƒ}t t
|ƒt¡}t|ƒD ]P\}}	|||	 ||	d  … }
|
|
|k  }
t
|
ƒdkrVd||< ||
  ¡ ||< qV| ¡ sâ| ¡ rât || ¡|| < ntj| j| jtd�}t ||f¡}|  | j|¡| _| S )z'Set the values at interpolation points.r   r    Trü   )rc   ré   rk  rŠ   rn   Úzerosrl  r[  Zvertex_neighbor_verticesrk   ri   Úboolrd   rP  r
  rŽ   ÚfullrC  r  r™   Úinterpolator)rn  r+  Zn_pointsZv_extraÚindicesZindptrÚrngÚusedrz   Z	extra_idxZngbrD   rD   rE   r¦   }  s$    	
z_GridData.set_valuesc                 C   s   || _ || _| S )z+Set locations for easier (delayed) calling.)r«   r¬   )rn  r«   r¬   rD   rD   rE   Úset_locationsŸ  s    z_GridData.set_locationsc                 G   s"   t |ƒdkr| j| jg}| j|Ž S )zEvaluate the interpolator.r   )ri   r«   r¬   rs  )rn  ÚargsrD   rD   rE   Ú__call__¥  s    z_GridData.__call__N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ro  r¦   rw  ry  rD   rD   rD   rE   ra  ^  s
   "ra  c                 C   s<   |dkr*|j | |dddgt| ƒ dd� n| | ||¡ dS )zPlot sensors.TrD  ÚorY   Únone)r`   ÚmarkerZ	edgecolorZ	facecolorN)Úscatterri   r3  )Úpos_xÚpos_yrã   r²   rD   rD   rE   Ú_topomap_plot_sensors¬  s     ÿr„  c           	      C   sl   t tt| ƒ|ƒd ƒ}|}t|| |ƒ\}}t d|› d|› d|› �¡ t| |d||d�}t||d|ƒ}||fS )Nz$Generating pos outlines with sphere z from z for T)Zignore_overlapÚ	to_spherer@   rà   )r   r   r4   rF   r   Údebugr   r  )	rA   rt   r@   r…  rB   Zorig_sphererC   rv   rå   rD   rD   rE   Ú_get_pos_outlinesµ  s       þr‡  rO   c                 C   s¨   t |ƒ}ddlm} t||dfdƒ |dk	rl|dk	rLtd|j› d|› d�ƒ |dk	rltd|j› d	|› d�ƒ t| |||||||||	|
|||||||||||d
�dd… S )u5  Plot a topographic map as image.

    Parameters
    ----------
    data : array, shape (n_chan,)
        The data values to plot.
    pos : array, shape (n_chan, 2) | instance of Info
        Location information for the data points(/channels).
        If an array, for each data point, the x and y coordinates.
        If an `~mne.Info` object, it must contain only one data type and
        exactly ``len(data)`` data channels, and the x/y coordinates will
        be inferred from the montage applied to the `~mne.Info` object.
    %(vmin_vmax_topomap)s
    %(cmap_topomap_simple)s
    sensors : bool | str
        Add markers for sensor locations to the plot. Accepts matplotlib plot
        format string (e.g., ``'r+'`` for red plusses). If True (default),
        circles will be used.
    res : int
        The resolution of the topomap image (number of pixels along each side).
    axes : instance of Axes | None
        The axes to plot to. If None, the current axes will be used.
    names : list | None
        List of channel names. If None, channel names are not plotted.
    %(show_names_topomap)s
        If ``True``, a list of names must be provided (see ``names`` keyword).
    %(mask_topomap)s
    %(mask_params_topomap)s
    %(outlines_topomap)s
    contours : int | array of float
        The number of contour lines to draw. If ``0``, no contours will be
        drawn. If an array, the values represent the levels for the contours.
        The values are in ÂµV for EEG, fT for magnetometers and fT/m for
        gradiometers. Defaults to ``6``.
    %(image_interp_topomap)s
    show : bool
        Show figure if True.
    onselect : callable | None
        Handle for a function that is called when the user selects a set of
        channels by rectangle selection (matplotlib ``RectangleSelector``). If
        None interactive selection is disabled. Defaults to None.
    %(extrapolate_topomap)s

        .. versionadded:: 0.18
    %(sphere_topomap)s
    %(border_topomap)s
    %(ch_type_topomap)s
    %(cnorm)s

        .. versionadded:: 0.24

    Returns
    -------
    im : matplotlib.image.AxesImage
        The interpolated data.
    cn : matplotlib.contour.ContourSet
        The fieldlines.

    Notes
    -----
    The ``cnorm`` parameter can be used to implement custom colormap
    normalization. By default, a linear mapping from vmin to vmax is used,
    which correspond to the first and last colors in the colormap. This might
    be undesired when vmin and vmax are not symmetrical around zero (or a value
    that can be interpreted as some midpoint). For example, assume we want to
    use the RdBu colormap (red to white to blue) for values ranging from -1 to
    3, and 0 should be white. However, white corresponds to the midpoint in the
    data by default, i.e. 1. Therefore, we use the following colormap
    normalization ``cnorm`` and pass it as the the ``cnorm`` argument:

    .. code-block:: python

        from matplotlib.colors import TwoSlopeNorm
        cnorm = TwoSlopeNorm(vmin=-1, vcenter=0, vmax=3)

    Note that because we define ``vmin`` and ``vmax`` in the normalization,
    arguments ``vmin`` and ``vmax`` to ``plot_topomap`` will be ignored if a
    normalization is provided. See the
    :doc:`matplotlib docs <matplotlib:tutorials/colors/colormapnorms>`
    for more details on colormap normalization.
    r   ©Ú	NormalizeNÚcnormzvmin=z/ is implicitly defined by cnorm, ignoring vmin=Ú.zvmax=z/ is implicitly defined by cnorm, ignoring vmax=)r@   ré   rB   rŠ  r   )r   Úmatplotlib.colorsr‰  r   r   rý   rþ   Ú_plot_topomap)rL   rv   rý   rþ   rÌ   rã   rä   r›   rÝ   Ú
show_namesr-  Úmask_paramsrå   r�   ræ   rò   Úonselectrè   r@   ré   rB   rŠ  r‰  rD   rD   rE   r  Â  s4    Y          üür  c              	   C   s”  |dkrt d|› d�ƒ‚t d|› d|› d|› �¡ tjtj f}tjtj f}tj|d  }|d }	| d	d
¡}
t tj|d |d d …df |
d |	d  f ¡t 	tj|d |d d …df |
d |	d  f ¡ }}t tj|d |d d …df |
d |	d  f ¡t 	tj|d |d d …df |
d |	d  f ¡ }}t 
|||¡}t 
|||¡}t ||¡\}}t| |||
|	|ƒ}||||f}||||fS )N)rg  ri  rh  z;`image_interp` must be `cubic`, `linear` or `nearest`, got a  . Previously, `image_interp` controlled the matplotlib image interpolation after an original cubic interpolation but this was changed to control the first interpolation instead for simplicity. To change the matplotlib image interpolation, use `im.set_interpolation(...)zInterpolation mode z, extrapolation mode z to r  r  rC   r=   r   r    )ÚRuntimeErrorr   r†  rn   ÚinfZc_Úgetr‰   Zr_r%  r  Zmeshgridra  )rv   rä   ræ   rè   rå   ré   ÚxlimÚylimÚmask_r  rC   ÚxminÚxmaxÚyminÚymaxÚxiÚyir«   r¬   r™   ÚextentrD   rD   rE   Ú_setup_interp,  sL    
ÿþþýþþý  ÿrž  éd   c                    sh  ddl m} |jt ||f¡tj |dd||d�}	|d \‰ ‰| dd¡\}
}|t |‡ ‡fd	d
„tt	ƒD ƒg¡ƒ}t
|jdt	 … ƒD ]Ú\}}d|j| kr qˆtƒ }|j| D ]�}|j| \}}||
 d ˆ d  || d ˆd   dk rþ| ||f¡ q°|ˆ tj |j| ¡ 9 }|ˆtj |j| ¡ 9 }| ||f¡ q°|jt|Ž d||| | ƒƒiŽ qˆ|	S )z$Make a Voronoi diagram on a topomap.r   )ÚVoronoiÚlowerÚequal)rÌ   rW  Úaspectr�  rÿ   r  rC   r=   c                    sL   g | ]D}ˆ d  t  dt j t | ¡ ˆd  t  dt j t | ¡ f‘qS )ç      ø?r   )rn   r  r  Ú_VORONOI_CIRCLE_RESr   ©rX   Út©ÚrxZryrD   rE   r[   a  s   þÿz$_voronoi_topomap.<locals>.<listcomp>Nr^   r   r    r¶   )rG  r   Úimshowrn   rp  Únanr“  r  rk   r¥  rd   Zpoint_regionZregionsrˆ   Zverticesr…   r&  rÿ   Úfillr¤   )rL   rv   rå   r²   rÌ   rÿ   r�  rä   r   r³   ZcxÚcyZvorZ	point_idxZ
region_idxZpolygonr‚   r_   rÅ   rD   r¨  rE   Ú_voronoi_topomapU  s:      þþÿÿ,"r®  c           	      C   sÎ   ddl m} | d }|  dd¡}tdd„ | D ƒƒ}d }d| kr‚| d }t|ƒrT|ƒ n|}| d	¡ | |¡ | |j¡ | 	|¡ |rÊ|d
kr¤|j
|jd|jd�}n&|j|d|d  d|d  d|jd�}|S )Nr   )Úpatchesr  rC   r=   c                 s   s   | ]}|  d ¡V  qdS )rà   N)rf   rW   rD   rD   rE   ra   y  s     z_get_patch.<locals>.<genexpr>r*  Fr9  T)r0  Ú	transformr   r    )r1  r¯  r“  rŽ   ÚcallableZset_clip_onZ	add_patchZset_transformÚ	transAxesr­   ZPolygonrm  Z	transDataZEllipse)	rå   rè   r™   r²   r¯  r  rC   Z_use_default_outlinesr¹   rD   rD   rE   Ú
_get_patchu  s6    


  ÿ 
 
 þr³  c           7   
      sB  ddl m} dd lm} ddlm} t | ¡} t 	dˆ › d| j
› �¡ t|tƒ�rPt|dd�}t||ƒ}t|dd	�‰ d
}tˆ ƒdkr’td| ƒ‚nBt|d ƒ| j
d krÌtdt|d ƒ| j
d f | ƒ‚nˆ  ¡ ‰ t‡ fdd„dD ƒƒ�r0t|dd�}t||d d d… |d�}t| | ˆ g ƒ\} }|  d¡} n tt| j
d ƒƒ}t|||d�}t|ˆ ƒ}| jdk�rxtdt| j
ƒ ƒ‚d}|jdk�r¨dj|jd�}t|d | ƒ‚nN|j
d dk�rÎd}t|d | ƒ‚n(|j
d dk�sî|j
d dk�röt|ƒ‚|d d …d d…f }t| ƒt|ƒk�r4tdt| ƒt|ƒf ƒ‚t| ƒdk}t| |||ƒ\}}|d k�rr|  |�rjd nd!¡}nt|tƒ�rˆ|  |¡}t!|||d"ƒ}t|t"ƒ�s¦t#‚|�r°|n| $¡ }t%||ƒ t&d#|ƒ}t'||||||ƒ\} }!}"}#|# (| ¡ |# )|!|"¡ƒ }$t*|||#|ƒ}%|d k�r"|||d$�}|d%k�rFt+| |||||| |d&�}&n|j,|$|d'd(| d)|d*�}&|d+ }'d}(t|tj-tfƒ�r~n*|dk�s¤|$|$d, kt .|$¡B  /¡ �r¨d }(|(�rêt0j1dd-��* t0 2d.¡ |j3|!|"|$|d/|'d0 d1�}(W 5 Q R X |%d k	�r |& 4|%¡ |(d k	�r |(j5D ]})|) 4|%¡ �q|j6\}*}+|
d k	�rB|
j7t8dd2�nd }
|dk	�rl|
d k�rlt9|*|+||d3� n–|�rÌ|
d k	�rÌt :|
¡d },|j;|*|, |+|, f|Ž t :|
 ¡d },t9|*|, |+|, ||d3� n6|�s|
d k	�rt :|
¡d },|j;|*|, |+|, f|Ž t|t"ƒ�rt<||ƒ |	�rÀ|d k�r0td4ƒ‚|	dk�rDd5d6„ }-n|	}-|
d k�r`t =t|ƒ¡nt :|
¡d }.t>t?||ƒƒD ]B\}/\}0}1|/|.k�r–�q||-|1ƒ}1|j@|0d |0d |1d7d7d8d9� �q||jA B¡ �sØ|jCd:d;� |d k	�r0|jD}2|2jE|2jF|2jG|2jHf\}3}4}5}6|||d<�|_I|jJ|3|3|5 g|4|4|6 gd=� tK|ƒ |&|(|#fS )>Nr   rˆ  )ÚRectangleSelectorzPlotting topomap for z data shape rD   r‡   Trõ   zJPick Info with e.g. mne.pick_info and mne.io.pick.channel_indices_by_type.r    z*Multiple channel types in Info structure. rH   zQNumber of channels in the Info object (%s) and the data array (%s) do not match. c                 3   s   | ]}|ˆ kV  qd S rú   rD   )rX   Útype_©rB   rD   rE   ra   «  s     z _plot_topomap.<locals>.<genexpr>)Úplanarr:   F)Útopomap_coordsr   )rt   r@   r^   z;Data needs to be array of shape (n_sensors,); got shape %s.z—Electrode positions should be specified as a 2D array with shape (n_channels, 2). Each row in this matrix contains the (x, y) position of an electrode.zL{ndim}D array supplied as electrode positions, where a 2D array was expected)rj  ú r;   z­The supplied electrode positions matrix contains 3 columns. Are you trying to specify XYZ coordinates? Perhaps the mne.channels.create_eeg_layout function is useful for you.r;  zOData and pos need to be of same length. Got data of length %s, pos of length %sÚRedsÚRdBu_rr=   r�  )rý   rþ   rh  )rv   rå   r²   rÌ   rÿ   r�  rä   r¡  r¢  Úbilinear)rÌ   rW  r£  r�  Úinterpolationrÿ   Úmarkeredgewidth©r   r   rê   rì   rY   ç       @rž   ©r?   )rã   r²   zFTo show names, a list of names must be provided (see `names` keyword).c                 S   s   | S rú   rD   ©r_   rD   rD   rE   Ú_show_names   s    z"_plot_topomap.<locals>._show_namesÚcenterúx-small)ÚhorizontalalignmentÚverticalalignmentrÀ   çffffffî?©Útop)r�  )r”  r•  )LrŒ  r‰  rÇ   rÈ   Úmatplotlib.widgetsr´  rn   Zasarrayr   r†  rŠ   rc   r3   r   r   r   ri   rj   ÚpoprŽ   r	   r   r
   rQ  rˆ   rk   Ú_check_extrapolaterj  rk  rÃ   r‰   r"   Zget_cmapr  r$  r>   ZgcaÚ_prepare_topomapr0   rž  r¦   rw  r³  r®  rª  r  Úisnanr
  rï   rð   rñ   rª   r­   r¨   r¥   rT  rq  r„  r�   r3  r6  rJ  rd   r¤   ÚtextÚfigureÚget_constrained_layoutÚsubplots_adjustZdataLimÚx0Úy0ÚwidthÚheightZRSry   r'   )7rL   rv   rý   rþ   rÌ   rã   rä   r›   rÝ   rŽ  r-  r�  rå   r�   ræ   rò   r�  rè   r@   ré   rB   rŠ  r‰  rÏ   r´  rt   Z	info_helpru   Zpos_helpÚerrorrÿ   r²   r�  r«   r¬   r™   rµ   r¹   r³   r/  r±   Úcolr‚  rƒ  rz   rÃ  Zshow_idxrq   ÚpÚch_idZlimrÔ  rÕ  rÖ  r×  rD   r¶  rE   r�  �  s   

ÿþþ
ÿÿ ÿ



     ÿ



   ÿ  ÿ&
ÿ








&
 ÿ

r�  r»  c           !      C   s†  ddl m} | jdkrtdƒ‚t|| jƒ}t||ƒsDtdt|ƒ ƒ‚t| || j	d�}|dkrjt
 d¡ dS |  ¡ dd…|f }t| ||d	�\}}}}}}}|| }t|||
|ƒ}
|rÄt|||ƒ\}}| j| }tt|  ¡ ƒƒd
krò|d|› d�7 }|j|dd� t|||ƒ\}}t| ¡ |||||||
||||	||||d�d }|�rzt|||dddd�\}} |jjdd� | ||f¡ t|ƒ dS )zPlot single ica map to axes.r   )r  Nú_The ICA's measurement info is missing. Please fit the ICA or add the corresponding info object.z>axis has to be an instance of matplotlib Axes, got %s instead.)Úallow_ref_megrQ   z7Cannot produce topographies for MEG reference channels.rN   r    ú (ú)r  r  )rý   rþ   rä   r›   rÌ   rå   r�   rã   ræ   rò   rè   r@   ré   rB   r½   ÚAUú%3.2f)rÁ   rÎ   rÃ   ©Z	labelsize)Zmatplotlib.axesr  rA   r‘  r   rc   rj   Útyper   rÝ  r   Zget_componentsr|   r  r
   Ú
_ica_namesri   ry   Úget_channel_typesrË   r"   r  r  rÒ   r²   Útick_paramsÚ	set_ticksÚ_hide_frame)!Úicarz   rB   rä   rý   rþ   rÌ   rÉ   rÎ   rò   rå   r�   ræ   r›   rã   rÝ  rè   r@   ré   r  rL   r  rv   rw   rÝ   ru   rC   Z
topo_titleÚvmin_Úvmax_r³   rÑ   rÂ   rD   rD   rE   Ú_plot_ica_topomap8  sf    

ÿ
ÿ
            üüÿ
rì  r÷   ©r   c          2         sj  ddl m} ddlm} | jdkr*tdƒ‚ˆdkr8tƒ nˆ‰t ˆ¡‰dˆkrV|ˆd< |dkràt| |ƒ}| j	j
d }d}g }td	||ƒD ]R}t|t|| |ƒƒ}t| ||||||||	|
||||ˆˆˆˆˆ|d
�‰ | ˆ ¡ qˆ|S t| j|ƒ}t| |ƒ}t|t|ƒd�}t | j	dd…|f j| jd| j… ¡}t| ||d�\}}}} }}}!t||||!ƒ}t |¡}|dd…|f }tt|ƒdd�\‰ }"}#}#|	dk�r˜d}	ˆ  |	¡ tƒ }$t|||"ƒD �]*\}%}&}'|%| jk�rÖtdd�ntƒ }(| j|% })tt |  !¡ ƒƒdk�r|)d|› d�7 })|$ |'j"|)fddi|(—Ž¡ |�rBt#|&||  ¡ ƒ\}&}*t$|&||ƒ\}+},t%|& &¡ |f|+|,||'|d	 |||d||dœˆ—Žd	 }-|-j' (| j|% ¡ |�rÖt)|'|-|ddddd�\}.}/|.j*j+dd� |. ,|+|,f¡ t-|'ƒ �q´~t.ˆ d� ˆ j/dd d!� ˆ j0 1¡  | |$f‡ fd"d#„	}0ˆ j0 2d$|0¡ t3|||fƒ�r^| |f‡‡‡‡‡fd%d&„	}1ˆ j0 2d$|1¡ t4|
ƒ ˆ S )'uˆ  Project mixing matrix on interpolated sensor topography.

    Parameters
    ----------
    ica : instance of mne.preprocessing.ICA
        The ICA solution.
    %(picks_ica)s  If ``None``, all components are plotted in batches of 20.
    ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' | None
        The channel type to plot. For 'grad', the gradiometers are
        collected in pairs and the RMS for each pair is plotted.
        If None, then channels are chosen in the order given above.
    res : int
        The resolution of the topomap image (n pixels along each side).
    %(vmin_vmax_topomap)s
    cmap : matplotlib colormap | (colormap, bool) | 'interactive' | None
        Colormap to use. If tuple, the first value indicates the colormap to
        use and the second value is a boolean defining interactivity. In
        interactive mode the colors are adjustable by clicking and dragging the
        colorbar with left and right mouse button. Left mouse button moves the
        scale up and down and right mouse button adjusts the range. Hitting
        space bar resets the range. Up and down arrows can be used to change
        the colormap. If None, 'Reds' is used for all positive data,
        otherwise defaults to 'RdBu_r'. If 'interactive', translates to
        (None, True). Defaults to 'RdBu_r'.

        .. warning::  Interactive mode works smoothly only for a small amount
                      of topomaps.
    sensors : bool | str
        Add markers for sensor locations to the plot. Accepts matplotlib
        plot format string (e.g., 'r+' for red plusses). If True (default),
        circles  will be used.
    colorbar : bool
        Plot a colorbar.
    title : str | None
        Title to use.
    show : bool
        Show figure if True.
    %(outlines_topomap)s
    contours : int | array of float
        The number of contour lines to draw. If 0, no contours will be drawn.
        When an integer, matplotlib ticker locator is used to find suitable
        values for the contour thresholds (may sometimes be inaccurate, use
        array for accuracy). If an array, the values represent the levels for
        the contours. Defaults to 6.
    %(image_interp_topomap)s
    inst : Raw | Epochs | None
        To be able to see component properties after clicking on component
        topomap you need to pass relevant data - instances of Raw or Epochs
        (for example the data that ICA was trained on). This takes effect
        only when running matplotlib in interactive mode.
    plot_std : bool | float
        Whether to plot standard deviation in ERP/ERF and spectrum plots.
        Defaults to True, which plots one standard deviation above/below.
        If set to float allows to control how many standard deviations are
        plotted. For example 2.5 will plot 2.5 standard deviation above/below.
    topomap_args : dict | None
        Dictionary of arguments to ``plot_topomap``. If None, doesn't pass any
        additional arguments. Defaults to None.
    image_args : dict | None
        Dictionary of arguments to ``plot_epochs_image``. If None, doesn't pass
        any additional arguments. Defaults to None.
    psd_args : dict | None
        Dictionary of arguments to ``psd_multitaper``. If None, doesn't pass
        any additional arguments. Defaults to None.
    reject : 'auto' | dict | None
        Allows to specify rejection parameters used to drop epochs
        (or segments if continuous signal is passed as inst).
        If None, no rejection is applied. The default is 'auto',
        which applies the rejection parameters used when fitting
        the ICA object.
    %(sphere_topomap_auto)s
    %(verbose)s

    Returns
    -------
    fig : instance of matplotlib.figure.Figure | list of matplotlib.figure.Figure

        The figure object(s). Components are plotted on a grid with maximum
        dimensions of 5â¨‰4. If more than 20 components are plotted, a new figure
        will be created for each batch of 20, and a list of those figures
        will be returned.

    Notes
    -----
    When run in interactive mode, ``plot_ica_components`` allows to reject
    components by clicking on their title label. The state of each component
    is indicated by its label color (gray: rejected; black: retained). It is
    also possible to open component properties by clicking on the component
    topomap (this option is only available when the ``inst`` argument is
    supplied).
    r   )ÚBaseRaw)Ú
BaseEpochsNrÜ  r@   r    é   r   )rt   rB   rä   rþ   rÌ   rã   rÉ   rÎ   rò   rå   r�   ræ   rp   Úplot_stdÚtopomap_argsÚ
image_argsÚpsd_argsÚrejectr@   )Ún_axesrN   é   ©rø   zICA componentsÚgray©r¶   rÞ  rß  rÆ   r  F)rý   rþ   rä   r›   rÌ   rå   r�   ræ   rò   rã   rB   rà  r¼   r½   rá  )rÎ   rÍ   rÁ   rÃ   râ  rí   g)\�Âõ(ì?r<   )rÊ  Úbottomc                    s”   d }|D ]}|  | ¡d r|} q$q|d k	r�| ¡ }t| d¡d dd … ƒ}||jkrp|j |¡ | d¡ n|j |¡ | d¡ ˆ j 	¡  d S )Nr   r¹  éýÿÿÿrY   rù  )
ÚcontainsZget_textrE  ÚsplitrR   r©   Ú	set_colorr…   r®   r¯   )Úeventré  ÚtitlesZtitle_pressedrÎ   ÚlabelÚicrí   rD   rE   Úonclick_title  s    

z*plot_ica_components.<locals>.onclick_titleÚbutton_press_eventc              
      sV   | j d k	rR| j  ¡ }| d¡rRt| d¡d dd … ƒ}|j||dˆˆˆ ˆˆd� d S )NZICAr¹  r   rü  T)rt   rò   rñ  rò  ró  rô  rõ  )ÚinaxesZ	get_labelrf   rE  rþ  Zplot_properties)r   ré  rp   r  r  )ró  rñ  rô  rõ  rò  rD   rE   Úonclick_topo1  s    



 üz)plot_ica_components.<locals>.onclick_topo)5Úiorî  Úepochsrï  rA   r‘  r$  r?   r   Zmixing_matrix_rŠ   rk   r‰   Úplot_ica_componentsr…   r   r+   ri   rn   Údotr¥   Zpca_components_Zn_components_r|   r  rÚ   r#   Úsuptitlerˆ   r¤   rR   rä  ry   rå  rË   r
   r"   r  Úflattenr›   Ú	set_labelrÒ   r²   ræ  rç  rè  r!   rÓ  r®   r¯   Úmpl_connectrc   r'   )2ré  rt   rB   rä   rý   rþ   rÌ   rã   rÉ   rÎ   rò   rå   r�   ræ   rp   rñ  rò  ró  rô  rõ  r@   r   rî  rï  Ún_componentsrÚ  ÚfigsrY   rL   r  rv   rw   rÝ   rC   r›   ru   r  rq   Údata_r²   ÚkwargsZ
comp_titleZnames_rê  rë  r³   rÑ   rÂ   r  r  rD   )r¡   ró  rñ  rô  rõ  rò  rE   r
  i  sÒ    e


              ú
ÿÿ



 ÿ       üüü
  ÿ


r
  rP  ú%1.1ec           .      C   s  ddl m} t| |ƒ}t| ||d�\}}}}}}}t||||ƒ}|sHd}| j|dd…dd…f }|rxt|||dd�\}}t|| j||dd�}t	 
|¡rªt	 || ¡  j¡}d\} }!t	 t| j||ƒ¡d }"|dk	rÚ|"d } |dk	rî|"d	 d
 }!d\}#}$t	 t| j||ƒ¡d }"|dk	�r |"d }#|dk	�r6|"d	 d
 }$|dd…|#|$…| |!…f }t	jt	j|dd�d
d�dd…t	jf }t	 |¡dk �rŠdnd}%t|||	|%ƒ\}}	t|
|%d�}
|dk�rÊ|j||fd�d
 n|}|j}&t|ƒ d}'t|tt	jfƒ�st||	|ƒ\}'}|dk	�r| |¡ tƒ }(tt| ||| |!|#|$|
d |(d�
})t|tt	jfƒ�s^t||	|ƒ\}}t |dd…df |||	||
d t!|||d|)|||||d�\}*}|�rddl"m#}+ t$d|ƒd }t%||*|
||d�\},}-|'dk�rè|+j&dd�}'|'|,_'|, (¡  |,j)j*dd� t+|ƒ |&S )aÈ  Plot topographic maps of specific time-frequency intervals of TFR data.

    Parameters
    ----------
    tfr : AverageTFR
        The AverageTFR object.
    tmin : None | float
        The first time instant to display. If None the first time point
        available is used.
    tmax : None | float
        The last time instant to display. If None the last time point available
        is used.
    fmin : None | float
        The first frequency to display. If None the first frequency available
        is used.
    fmax : None | float
        The last frequency to display. If None the last frequency available is
        used.
    ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' | None
        The channel type to plot. For 'grad', the gradiometers are collected in
        pairs and the mean for each pair is plotted. If None, then channels are
        chosen in the order given above.
    baseline : tuple or list of length 2
        The time interval to apply rescaling / baseline correction. If None do
        not apply it. If baseline is (a, b) the interval is between "a (s)" and
        "b (s)". If a is None the beginning of the data is used and if b is
        None then b is set to the end of the interval. If baseline is equal to
        (None, None) the whole time interval is used.
    mode : 'mean' | 'ratio' | 'logratio' | 'percent' | 'zscore' | 'zlogratio' | None
        Perform baseline correction by

          - subtracting the mean baseline power ('mean')
          - dividing by the mean baseline power ('ratio')
          - dividing by the mean baseline power and taking the log ('logratio')
          - subtracting the mean baseline power followed by dividing by the
            mean baseline power ('percent')
          - subtracting the mean baseline power and dividing by the standard
            deviation of the baseline power ('zscore')
          - dividing by the mean baseline power, taking the log, and dividing
            by the standard deviation of the baseline power ('zlogratio')

        If None no baseline correction is applied.
    %(vmin_vmax_topomap)s
    cmap : matplotlib colormap | (colormap, bool) | 'interactive' | None
        Colormap to use. If tuple, the first value indicates the colormap to
        use and the second value is a boolean defining interactivity. In
        interactive mode the colors are adjustable by clicking and dragging the
        colorbar with left and right mouse button. Left mouse button moves the
        scale up and down and right mouse button adjusts the range. Hitting
        space bar resets the range. Up and down arrows can be used to change
        the colormap. If None (default), 'Reds' is used for all positive data,
        otherwise defaults to 'RdBu_r'. If 'interactive', translates to
        (None, True).
    sensors : bool | str
        Add markers for sensor locations to the plot. Accepts matplotlib plot
        format string (e.g., 'r+'). If True (default), circles will be used.
    colorbar : bool
        Plot a colorbar.
    unit : str | None
        The unit of the channel type used for colorbar labels.
    res : int
        The resolution of the topomap image (n pixels along each side).
    size : float
        Side length per topomap in inches (only applies when plotting multiple
        topomaps at a time).
    cbar_fmt : str
        String format for colorbar values.
    %(show_names_topomap)s
    title : str | None
        Plot title. If None (default), no title is displayed.
    axes : instance of Axes | None
        The axes to plot to. If None the axes is defined automatically.
    show : bool
        Show figure if True.
    %(outlines_topomap)s
    contours : int | array of float
        The number of contour lines to draw. If 0, no contours will be drawn.
        When an integer, matplotlib ticker locator is used to find suitable
        values for the contour thresholds (may sometimes be inaccurate, use
        array for accuracy). If an array, the values represent the levels for
        the contours. If colorbar=True, the ticks in colorbar correspond to the
        contour levels. Defaults to 6.
    %(sphere_topomap_auto)s

    Returns
    -------
    fig : matplotlib.figure.Figure
        The figure containing the topography.
    r   NrN   rP  ©ÚmethodTrÁ  râ   r^   r    r   r  F©rÿ   ©Zfigsize)	Útfrrv   rB   ÚitminÚitmaxÚifminÚifmaxrÌ   r¡   )rý   rþ   r›   rÌ   ræ   r�   rÝ   rŽ  rò   r�  rã   rä   rB   rå   r@   ©ÚtickerÚunitsÚmisc)rÎ   rÃ   r÷  ©Znbinsr  râ  ),rÇ   rÈ   r   r|   r  rL   r
   r   Útimesrn   ZiscomplexobjÚsqrtZconjr"  r�   r   ÚfreqsrP  rK  r‰   r"   r+   ÚsubplotsrÑ  rè  rc   rˆ   r  Ú_set_contour_locatorrË   r   Ú	_onselectr  r   r1  r  r0   rÒ   ÚMaxNLocatorÚlocatorZupdate_ticksr²   ræ  r'   ).r  ÚtminÚtmaxÚfminÚfmaxrB   ÚbaselineÚmoderý   rþ   rÌ   rã   rÉ   Úuniträ   rÀ   Úcbar_fmtrŽ  rÎ   r›   rò   rå   r�   r@   rÏ   rt   rv   rw   rÝ   ru   rC   rL   r  r  rz   r  r  rÿ   r¡   r*  Zfig_wrapperZselection_callbackr³   r  rÑ   rÂ   rD   rD   rE   Úplot_tfr_topomapB  s–    a
ÿ


&"


    þ       ú

r3  z%3.1fr`   c           ^         s�
  ddl m} ddlm}  ddlm}! ddlm}" tˆ|"dƒ t|t	dƒ ˆ 
¡ ‰tˆ|ƒ}t|ˆjƒ\}}#|d	krvd
nd}$t|dtfdƒ |dkr¢|d	krždnd}~td|ƒ}|d  |d 9  < |d  |d 9  < tˆ||d�\}%}&‰}'}}}(t||&||(ƒ}|dk	})t|tƒ�o|dk}*|*�r0|)�r0tdƒ‚| d¡�r@dn|}+td|ƒ|+ },td|	ƒ|+ }-|'}.|�snd}'td|dƒ |dk�r–ˆj�s–ˆ ¡  n|dk�r¨ˆ ¡  ˆj‰ ˆj ¡ � g ˆjd< W 5 Q R X ˆj|%dd �‰t||jƒ�rð|g}|)�rt|ƒt|ƒ nd}/t ˆ||/ƒ}t|ƒ}0d!dˆjd"   }1t!|ƒt!ˆjƒ|1 k�s`t"|ƒt"ˆjƒ|1 k �r†td#ˆjd d$›d%ˆjd& d$›d'�ƒ‚|0t|ƒ }2|*�r:d(d!g}3d}|2}|| }4|t!dd)d*|  ƒ t	|ƒd+  }5t#|4d, |5d, fd-�}6d.d/d0d1d2œ}7| ||fd3|3i|7—Ž}8g }t$|0ƒD ]}9| %| &|8d|9f ¡¡ �qnx|dk�rbt'|0|||||d4�\}6}}}nPd5\}}|d  (¡ }6t|ƒ|2k�r²|�rŽd6nd7}:t)d8|2› d9|:› d:t|ƒ› d'�ƒ‚|6 *¡ �s|j+d; d|2  };t!|dk�rÞd0nd<d.| ƒ}<|6j,|;d!|; dd!|< d2� ‡fd=d>„|D ƒ}=d?}>g }?|dk�rLt- .dg|0 ¡}ˆ t- /|%|=¡ ‰ �nºt0|ƒ�rht- .|g|0 ¡}n6t- .|¡j1dk�r”t2|>› d@t3|ƒ› d'�ƒ‚n
t- .|¡}t|ƒ|0k�rÆtdA|0› dBt|ƒ› dC�ƒ‚t- 4t|%ƒt|=ƒf¡}@t5t6|ˆj|= |=ƒƒD �]\}A\}B}C}Dt0|Bƒ�r|Bdk�s*t0|Bƒ�sd|Bdk	�rdt|ƒd!k�rH|>› dD|B› �}En|>› dD|B› dE|› �}Et|Eƒ‚|Bdk�rœˆ |% dd…|Df |@dd…|Af< |? %|Cg¡ nb|C|Bd  }F|C|Bd  }G|Fˆjk ˆj|Gk @ }Hˆ |% dd…|Hf  7d&¡|@dd…|Af< |? %ˆj|H ¡ �qò|@‰ ˆ |,9 ‰ ˆ�r2t8ˆ ||.ƒ\‰ }.|t9k�r2d‰|dk	�rš|j:t	ddF�}|dk�rŠ|t- /|%ddd… |=¡ |t- /|%d!dd… |=¡ B }In|t- /|%|=¡ }I‡ ‡‡‡fdGd>„t$|0ƒD ƒ}Jt- "|J¡‰t- !|J¡‰t;||0ˆdkdH�}t|t<t-j=fƒ�sþt>ˆˆ|ƒ\}#}t?ˆˆ||
|'||d ||||d||||dI�}Kg g  }L}Mt5t6||ƒƒD �]&\}A\}N}B|�oj|dk	�oj|A|d! k}O|O�rz|Ad! n|A}9t@ˆ dd…|Af |&f||9 |dk	�r²|Idd…|Af nddJœ|K—Ž\}P}Q}R|L %|P¡ |Qdk	�rä|M %|Q¡ |d7k�rB|Bdk�r||N|$  }SnT|?|A d }F|?|A d& }G||F|$  }T|T AdK¡d }T||G|$  }U|T› dL|U› �}S~T~U~F~G||9  B|S¡ �qB|*�	r>| %| &|8d!dd&…f ¡¡ |!|d& dMˆjd ˆjd& |d dNdO�}V|VjC D¡  ˆ�rÊt8ndPdQ„ }WtEtF|d ˆjˆj|&|,|W||$|KdR�
}X|V G|X¡ t- Hˆjtˆjƒ¡ IˆjjJ¡}Y|d& jK|YˆjdSdT� |V|d& _L|dk	�	rX|jM|dUdVdW� |�
r&|*�	r€| &|8dX ¡}ZtN|Z||ƒ n6|dk�	s”|dk�	rž|d& }Zn||d!  }ZtN|Z||ƒ |-dk	�	rÊ|Z B|-¡ |6jO|Ld& |Z|Z|dY�}[|Qdk	�	rô|[ P|¡ |[jQjRdZd[� |d! �
r&|LD ]}\tS|[|\ƒ|\jT_U�
q|dk�
rptVˆƒ t?ˆ|6ˆjd\ |%|L|M|&|=|
tWˆ|,|||R|d]�}]tXd|]ƒ tY|dd^� |)�
rŒ|6jZ [¡  |6S )_a„  Plot topographic maps of specific time points of evoked data.

    Parameters
    ----------
    evoked : Evoked
        The Evoked object.
    times : float | array of float | "auto" | "peaks" | "interactive"
        The time point(s) to plot. If "auto", the number of ``axes`` determines
        the amount of time point(s). If ``axes`` is also None, at most 10
        topographies will be shown with a regular time spacing between the
        first and last time instant. If "peaks", finds time points
        automatically by checking for local maxima in global field power. If
        "interactive", the time can be set interactively at run-time by using a
        slider.
    %(ch_type_evoked_topomap)s
    %(vmin_vmax_topomap)s
    %(cmap_topomap)s
    %(sensors_topomap)s
    %(colorbar_topomap)s
    %(scalings_topomap)s
    %(units_topomap)s
    %(res_topomap)s
    %(size_topomap)s
    %(cbar_fmt_topomap)s
    time_unit : str
        The units for the time axis, can be "ms" or "s" (default).

        .. versionadded:: 0.16
    time_format : str | None
        String format for topomap values. Defaults (None) to "%%01d ms" if
        ``time_unit='ms'``, "%%0.3f s" if ``time_unit='s'``, and
        "%%g" otherwise. Can be an empty string to omit the time label.
    %(proj_plot)s
    %(show)s
    %(show_names_topomap)s
    %(title_none)s
    %(mask_evoked_topomap)s
    %(mask_params_topomap)s
    %(outlines_topomap)s
    %(contours_topomap)s
    %(image_interp_topomap)s
    average : float | array-like of float, shape (n_times,) | None
        The time window (in seconds) around a given time point to be used for
        averaging. For example, 0.2 would translate into a time window that
        starts 0.1 s before and ends 0.1 s after the given time point. If the
        time window exceeds the duration of the data, it will be clipped.
        Different time windows (one per time point) can be provided by
        passing an ``array-like`` object (e.g., ``[0.1, 0.2, 0.3]``). If
        ``None`` (default), no averaging will take place.

        .. versionchanged:: 1.1
           Support for ``array-like`` input.
    %(axes_topomap)s
    %(extrapolate_topomap)s

        .. versionadded:: 0.18
    %(sphere_topomap_auto)s
    %(border_topomap)s
    nrows : int | 'auto'
        The number of rows of topographies to plot. Defaults to 1. If 'auto',
        obtains the number of rows depending on the amount of times to plot
        and the number of cols. Not valid when times == 'interactive'.

        .. versionadded:: 0.20
    ncols : int | 'auto'
        The number of columns of topographies to plot. If 'auto' (default),
        obtains the number of columns depending on the amount of times to plot
        and the number of rows. Not valid when times == 'interactive'.

        .. versionadded:: 0.20

    Returns
    -------
    fig : instance of matplotlib.figure.Figure
       The figure.

    Notes
    -----
    When existing ``axes`` are provided and ``colorbar=True``, note that the
    colorbar scale will only accurately reflect topomaps that are generated in
    the same call as the colorbar. Note also that the colorbar will not be
    resized automatically when ``axes`` are provided; use Matplotlib's
    :meth:`axes.set_position() <matplotlib.axes.Axes.set_position>` method or
    :doc:`gridspec <matplotlib:tutorials/intermediate/arranging_axes>`
    interface to adjust the colorbar size yourself.
    r   N)ÚGridSpec)ÚSliderr   )ÚEvokedr–   rÉ   r`   r  ç     @�@Útime_formatz%0.3f sz%01d msr�  Z
markersizerÀ  r¾  rN   Úinteractivez8User-provided axes not allowed when times='interactive'.r·  r:   Úscalingsr   r’   )TFr9  ÚreconstructTr;  rK   Frí  r    ÚsfreqzTimes should be between z0.3z and r^   r‹  r÷  çš™™™™™¹?r;  rA  r¤  r  çš™™™™™É?çš™™™™™é?r½   gÍÌÌÌÌÌì?)Úleftr¼   rû  rÊ  Úheight_ratios)rø   rù   rÎ   rÉ   rÀ   râ   z plus one for the colorbarÚ zYou must provide z axes (one for each timez), got zfigure.subplot.wspacerD  c              
      s2   g | ]*}t  tˆ j|d ˆ jd d�¡d d ‘qS )Nr<  )r+  r,  r<  r   )rn   r�   r   r#  rA   r¦  ©r–   rD   rE   r[   ¹  s   þÿÿÿz'plot_evoked_topomap.<locals>.<listcomp>z_"average" must be `None`, a positive number of seconds, or an array-like object of the previousz; got type: z+You requested to plot topographic maps for z time points, but provided zV periods for averaging. The number of time points and averaging periods must be equal.z; got z in rÁ  c                    s(   g | ] }t ˆ d d …|f ˆˆˆd�‘qS )Nr  )r"   r�   )rL   rw   rþ   rý   rD   rE   r[   ý  s   ÿ)rö  rÿ   )rý   rþ   rã   rä   rÝ   rŽ  rÌ   r�  rå   r�   ræ   rò   rè   r@   ré   rB   )r›   r-  r¹  u    â€“ ZTimez%1.2fs)Zvalfmtc                 S   s   | S rú   rD   rÂ  rD   rD   rE   Ú<lambda>.  ó    z%plot_evoked_topomap.<locals>.<lambda>)	r²   rL   r#  rv   ÚscalingÚfuncr8  Úscaling_timer  rY   rú  rÊ  zx-large)rÇ  rÀ   )r   r^   )r²   rÂ   rÃ   é   râ  r•   )r–   r¡   r•   rt   rœ   rš   rv   r—   rä   Zplot_update_proj_callbackrw   r˜   r›   r�   r™   rè   ©Úblock)\rÇ   rÈ   Zmatplotlib.gridspecr4  rË  r5  r–   r6  r   rq  r?   r   r,   r#  rk  r0   r|   r  rc   rj   rf   r   r’   r£   Z_reconstruct_projrL   rA   r¢   Z_pick_drop_channelsr  ri   rE  r(   r%  r‰   r&   rk   r…   Zsubplotr#   r  r‘  rÒ  r)  rÓ  rn   ro   Zix_r   rj  Ú	TypeErrorrã  rp  rd   r¤   rP  r
   rg   rT  r+   rˆ   r  r'  r$  r�  rþ  rË   Zvliner©   r   Ú_slider_changedZ
on_changedrI  rQ  rŠ   r3  Úsliderr  Ú_resize_cbarrÉ   rç  r²   ræ  r)   r›   rÊ   r$   r»   r%   r'   r®   r¯   )^r–   r#  rB   rý   rþ   rÌ   rã   rÉ   r:  r   rä   rÀ   r2  Ú	time_unitr8  r’   rò   rŽ  rÎ   r-  r�  rå   r�   ræ   Zaverager›   rè   r@   ré   rù   rø   rÏ   r4  r5  r6  ru   rH  rt   rv   rÝ   rC   Z
axes_givenr9  r5  rF  r1  rG   Zn_peaksZn_timesÚspaceZ	want_axesrA  rÖ  r×  r¡   Zg_kwargsÚgsZax_idxZcbar_errZside_marginZ
top_marginr—   Zavg_errZaveraged_timesr  Zaverage_idxZthis_averageZ	this_timeZthis_time_idxÚmsgZtmin_Ztmax_Z	time_maskr–  r  r  rœ   rš   ÚtimeZadjust_for_cbarr·   Úcnr™   Z
axes_titleZ	from_timeZto_timerN  rG  Zchanged_callbackÚtsrÂ   rÑ   r³   r°   rD   )rL   r–   rw   rþ   rý   rE   Úplot_evoked_topomapø  s    b

ÿ

ÿ&"
    þ 
ÿ
þ


ÿÿÿÿþþ
 &


ÿÿ

      û
ÿÿ
þ ÿþþ




 ÿ

    ü









           û

rW  c                 C   sP   |   ¡ }|dkr&ddd|  |  |_|jd|  |_d|_d|_|  |¡ dS )zResize colorbar.r    çffffffæ?r=  r>  N)Zget_positionrÔ  Úx1rÕ  Úy1Zset_position)rÂ   Z
n_fig_axesrÀ   ÚcposrD   rD   rE   rO  `  s    rO  c
                 C   s’   t  t  ||  ¡¡}
||dd…|
f ƒ ¡ | }| ¡  t||fd|i|	—Ž\}}t|dƒrt||j_t	|jj
jdƒ |dk	rŽ| || |  ¡ dS )z(Handle selection in interactive topomap.Nr›   rÊ   r   )rn   ÚargminÚabsr  Úclearr  ÚhasattrrÊ   ÚmappablerO  rÑ   r²   rË   )Úvalr²   rL   r#  rv   rF  rG  r8  rH  r  rz   r³   ru   rD   rD   rE   rM  k  s    
rM  ú%3.3fc                 C   s   t |ƒ |dkrt | ¡n|}|dkr0t | ¡n|}t ||g¡}tt|ƒƒdkp^t |dk¡}t||d�}|dk	r‚|j	|dd� t
| |||||d td|d||d�\}}|	rüt|||d	dd
|
d�\}}| ||f¡ |dk	rî|jj|dd� |jjdd� dS )zPlot topomap multi cbar.Nr    r   r  rÄ   r  F)
rý   rþ   r›   rÌ   ræ   r�   rå   rò   r@   rB   rD  z10%)rÁ   rÎ   rÀ   rÃ   é   râ  )rè  rn   r‰   r%  Úsignri   ry   rŽ   r+   rË   r  r   rÒ   rç  r²   Ú
set_ylabelræ  )rL   rv   r²   rÎ   r1  rý   rþ   rÌ   rå   rÉ   r2  r@   rB   Zsignsrÿ   r³   ru   rÑ   rÂ   rD   rD   rE   Ú_plot_topomap_multi_cbary  s4        ý
 ÿ
rf  Úlengthc           !      C   sÒ   t | |	ƒ}	tddƒ}tddƒ}||	 }||	 }t| |	|d�\}}}}}	}}t||||ƒ}t| |||||||||d�
\}} tj|dd�}||d 9 }|rªt||	|d	d
�\}}t|| ||||
||||||||||	d�S )aÞ  Plot the topomap of the power spectral density across epochs.

    Parameters
    ----------
    epochs : instance of Epochs
        The epochs object.
    %(bands_psd_topo)s
    tmin : float | None
        Start time to consider.
    tmax : float | None
        End time to consider.
    proj : bool
        Apply projection.
    bandwidth : float
        The bandwidth of the multi taper windowing function in Hz. The default
        value is a window half-bandwidth of 4 Hz.
    adaptive : bool
        Use adaptive weights to combine the tapered spectra into PSD
        (slow, use n_jobs >> 1 to speed up computation).
    low_bias : bool
        Only use tapers with more than 90%% spectral concentration within
        bandwidth.
    %(normalization)s
    ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' | None
        The channel type to plot. For 'grad', the gradiometers are collected in
        pairs and the mean for each pair is plotted. If None, then first
        available channel type from order given above is used. Defaults to
        None.
    %(cmap_psd_topo)s
    %(agg_fun_psd_topo)s
    %(dB_psd_topo)s
    %(n_jobs)s
    %(normalize_psd_topo)s
    %(cbar_fmt_psd_topo)s
    %(outlines_topomap)s
    %(axes_psd_topo)s
    show : bool
        Show figure if True.
    %(sphere_topomap_auto)s
    %(vlim_psd_topo_joint)s
    %(verbose)s

    Returns
    -------
    fig : instance of Figure
        Figure distributing one image per channel across sensor topography.
    r   Nr:  rN   )	r+  r,  Ú	bandwidthÚadaptiveÚlow_biasÚnormalizationrt   r’   Ún_jobsr   r  r   rP  r  )Úpsdsr%  rv   Úagg_funÚbandsrÌ   ÚdBÚ	normalizer2  rå   r›   rò   r@   rç   r1  rB   )	r   r0   r|   r  r/   rn   rP  r
   Úplot_psds_topomap)!r	  ro  r+  r,  r’   rh  ri  rj  rk  rB   rÌ   rn  rp  rl  rq  r2  rå   r›   rò   r@   rç   r   r   r:  r1  rF  rt   rv   rw   rÝ   rC   rm  r%  rD   rD   rE   Úplot_epochs_psd_topomap—  sN    8


ÿ   ü
            ürs  ú%0.3fc                    sˆ  ddl m} t|ƒ}|dkr(ˆr$dnd}|dkr@dddd	d
g}n8t ˆ¡d }t d|g¡|d  ‰‡‡fdd„|D ƒ}ˆ dkr�ˆrŠtjntj‰ ˆr¾ˆˆjddd� ‰t ˆjdd�d¡s¾t	‚t
|ƒ}|
dk	rät|
|ƒ |
d j}n,|jd|d| dfd�\}}
|dk�r|
g}
|dk�rr‡fdd„|D ƒ}‡ ‡fdd„|D ƒ}‡‡fdd„|D ƒ}t |¡ ¡ }t |¡ ¡ }n|\}}|dk�ršˆ�r”ˆ�s”dnd}n.d|k�r¬d| }|d7 }ˆ�rÈˆ�sÈ|d7 }t|
|ƒD ]”\}\}}}|ˆk ˆ|k @ }| ¡ dk�rtd |||f ƒ‚ˆ ˆdd…|f dd�}ˆ�rBˆ�sBd!t |¡ }t||||||||	d||||d"� �qÒt|d#� |j ¡  t|ƒ |S )$a©  Plot spatial maps of PSDs.

    Parameters
    ----------
    psds : np.ndarray of float, shape (n_channels, n_freqs)
        Power spectral densities
    freqs : np.ndarray of float, shape (n_freqs)
        Frequencies used to compute psds.
    pos : numpy.ndarray of float, shape (n_sensors, 2)
        The positions of the sensors.
    %(agg_fun_psd_topo)s
    %(bands_psd_topo)s
    %(cmap_psd_topo)s
    %(dB_psd_topo)s
    %(normalize_psd_topo)s
    %(cbar_fmt_psd_topo)s
    %(outlines_topomap)s
    %(axes_psd_topo)s
    show : bool
        Show figure if True.
    %(sphere_topomap)s
    %(vlim_psd_topo_joint)s
    unit : str | None
        Measurement unit to be displayed with the colorbar. If ``None``, no
        unit is displayed (only "power" or "dB" as appropriate).
    %(ch_type_topomap)s

    Returns
    -------
    fig : instance of matplotlib.figure.Figure
        Figure with a topomap subplot for each band.
    r   Nr÷   z%0.1frt  )r   r;  zDelta (0-4 Hz))r;  rc  zTheta (4-8 Hz))rc  r  zAlpha (8-12 Hz))r  é   zBeta (12-30 Hz))ru  é-   zGamma (30-45 Hz)r   c                    sJ   g | ]B}t |ƒd krBtˆ ˆt t ˆ|d  ¡¡  ƒ|d f n|‘qS )r   r   r    )ri   Útuplern   r\  r]  )rX   Zband)Ú	bin_edgesr%  rD   rE   r[     s    
ÿ$ÿz%plot_psds_topomap.<locals>.<listcomp>r^   TrB  r  r  r    r¤  r  rô   c                    s"   g | ]\}}}|ˆ k ˆ |k @ ‘qS rD   rD   )rX   r-  r.  ru   )r%  rD   rE   r[   3  s   ÿc                    s$   g | ]}ˆ ˆd d …|f dd�‘qS r=  rD   )rX   Z
_freq_mask)rn  rm  rD   rE   r[   5  s   ÿc                    s&   g | ]}ˆ rˆsd t  |¡ n|‘qS )rÄ   )rn   Úlog10)rX   Z_d)rp  rq  rD   rE   r[   7  s   ÿrp  Úpowerú/z(%s)u   Â²/Hzz (dB)z$No frequencies in band "%s" (%s, %s)rÄ   )
rÎ   rý   rþ   rÌ   rå   rÉ   r1  r2  r@   rB   rí   )rÇ   rÈ   r   rn   rL  ro   rN  rP  Zallcloser>   ri   r*   rÑ  r&  r‰   r%  r¤   r‘  ry  rf  r!   r®   r¯   r'   )rm  r%  rv   rn  ro  rÌ   rp  rq  r2  rå   r›   rò   r@   rç   r1  rB   rÏ   Zbin_spacingrö  r¡   Z_freq_masksZ_datasrý   rþ   r²   r-  r.  rÎ   Z	freq_maskrL   rD   )rn  rx  rp  r%  rq  rm  rE   rr  ë  sŒ    & þÿ



ÿÿÿ

ÿ     ý


rr  c                 C   sŽ  ddl m} |jt|jd ƒfd d�}| d¡}|jddddddd� |jg g d	d
� tdddddgdddddgfd�}t	||ƒ t
t| jƒ|ƒ}| j| }t | j¡| }	tt||	ƒƒD ]ª\}
\}}t |d |d d  |d |d d  f¡}|j||dddd� |r¼|d |d |d  |d |d |d  f\}}}}|j|||||g|||||gdd� q¼| d¡ t|dddd� t|ƒ |S )aÈ  Plot the sensor positions.

    Parameters
    ----------
    layout : None | Layout
        Layout instance specifying sensor positions.
    %(picks_nostr)s
    show_axes : bool
            Show layout axes if True. Defaults to False.
    show : bool
        Show figure if True. Defaults to True.

    Returns
    -------
    fig : instance of Figure
        Figure containing the sensor topography.

    Notes
    -----
    .. versionadded:: 0.12.0
    r   Nzfigure.figsizer   r  éo   r    )r@  rû  r¼   rÊ  ZwspaceZhspacer¢  )ZxticksÚyticksr£  )ré   rÀ  r;   rÄ  rÅ  )ZxyrÆ  rÇ  rÀ   rY   rú  Úoff)r¡   rÁ   Zw_padZh_pad)rÇ   rÈ   rÑ  r%  r)  Úadd_subplotrÓ  ry   r$  r6  r   ri   rÝ   rv   rn   ro   rd   r¤   Zannotater3  r  r!   r'   )rs   rt   Z	show_axesrò   rÏ   r¡   r²   rå   rv   rÝ   rq   rÚ  rÛ  Z
center_posrY  Zx2rZ  Úy2rD   rD   rE   Úplot_layoutZ  s2    
ÿ"

.
 ÿ4&
r�  c                    sÞ  ddl m} ddlm} | j}t| j|jƒ}t| j|jƒ}t| j|jƒ}t| j|jƒ}|dd…df |k |dd…df |k@ |dd…df |k @ |dd…df |k@ }dd„ |D ƒ}t	 
|¡d }|jD ]}t||ƒrÈ| |¡ qÈ|jj ¡  t|ƒdkrþdS ˆj}|dk�rTtˆj|dd	�‰ t	j||||…||…f dd
�}‡ ‡fdd„|D ƒ}nØ|dk�rÜtˆj|dd�}tƒ }|D ].}| ||d  ¡ | ||d d  ¡ �qxt	j||||…||…f dd
�}‡fdd„|D ƒ}nP|dk�r,tˆjdddd�‰ t	j||||…||…f dd
�}‡ ‡fdd„|D ƒ}t dt|ƒ ¡ t|
ƒdk�rX|
 tƒ ¡ | |
d j¡�sttƒ |
d< |
d  d¡}|dk�rštˆjƒd nt|tˆjƒd ƒ}|dk�rÆtˆj ƒd nt|tˆj ƒd ƒ}|dk�rèd}|dk�röd}ˆj| d ˆj| d ˆj | ˆj | f}dt|ƒ|f }| !|¡ | "d¡ | #d¡ |j$||dd|	d�}t|
d  %¡ ƒdk �rš|
d j&|d�|
d  %¡ d _'n|
d  %¡ d j'j(|d� |
d j ¡  | |
d j¡ t)dƒ dS )z=Handle drawing average tfr over channels called from topomap.r   N)ÚPathCollectionr    c                 S   s   g | ]}|rd nd‘qS )ÚrrY   rD   r  rD   rD   rE   r[   •  s     z_onselect.<locals>.<listcomp>r9   F)rP   rQ   r  c                    s   g | ]}ˆj ˆ |  ‘qS rD   rV   ©rX   r_   ©rt   r  rD   rE   r[   ¡  s     r:   )rs   r¸  r   c                    s   g | ]}ˆ j | ‘qS rD   rV   r„  )r  rD   rE   r[   ª  s     rO   T)rP   rO   rQ   c                    s   g | ]}ˆj ˆ |  ‘qS rD   rV   r„  r…  rD   rE   r[   ®  s     zAveraging TFR over channels r|  r7  zAverage over %d %s channels.z	Time (ms)zFrequency (Hz)r÷   r¡  )r�  r£  rW  rÌ   )r`  )*rÇ   rÈ   Zmatplotlib.collectionsr‚  r  r‰   Zxdatar%  Zydatarn   r�   r¨   rc   rÿ  rÑ  r®   r¯   ri   rL   r   rA   rP  r	   rˆ   r…   r   rk  r&   Zfignum_existsÚnumberr  r#  r%  rË   Z
set_xlabelre  rª  Zget_axesrÉ   rÑ   Zon_mappable_changedr'   )ZeclickZereleaser  rv   rB   r  r  r  r  rÌ   r¡   rs   rÏ   r‚  r²   r—  r˜  r™  rš  rt  rŸ   Z
collectionrL   rH   ZgradsZidxsrz   r�  rÎ   ZimgrD   r…  rE   r(  ‰  sŽ    &ÿÿ


 
ÿ 
 
ÿÿ

 ÿ


ÿ r(  c                 C   s    t |ƒ |r|  ¡ stdƒ‚dS )zxPrepare the topomap axis and check positions.

    Hides axis frame and check that position information is present.
    zENo position information found, cannot compute geometries for topomap.N)rè  rŽ   r‘  )rv   r²   Zcheck_nonzerorD   rD   rE   rÎ  Ï  s    rÎ  c                 C   s.   |   ¡  | j g ¡ | j g ¡ |  d¡ dS )zHide axis frame for topomaps.FN)Z
get_yticksZxaxisrç  ZyaxisZset_frame_on)r²   rD   rD   rE   rè  Ú  s    rè  c                 C   s(   t d| dƒ | dkr$|tkr dnd} | S )Nrè   )r8  r9  rà   r÷   r÷   r9  rà   )r   r   )rè   rB   rD   rD   rE   rÍ  â  s    rÍ  c
           $      C   sÆ  t  d¡ |d }
tƒ }|d r¬|d }tt|
ƒƒD ]}|j||
| ddd� q4t|
ddƒ\}}|jt 	t 
||d	¡d
¡|dd
g d� |j|d dd�|d< | |d ¡ |rÌddlm} ||
dg ƒ\}
}t |
¡dkrÞdnd}|rêdnd}t|
dd|ƒ\}}t||d d|d ƒ}t| ƒ t|d d|||dd�\}}}}t|||| ƒ}tƒ |d< |d D ],}|d  | |
dd…|f ¡||ƒ¡ �q^|d d }t |d ¡}t |d ¡}tj
||ddd�dd… }| ||||||||dœ¡ | j||||d d!|d"d#�}| jddd$� | jj||d%� | j||||ddd&�} | |¡ | jd'd(d)| jd*d+d,�}!|!|d-< | |¡ | |!¡ | j D ]}"|" |¡ �q|t!| |ƒ}#| ||#d.œ¡ t"| jd/� t#|ƒt#| j ƒ S )0zInitialize animated topomap.zInitializing animation...rL   Ú	butterflyÚ	all_timesrY   r    ©r¶   rº   Nr÷  r^   r   )r}  r”  rƒ  rú  Úline)r
   r:   TFrº  r»  rv   rà   rC   rß   )rv   rä   ræ   rè   rå   ré   ÚZisÚframesrI  rF  )rý   rþ   r«   r¬   rµ   r�  rÌ   Ú	cont_limsr¡  r¢  r¼  ©rÌ   rý   rþ   rW  r£  r�  r½  )ÚenableZtight)rÂ   ©ZlevelsrŸ   r    çš™™™™™á?rÈ  rB  rÄ  r¼   )r°  ÚvaZharÐ  )r*  rå   rí   )$r   rA   rˆ   rk   ri   r3  r"   ry   rn   Úaroundr  Úaxvliner…   Zmne.channels.layoutr
   r‰   r  rè  rž  r³  r¦   ÚnanminZnanmaxÚupdaterª  Z	autoscalerÑ  rÉ   rª   r­   rÐ  r²  r¨   r6  r!   rw  )$r²   Úax_lineÚax_cbarr°   rw   r@   rB   ræ   rè   r   rL   r2  rˆ  rz   rý   rþ   r
   ru   rÿ   rÌ   rå   r�  r«   r¬   r™   r¹   Úframerµ   Zzi_minZzi_maxr�  r³   r±   rÐ  rÙ  r4  rD   rD   rE   Ú
_init_animé  s‚    

ÿÿ    þ
*  ÿ þ
ÿ



rš  c              
   C   s  |d r|d } |d |  }|d dkr@d|d |  d f }nd	|d |  f }|d
 rd|d }nT|  ¡  |jddd|jd�}|d  ¡ D ]*\}\}}	d|kr¢qŒ|j||	dddd� qŒt|ƒ | |¡ |d }
|d }|d }|d }|d |  }|d }|d }|d }|j|||
|dd|d d!�}|d" }tj	d#d$��& t 
d%¡ |j||||ddd&�}W 5 Q R X | |¡ |jD ]}| |¡ �qx||g}|d' �rê|d( }|d) }| ¡  | ¡ }|j|| d*d+�|d)< | |¡ | |d) ¡ | |d< t|ƒt|jƒ S ),zUpdate animated topomap.Úpauser™  rŒ  rP  Úmsz%6.0f msr#  r7  z%6.3f sÚblitrÐ  gÍÌÌÌÌÌÜ?r  rB  )r°  rå   r-  rY   r    Fr.  rý   rþ   r«   r¬   r‹  r�  rÌ   r*  r¡  r¢  r¼  rŽ  r�  Trê   rì   r�  r‡  rˆ  rŠ  rƒ  rú  )ZclarÐ  r²  r2  r3  rè  Zset_textrª  rï   rð   rñ   rª   r­   r¨   r©   Zget_ylimr”  Zset_ylimr…   rw  )r™  r²   r—  r°   r—   rÎ   rÐ  rY   r_   rÅ   rý   rþ   r«   r¬   rµ   r�  rÌ   r*  r³   r�  r±   rÙ  r2  rˆ  rŠ  r•  rD   rD   rE   Ú_animate,	  sl    

 þ
     ÿ



rž  c                 C   s   |d  |d< dS )z/Pause or continue the animation on mouse click.r›  NrD   ©r   r°   rD   rD   rE   Ú_pause_animf	  s    r   c                 C   sb   | j dkr*d|d< t|d d dƒ|d< n4| j dkr^d|d< t|d d t|d ƒd ƒ|d< d	S )
z%Handle key presses for the animation.r@  Tr›  r™  r    r   r¼   rŒ  N)r5  r%  r‰   ri   rŸ  rD   rD   rE   Ú
_key_pressk	  s    

r¡  c          #         s²  ddl m}m} |dkr*tˆ jƒd d }|dkr:tdƒ‚t|ˆ jƒ\}}|dkrlt 	ˆ jd ˆ jd d¡}t 
|¡}|jdkrŽtd	|j ƒ‚t|ƒˆ jd ks²t|ƒˆ jd k rºtd
ƒ‚‡ fdd„|D ƒ}tˆ ||d�\}}}}}}}ˆ j|dd…f }|tdƒ| 9 }|jdd�}d}|d d }|d t|ƒ }|j|d||d�}|�rd|j||df|d�}nd}t|tƒ�r’t 	dtˆ jƒd |¡ t¡}|j|d|f|d�}|jtdƒ| dd� t|
|ƒ}
t||ˆ jd|||d|||d�}tt||||||||	|
|d�}tt|||d�}tt|d�}|j  !d|¡ tt"|d�} |j  !d| ¡ |dk�r`ˆ jd d  }d!| }!|j#|||t|ƒ|!|d"�}"|"|_$t%|dd#� d$|k�rª|d$  &¡  ||"fS )%zeMake animation of evoked data as topomap timeseries.

    See mne.evoked.Evoked.animate_topomap.
    r   )rÈ   Ú	animationN)r9   r:   rO   r5   r6   r8   r7   z…Channel type not supported. Supported channel types include 'mag', 'grad', 'eeg'. 'hbo', 'hbr', 'fnirs_cw_amplitude', and 'fnirs_od'.r^   rÄ   r    z#times must be 1D, got %d dimensionsz0All times must be inside the evoked time series.c                    s    g | ]}t  ˆ j| ¡ ¡ ‘qS rD   )rn   r]  r#  r\  )rX   rT  rC  rD   rE   r[   �	  s     z&_topomap_animation.<locals>.<listcomp>rN   r:  )rá   r÷  r  )rc  r  r¿  )ÚrowspanÚcolspan)r¤  )r£  r   r  F)rL   rv   rˆ  r™  rŒ  r‡  r�  r›  r#  rP  rC   )
r²   r˜  r—  r°   rw   r@   rB   ræ   rè   r   )r²   r—  r°   )r°   r  Zkey_press_eventr<  g      $@iè  )Ú	init_funcrŒ  Úintervalr�  rJ  rŠ  )'r1  rÈ   r¢  r   rA   rj   r,   r#  rn   r  ro   rj  r%  r‰   r|   rL   r0   rÑ  rq  Zsubplot2gridrc   r   ri   rT  rE  rË   rÍ  r$  r   rš  rž  r   r®   r  r¡  ZFuncAnimationZmne_animationr'   r©   )#r–   rB   r#  Z
frame_rater‡  r�  rò   rP  r@   ræ   rè   r   rÏ   r¢  ru   rŒ  rt   rv   rw   rC   rL   r¡   rŠ   r¤  r£  r²   r—  r˜  r°   r¥  Zanimate_funcZ
pause_funcZkey_press_funcr¦  ZanimrD   rC  rE   Ú_topomap_animationu	  s†    

$ÿ
    ý
   ü

 þ
r§  c                 C   sF   d}t |tƒr>|dkr>ddlm} |j|d d�}| | |¡}||fS )zSet correct contour levels.Nr   r  r    r"  )rc   r   r1  r  r)  Ztick_values)rý   rþ   r�   r*  r  rD   rD   rE   r'  À	  s    r'  c                     sÌ  |
sd}ˆdk	r"|dˆ 7 }nd}t ttˆƒƒƒ}d‰t|ƒˆkr|t|ƒ}‡ ‡‡‡‡‡‡‡‡‡	‡
fdd„td|ˆƒD ƒ}|S t |¡rŒ|g}tˆˆ |d	�\}}}}}}}t||ˆ|ƒ‰t ˆ¡‰ˆdd…|f ‰tt|ƒd
d�\}}}}| 	|¡ t
|ˆ|ˆ
ˆƒD ]œ\}}}}}|
�r8d |ˆj| ¡}|j|dd� n| d |¡¡ |�r^t|ˆ g ƒ\}}t|ddƒ\}}t| ¡ |||d|ˆˆˆdtd�d  t|ƒ �qt|d� |jdd� |j ¡  tˆ	ƒ |S )z*Customize ica.plot_components for corrmap.zDetected componentsNz	 of type zSupplied templaterð  c                    sL   g | ]D}t ˆ||ˆ … ˆ
||ˆ … ˆ||ˆ … ˆ ˆˆˆ	ˆˆˆd �
‘qS ))rå   rÌ   r�   )Ú_plot_corrmaprW   ©rB   rÌ   r�   rL   ré  rt  r  rå   rÚ  rò   ÚsubjsrD   rE   r[   Û	  s   ý      þz!_plot_corrmap.<locals>.<listcomp>r   rN   r÷  rø  zSubj. {}, {}r  r  zSubj. {}rß   F)	rý   rþ   rä   r›   rÌ   rå   r�   rò   ræ   rí   r?  rÉ  )rˆ   rk   ri   rn   Zisscalarr|   r  rÚ   r#   r  r¤   rÃ   rä  rË   r
   r"   r  r  r   rè  r!   rÓ  r®   r¯   r'   ) rL   rª  rt  rB   ré  r  rò   rå   rÌ   r�   Útemplater@   rÎ   rt   r  r  r  rv   rw   rÝ   ru   rC   r¡   r›   rq   r  r²   Úsubjectrz   Úttlrê  rë  rD   r©  rE   r¨  Ì	  s^    
ý
ÿ

    ýý

r¨  c           	   	   C   sb   ddl m}m} t ¡ �< tjdtd� || |ƒ}|||ƒ}| |j|j	¡\}}W 5 Q R X ||fS )zTake gradients of z on a mesh.r   )ÚCubicTriInterpolatorÚTriangulationrì   )Úcategory)
Zmatplotlib.trir®  r¯  rï   rð   ÚfilterwarningsÚDeprecationWarningZgradientr_   rÅ   )	r_   rÅ   Úzr®  r¯  r[  Ztcir'  r(  rD   rD   rE   Ú_trigradient
  s    


r´  gLÎaã§�ô=c           #      C   sþ  ddl m} ddlm} t||ƒ}t|ƒ}t|ƒdkr@tdƒ‚n|d d }|dkr`td| ƒ‚|d	krv|d
krv|}n>t|ƒ}t|ƒdkr”tdƒ‚n|d d }|d
kr´td| ƒ‚||k	rüt|t	|dd�ƒ}t|t	|dd�ƒ}|||ddd�}t
 || ¡} t|d
|d�\}}}}}}}t||||ƒ}|	d	k�r>| ¡ \}}	n|	j}t| ||	||||||
||||||d||||d� t|jƒ\}}t||| ƒ\}} | j}!|j }"|	j|||!|"|dddd� |	jj ¡  tjdd�� t d¡ t|d� W 5 Q R X t|ƒ |S )uy
  Plot arrow map.

    Compute arrowmaps, based upon the Hosaka-Cohen transformation
    :footcite:`CohenHosaka1976`, these arrows represents an estimation of the
    current flow underneath the MEG sensors. They are a poor man's MNE.

    Since planar gradiometers takes gradients along latitude and longitude,
    they need to be projected to the flattened manifold span by magnetometer
    or radial gradiometers before taking the gradients in the 2D Cartesian
    coordinate system for visualization on the 2D topoplot. You can use the
    ``info_from`` and ``info_to`` parameters to interpolate from
    gradiometer data to magnetometer data.

    Parameters
    ----------
    data : array, shape (n_channels,)
        The data values to plot.
    info_from : instance of Info
        The measurement info from data to interpolate from.
    info_to : instance of Info | None
        The measurement info to interpolate to. If None, it is assumed
        to be the same as info_from.
    scale : float, default 3e-10
        To scale the arrows.
    %(vmin_vmax_topomap)s
    %(cmap_topomap_simple)s
    sensors : bool | str
        Add markers for sensor locations to the plot. Accepts matplotlib plot
        format string (e.g., 'r+' for red plusses). If True (default), circles
        will be used.
    res : int
        The resolution of the topomap image (n pixels along each side).
    axes : instance of Axes | None
        The axes to plot to. If None, a new figure will be created.
    names : list | None
        List of channel names. If None, channel names are not plotted.
    %(show_names_topomap)s
        If ``True``, a list of names must be provided (see ``names`` keyword).
    %(mask_topomap)s
    %(mask_params_topomap)s
    %(outlines_topomap)s
    contours : int | array of float
        The number of contour lines to draw. If 0, no contours will be drawn.
        If an array, the values represent the levels for the contours. The
        values are in ÂµV for EEG, fT for magnetometers and fT/m for
        gradiometers. Defaults to 6.
    %(image_interp_topomap)s
    show : bool
        Show figure if True.
    onselect : callable | None
        Handle for a function that is called when the user selects a set of
        channels by rectangle selection (matplotlib ``RectangleSelector``). If
        None interactive selection is disabled. Defaults to None.
    %(extrapolate_topomap)s

        .. versionadded:: 0.18
    %(sphere_topomap_auto)s

    Returns
    -------
    fig : matplotlib.figure.Figure
        The Figure of the plot.

    Notes
    -----
    .. versionadded:: 0.17

    References
    ----------
    .. footbibliography::
    r   )rÈ   r   )Ú_map_meg_or_eeg_channelsr    z]Multiple channel types are not supported.All channels must either be of type 'grad' or 'mag'.)r9   r:   zNChannel type '%s' not supported. Supported channel types are 'mag' and 'grad'.Nr9   z)Multiple channel types are not supported.z,only 'mag' channel type is supported. Got %sT)rP   )r<   r<   g{®Gáz¤?Zaccurate)rW  r0  rN   F)r›   rý   rþ   rÌ   rã   rä   rÝ   rŽ  r-  r�  rå   r�   ræ   rò   r�  rè   r@   rB   rY   )r˜   r¶   rº   r0  rê   rì   rí   )r1  rÈ   Úforwardrµ  r   r   ri   rj   r   r   rn   r  r|   r  r&  rÑ  r  rw  r¥   r´  rL   Zquiverr®   Z	draw_idlerï   rð   rñ   r!   r'   )#rL   Z	info_fromZinfo_tor˜   rý   rþ   rÌ   rã   rä   r›   rÝ   rŽ  r-  r�  rå   r�   ræ   rò   r�  rè   r@   rÏ   rµ  rB   Úmappingru   rv   rC   r¡   r_   rÅ   r'  r(  ZdxxZdyyrD   rD   rE   Úplot_arrowmap
  sŠ    O

ÿ
ÿ   ÿÿ   ÿ
         û
r¸  c                 C   s
  ddl m} |dkrtƒ }n| ¡ }t| dd�}| dd¡ | dd¡ | d	t| |ƒj¡ | d
d¡ | dd¡ d|kr„|d ntdƒ}d|krª| 	¡ \}}	|	|d< nd}d|krÀ| 
d¡nd}
|jdd… |j|jfk�rtd|jd |j|jf› d|j› �ƒ‚| ¡ }t |j¡}t|jd ƒD ]}|| j| || |< �q(tjtj|dd�dd�}t|t| |ƒf|Ž\}}|dk�r†|jn|}|D ]F\}}t| ||g|d�}|jj|d |d g|d |d gdd� �qŽ|dk	�rì|j |¡ |
�r| |¡}| d¡ |S )a†  Topoplot electrode distance matrix with bridged electrodes connected.

    Parameters
    ----------
    %(info_not_none)s
    bridged_idx : list of tuple
        The indices of channels marked as bridged with each bridged
        pair stored as a tuple.
        Can be generated via
        :func:`mne.preprocessing.compute_bridged_electrodes`.
    ed_matrix : array of float, shape (n_channels, n_channels)
        The electrical distance matrix for each pair of EEG electrodes.
        Can be generated via
        :func:`mne.preprocessing.compute_bridged_electrodes`.
    title : str
        A title to add to the plot.
    topomap_args : dict | None
        Arguments to pass to :func:`mne.viz.plot_topomap`.

    Returns
    -------
    fig : instance of matplotlib.figure.Figure
        The topoplot figure handle.

    See Also
    --------
    mne.preprocessing.compute_bridged_electrodes
    r   NT)rO   ræ   rh  rÌ   Zsummer_rrÝ   rŽ  r�   Fr@   r›   rÉ   r    z	Expected z shaped `ed_matrix`, got r  rN   r¿  )r    r   )r   r    )r    r    rƒ  rú  z Electrical Distance ($\mu$$V^2$))rÇ   rÈ   r$  r?   r   Ú
setdefaultr   rG   r   r&  rÌ  rŠ   rÀ   r‘  rn   Ztril_indicesrk   r¥   rO  r•  r  rÑ  r   r›   r3  rË   rÉ   r  )rA   Zbridged_idxZ	ed_matrixrÎ   rò  rÏ   rt   r@   r¡   r²   rÉ   Ztril_idxZepo_idxZ
elec_distsr³   rU  Zidx0r\  rv   rÂ   rD   rD   rE   Úplot_bridged_electrodesŸ
  sX    ÿ
ÿÿ ÿ ÿ



rº  Ú2dc              
      sô  ddl m} ddl}ddlm} ddlm} t| tdƒ tˆ t	j
|jfdƒ tˆ |jƒ}	|rl|dkrltd	ƒ‚t| j|d
d�}
t| |
ƒ} t| jƒ}ˆ jd |krºtdˆ jd › d|› d�ƒ‚|dkrú| ddi¡� || |dd�}W 5 Q R X t|jd ƒ nB|dk�r<| ddi¡� || ddd�}W 5 Q R X |jd  d¡ |jd  |jj¡}|d  d¡ |dk�rÊ|d  d¡ |d  ¡ }|d  d¡ ‡ fdd„tˆ jd ƒD ƒ}dd„ |D ƒ}|d  |¡ n.|d j }t	j!|d j"|d j"|d gdd�}|jd }t#ƒ }ˆ jd }t|ƒD ]¢}ˆ ||d d…f }|	�rF| $¡ d }nt	 %|¡d }t|ƒdk�rf�q||d 7 }|D ]B}|||gdd…f }t&||gƒ}|j'|j(ddd œŽd ||< �qv�q|�rðt#ƒ }t)t*||||ˆ ||d!�}|j+ ,d"|¡ |S )#a�  Plot channel adjacency.

    Parameters
    ----------
    info : instance of Info
        Info object with channel locations.
    adjacency : array
        Array of channels x channels shape. Defines which channels are adjacent
        to each other. Note that if you edit adjacencies
        (via ``edit=True``), this array will be modified in place.
    ch_names : list of str
        Names of successive channels in the ``adjacency`` matrix.
    kind : str
        How to plot the adjacency. Can be either ``'3d'`` or ``'2d'``.
    edit : bool
        Whether to allow interactive editing of the adjacency matrix via
        clicking respective channel pairs. Once clicked, the channel is
        "activated" and turns green. Clicking on another channel adds or
        removes adjacency relation between the activated and newly clicked
        channel (depending on whether the channels are already adjacent or
        not); the newly clicked channel now becomes activated. Clicking on
        an activated channel deactivates it. Editing is currently only
        supported for ``kind='2d'``.

    Returns
    -------
    fig : Figure
        The :class:`~matplotlib.figure.Figure` instance where the channel
        adjacency is plotted.

    See Also
    --------
    mne.channels.get_builtin_ch_adjacencies
    mne.channels.read_ch_adjacency
    mne.channels.find_ch_adjacency

    Notes
    -----
    .. versionadded:: 1.1
    r   )ÚsparseNr    )Úplot_sensorsrA   Ú	adjacencyZ3dz-Editing a 3d adjacency plot is not supported.T)Úorderedz]``adjacency`` must have the same number of rows as the number of channels in ``info``. Found z  channels for ``adjacency`` and z for ``inst``.ZtoolbarÚNoneF)re   rò   r»  Ztopomapr¢  r<   rX  rÄ   c                    s   g | ]}t  ˆ | ¡d  ‘qS ©r    ©rn   rN  r�   ©r¾  rD   rE   r[   B  s   ÿz%plot_ch_adjacency.<locals>.<listcomp>c                 S   s   g | ]}t |d ƒd ‘qS )r;   ç      @)r%  r„  rD   rD   rE   r[   D  s     r   r  )r‘  r‘  r‘  g      è?r‰  )r›   Ú	positionsÚhighlightedÚ	line_dictr¾  Ú	node_sizeÚpath_collectionZ
pick_event)-Zscipyr¼  r1  rÇ   rÈ   rB  r½  r   r3   rn   r  Z
csr_matrixrc   rj   r   rG   r   ri   rŠ   Z
rc_contextr-   r›   r  Zfindobjr¨   r‚  Zset_linewidthsZ	set_alphaZget_offsetsZ
set_zorderrk   Ú	set_sizesZ
_offsets3drU  rL   r$  Znonzeror�   rw  r3  r¥   r   Ú_onpick_ch_adjacencyr®   r  )rA   r¾  rG   re   Zeditr¼  ZmplrÏ   r½  Z
has_sparseÚselZ
n_channelsr¡   rÉ  rv   Ún_connectionsrÈ  r²   ÚlinesZch_idxÚrowZch_neighboursZngb_idxZthis_posZch_pairrÆ  Zthis_onpickrD   rÃ  rE   Úplot_ch_adjacencyì
  s‚    )




ÿ
$


ÿÿ  ýrÐ  c                    sÊ  | j d }||kr4||  ¡  ||= |jj ¡  �n’t|ƒdkrŒt|| d dƒ}	|j||dd…f jd|	ddœŽ}
|
||< |jj ¡  �n:t	| 
¡ ƒd }||g}| ¡  t|ƒ}|| 
¡ kräd‰||  ¡  ||= tˆ |d	ƒ n>d
‰||dd…f }|j|jddiŽd }|||< tˆ |dƒ ||  ¡  ||= ‡ ‡fdd„|D ƒ}t||ƒD ]\}}t|dƒd ||< �qR|d  |¡ t|| d dƒ}	|j||dd…f jd|	ddœŽ}
|
||< |jj ¡  dS )z*Handle interactivity in plot_ch_adjacency.r   r   rŸ  Nz	tab:greené   )r¶   r`   Zzorderr^   Fr    r¶   Tc                    s"   g | ]}t  ˆ | ¡d  ˆ ‘qS rÁ  rÂ  )rX   rz   ©r¾  Zn_conn_changerD   rE   r[   ¦  s   ÿz(_onpick_ch_adjacency.<locals>.<listcomp>r;   rÄ  )Úindr©   rÑ  r®   r¯   ri   r%  r�  r¥   rˆ   ÚkeysÚsortrw  Ú_set_adjacencyr3  r¤   rÊ  )r   r›   rÅ  rÆ  rÇ  r¾  rÈ  rÉ  Znode_indrÀ   Údotsr5  Ú
both_nodesZselected_posrŠ  rÍ  rz   Zn_connrD   rÒ  rE   rË  p  s\    
  þÿ  þrË  c              	   C   s:   ddl }|jdd�� || ||ddd… f< W 5 Q R X dS )zDSet adjacency for given node pair, caching errors for sparse arrays.r   NTrê   r^   )rï   rð   )r¾  rØ  Úvaluerï   rD   rD   rE   rÖ  µ  s    rÖ  )N)r¼   r½   NNr¾   )T)NNNNNNrP  NNNTTNrß   r   r  FNNTrà   rá   N)r    )
NNNNNrà   Frb  NrO   )NNNFNFTrg  NNNFNFr÷   rà   NTNrâ   N)NNNTFrt  rà   NTNrâ   NrO   )NFT)N)T)FN)NN)r»  F)NNNNNNN)sr}  r?   r‹   Ú	functoolsr   Únumbersr   rï   Únumpyrn   r/  r   Zchannels.channelsr   Zchannels.layoutr   r   r	   r
   Údefaultsr   r   r   Zio.pickr   r   r   r   r   r   r   r   Úutilsr   r   r   r   r   r   r   r   r   r   r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   Ztime_frequencyr/   r0   Z
transformsr1   r2   Zio.meas_infor3   r4   rg   rF   r|   rh   r»   rÒ   rÞ   ró   rî   r  r6  r`  r	  ra  r„  r‡  r  rž  r¥  r®  r³  r�  rì  r
  r3  rW  rO  rM  rf  rs  rr  r�  r(  rÎ  rè  rÍ  rš  rž  r   r¡  r§  r'  r¨  r´  r¸  rº  rÐ  rË  rÖ  rD   rD   rD   rE   Ú<module>   sZ  (0@
K3+    ÿ
      ú.      ú
b1{N	
          úi&            û
 ,         ú
1         øø Y                                 ú 6                  ö  i
            ý
                                  ùS                      ün/ ÿ
F

B:þK   ÿ
7          ú   ÿL
        þ
E