U
    f»{j“  ã                   @   st  d dl Z d dlmZ d dlmZ d dlmZ d dlZ	ddl
mZmZ ddlmZmZmZ ddlmZ ddlmZ dd	lmZmZmZmZmZmZmZ d
dlmZ G dd„ deƒZ dd„ Z!dd„ Z"d<dd„Z#ed=dd„ƒZ$ed>dd„ƒZ%ed?dd„ƒZ&edd„ ƒZ'd@d!d"„Z(edAd#d$„ƒZ)ed%d&„ ƒZ*d'd(„ Z+edBd)d*„ƒZ,d+d,„ Z-d-d.„ Z.dCd0d1„Z/dDd2d3„Z0d4d5„ Z1dEd:d;„Z2dS )Fé    N)Údefaultdict)Úcombinationsé   )Ú_pol_to_cartÚ_cart_to_sph)Ú
pick_typesÚ_picks_to_idxÚ_FNIRS_CH_TYPES_SPLIT)ÚFIFF)ÚInfo)Ú_clean_namesÚwarnÚ_check_ch_locsÚfill_docÚ_check_optionÚ_check_sphereÚloggeré   )Ú_get_ch_infoc                   @   s6   e Zd ZdZdd„ Zdd„ Zdd„ Zeddd„ƒZdS )ÚLayoutaA  Sensor layouts.

    Layouts are typically loaded from a file using
    :func:`~mne.channels.read_layout`. Only use this class directly if you're
    constructing a new layout.

    Parameters
    ----------
    box : tuple of length 4
        The box dimension (x_min, x_max, y_min, y_max).
    pos : array, shape=(n_channels, 4)
        The unit-normalized positions of the channels in 2d
        (x, y, width, height).
    names : list
        The channel names.
    ids : list
        The channel ids.
    kind : str
        The type of Layout (e.g. 'Vectorview-all').
    c                 C   s"   || _ || _|| _|| _|| _d S )N)ÚboxÚposÚnamesÚidsÚkind)Úselfr   r   r   r   r   © r   úR/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/channels/layout.pyÚ__init__2   s
    zLayout.__init__c           	   
   C   sÞ   | j dd…df }| j dd…df }| j dd…df }| j dd…df }| d¡r^d| j }n| d¡rnd	}ntd
ƒ‚t|jd ƒD ]8}|d| j| || || || || | j| f 7 }q„t|dƒ}| 	|¡ | 
¡  dS )zÂSave Layout to disk.

        Parameters
        ----------
        fname : str
            The file name (e.g. 'my_layout.lout').

        See Also
        --------
        read_layout
        Nr   r   r   é   ú.loutz%8.2f %8.2f %8.2f %8.2f
ú.layÚ ú5Unknown layout type. Should be of type .lout or .lay.z %03d %8.2f %8.2f %8.2f %8.2f %s
Úw)r   Úendswithr   Ú
ValueErrorÚrangeÚshaper   r   ÚopenÚwriteÚclose)	r   ÚfnameÚxÚyÚwidthÚheightZout_strÚiiÚfr   r   r   Úsave9   s(    

  ÿÿ

zLayout.savec                 C   s   d| j d | jdd… ¡f S )z!Return the string representation.z <Layout | %s - Channels: %s ...>ú, Nr   )r   Újoinr   )r   r   r   r   Ú__repr__Z   s    ÿzLayout.__repr__NFTc                 C   s   ddl m} || |||d�S )aÂ  Plot the sensor positions.

        Parameters
        ----------
        %(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 matplotlib.figure.Figure
            Figure containing the sensor topography.

        Notes
        -----
        .. versionadded:: 0.12.0
        r   )Úplot_layout)ÚpicksÚ	show_axesÚshow)Zviz.topomapr7   )r   r8   r9   r:   r7   r   r   r   Úplot_   s    zLayout.plot)NFT)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r3   r6   r   r;   r   r   r   r   r      s   !r   c              	   C   sØ   t | ƒ�´}| ¡ }ttt| ¡ ƒƒ}g g g   }}}|D ]~}| ¡ }t|ƒdkrp|\}	}
}}}}}|d | }n|\}	}
}}}}| tj	|
|||gtj
d�¡ | |¡ | t|	ƒ¡ q8W 5 Q R X t 	|¡}||||fS )úAux function.é   ú ©Zdtype)r)   ÚreadlineÚtupleÚmapÚfloatÚsplitÚlenÚappendÚnpÚarrayÚfloat64Úint)r,   r2   Zbox_liner   r   r   r   ÚlineÚsplitsÚcidr-   r.   ÚdxÚdyÚchkindÚnbÚnamer   r   r   Ú
_read_loutx   s    


rW   c              	   C   sÂ   t | ƒ�ž}d}g g g   }}}|D ]~}| ¡ }t|ƒdkrZ|\}}	}
}}}}|d | }n|\}}	}
}}}| tj|	|
||gtjd�¡ | |¡ | t|ƒ¡ q"W 5 Q R X t |¡}||||fS )r@   NrA   rB   rC   )r)   rH   rI   rJ   rK   rL   rM   rN   )r,   r2   r   r   r   r   rO   rP   rQ   r-   r.   rR   rS   rT   rU   rV   r   r   r   Ú	_read_layŽ   s    


rX   Tc           	      C   sæ  |dkrt  t  t¡dd¡}|  d¡sFt  t  || d ¡¡rF| d7 } n(|  d¡snt  t  || d ¡¡rn| d7 } |  d¡r¢t  || ¡}| dd… } t|ƒ\}}}}nF|  d¡ràt  || ¡}| dd… } t|ƒ\}}}}|  d¡ ntdƒ‚|�rÔ|dd…d	f  t	 
|dd…d	f ¡8  < |dd…d
f  t	 
|dd…d
f ¡8  < tt	 |dd…d	f ¡t	 |dd…d
f ¡ƒ|d  }|| }|dd…dd…f  d7  < |dd…dd…f  d9  < |dd…dd…f  d9  < t|||| |d�S )a  Read layout from a file.

    Parameters
    ----------
    kind : str
        The name of the .lout file (e.g. kind='Vectorview-all' for
        'Vectorview-all.lout').

    path : str | None
        The path of the folder containing the Layout file. Defaults to the
        mne/channels/data/layouts folder inside your mne-python installation.

    scale : bool
        Apply useful scaling for out the box plotting using layout.pos.
        Defaults to True.

    Returns
    -------
    layout : instance of Layout
        The layout.

    See Also
    --------
    Layout.save

    Notes
    -----
    Valid ``kind`` arguments are:

    .. table::
       :widths: auto

       +----------------------+
       | Kind                 |
       +======================+
       | biosemi              |
       +----------------------+
       | CTF151               |
       +----------------------+
       | CTF275               |
       +----------------------+
       | CTF-275              |
       +----------------------+
       | EEG1005              |
       +----------------------+
       | EGI256               |
       +----------------------+
       | GeodesicHeadWeb-130  |
       +----------------------+
       | GeodesicHeadWeb-280  |
       +----------------------+
       | KIT-125              |
       +----------------------+
       | KIT-157              |
       +----------------------+
       | KIT-160              |
       +----------------------+
       | KIT-AD               |
       +----------------------+
       | KIT-AS-2008          |
       +----------------------+
       | KIT-UMD-3            |
       +----------------------+
       | magnesWH3600         |
       +----------------------+
       | Neuromag_122         |
       +----------------------+
       | Vectorview-all       |
       +----------------------+
       | Vectorview-grad      |
       +----------------------+
       | Vectorview-grad_norm |
       +----------------------+
       | Vectorview-mag       |
       +----------------------+
    NÚdataZlayoutsr    r!   éûÿÿÿéüÿÿÿr#   r   r   )r   r   r   g¸…ëQ¸ž?g'�JÎË"î?g®Gázî?©r   r   r   r   r   )Úopr5   ÚdirnameÚ__file__r%   ÚexistsrW   rX   r&   rK   ÚminÚmaxr   )	r   ÚpathÚscaler,   r   r   r   r   Úscalingr   r   r   Úread_layout£   s2    M 
 

**6rf   ç      à?ÚbadsFc                    sÒ  d|  krdksn t dƒ‚|dk	rDd|  kr:dksDn t dƒ‚|dk	rjd|  kr`dksjn t dƒ‚tdd	d|d
�}|rŒ|jd	dd� tˆ f|Ž}tˆ |ƒ}‡ fdd„|D ƒ}	t tj|dd� tj|dd�¡ ¡ d }
||
 }|dksø|dk�rt	|||dd�\}}|d| 9 }tdd|  dd|  ƒ}||9 }||9 }||9 }|d7 }|j
d }tj|dd…df d|  |dd…df d|  |t |¡ |t |¡ f }d}dt |¡ }t|||	d|d�}|S )a¿  Create .lout file from EEG electrode digitization.

    Parameters
    ----------
    %(info_not_none)s
    radius : float
        Viewport radius as a fraction of main figure height. Defaults to 0.5.
    width : float | None
        Width of sensor axes as a fraction of main figure height. By default,
        this will be the maximum width possible without axes overlapping.
    height : float | None
        Height of sensor axes as a fraction of main figure height. By default,
        this will be the maximum height possible without axes overlapping.
    exclude : list of str | str
        List of channels to exclude. If empty do not exclude any.
        If 'bads', exclude channels in info['bads'] (default).
    csd : bool
        Whether the channels contain current-source-density-transformed data.

    Returns
    -------
    layout : Layout
        The generated Layout.

    See Also
    --------
    make_grid_layout, generate_2d_layout
    r   rg   z1The radius parameter should be between 0 and 0.5.Nç      ð?z.The width parameter should be between 0 and 1.z/The height parameter should be between 0 and 1.FT)ÚmegÚeegÚref_megÚexclude)Úcsdrk   c                    s   g | ]}ˆ d  | d ‘qS ©ÚchsÚch_namer   ©Ú.0Úi©Úinfor   r   Ú
<listcomp>;  s     z#make_eeg_layout.<locals>.<listcomp>©Zaxisr   çš™™™™™¹?©Úpaddingr   ©r   r   r   r   ZEEGr\   )r&   ÚdictÚupdater   Ú_find_topomap_coordsrK   Úmaximumra   rb   Ú	_box_sizer(   Úc_ÚonesÚaranger   )rv   Zradiusr/   r0   rm   rn   Zpick_kwargsr8   Zloc2dr   rd   re   Z
n_channelsr   r   r   Úlayoutr   ru   r   Úmake_eeg_layout  s@    
*
ýr†   c                    sª  t ˆ |dƒ}‡ fdd„|D ƒ}|s*tdƒ‚ttt|ƒƒƒ}t|ƒ}|dkrŒt |¡ }}|d rvt|d ƒt|ƒ }}|| |k r¢|d7 }ntt |t	|ƒ ¡ƒ}t 
t dd|¡t dd|¡¡\}}| ¡ d|… | ¡ d|…  }}ttj||f d	d
�\}	}
d\}}dd|	 |  }dd|
 |  }|| }|| }|	|9 }	|
|9 }
|d7 }|d7 }tj|d|	  |d|
  |	t |¡ |
t |¡ f }d}t|||d|d�}|S )a‘  Generate .lout file for custom data, i.e., ICA sources.

    Parameters
    ----------
    %(info_not_none)s
    %(picks_base)s all good misc channels.
    n_col : int | None
        Number of columns to generate. If None, a square grid will be produced.

    Returns
    -------
    layout : Layout
        The generated layout.

    See Also
    --------
    make_eeg_layout, generate_2d_layout
    Úmiscc                    s   g | ]}ˆ d  | d ‘qS ro   r   )rs   Úkru   r   r   rw   v  s     z$make_grid_layout.<locals>.<listcomp>zNo misc data channels found.Nr   g      à¿rg   ry   rz   )ç{®Gáz„?r‰   ri   r|   z	grid-miscr\   )r   r&   Úlistr'   rI   rK   ÚsqrtrN   ÚceilrG   ZmeshgridZlinspaceZravelr�   r‚   rƒ   r   )rv   r8   Zn_colr   r   ÚsizeZn_rowr-   r.   r/   r0   Zborder_xZborder_yZ	x_scalingZ	y_scalingr   r   r…   r   ru   r   Úmake_grid_layout`  sD    
ÿ" ÿrŽ   c                    sd  t d|ddddddgƒ tˆƒ\}}}}}}}	}
}}}}}|o@|}|oJ| }|oT| }|dkrj|
sjtdƒ‚|dkr~|s~td	ƒ‚d}|rŽ|dks¢t||gƒr¨|dkr¨d
}nÜ|s¸|r¾|dkr¾d}nÆ|sÎ|rì|dkrìˆd d  d¡ræd}nd}n˜|röd}nŽ|�r|dk�s|�r:|dk�r:tˆttfƒ�s.tdƒ‚tˆˆ d�S |�rX|dk�rXtˆˆ dd�S |�rdd}n |�rpd}n|	dk�r„t	ˆ|	ƒ}|dk�rÎt
ˆdddd�}‡fdd„|D ƒ}tˆ|dd �}t||d!dd"�S t|ƒ‰|�sìtˆjdd#�ˆ_|�rtˆjdd$�ˆ_ˆ d%k�rˆd% ‰ ‡ fd&d„tˆjƒD ƒ}‡fd'd„|D ƒˆ_ˆj| ˆ_‡fd(d„|D ƒˆ_ˆS ))aÉ  Choose a layout based on the channels in the info 'chs' field.

    Parameters
    ----------
    %(info_not_none)s
    ch_type : {'mag', 'grad', 'meg', 'eeg'} | None
        The channel type for selecting single channel layouts.
        Defaults to None. Note, this argument will only be considered for
        VectorView type layout. Use ``'meg'`` to force using the full layout
        in situations where the info does only contain one sensor type.
    exclude : list of str | str
        List of channels to exclude. If empty do not exclude any.
        If 'bads', exclude channels in info['bads'] (default).

    Returns
    -------
    layout : Layout instance | None
        None if layout not found.
    Úch_typeNÚmagÚgradrj   rk   rn   z0No MEG channels present. Cannot find MEG layout.z0No EEG channels present. Cannot find EEG layout.zVectorview-allzVectorview-magÚch_namesr   ÚXzVectorview-grad_normzVectorview-gradZNeuromag_122)Nrk   zGCannot make EEG layout, no measurement info was passed to `find_layout`©rm   )Nrn   T)rm   rn   ZmagnesWH3600zCTF-275rY   r   F)rm   Zwith_ref_megc                    s   g | ]}ˆ d  | ‘qS ©r’   r   )rs   Úpickru   r   r   rw   ë  s     zfind_layout.<locals>.<listcomp>)r8   Úignore_overlapZcustom)r’   rV   Ú	normalize)Zremove_whitespace)Zbefore_dashrh   c                    s   g | ]\}}|ˆ kr|‘qS r   r   )rs   r1   rV   r”   r   r   rw   ù  s      c                    s   g | ]}ˆ j | ‘qS r   )r   ©rs   r1   ©r…   r   r   rw   ú  s     c                    s   g | ]}ˆ j | ‘qS r   )r   r™   rš   r   r   rw   ü  s     )r   r   ÚRuntimeErrorÚanyr%   Ú
isinstancer}   r   r†   Ú_find_kit_layoutr   r   Úgenerate_2d_layoutrf   r   r   Ú	enumerater   r   )rv   r�   rm   Z
has_vv_magÚhas_vv_gradZ	is_old_vvZ
has_4D_magZctf_other_typesZhas_CTF_gradZn_kit_gradsZhas_any_megZhas_eeg_coilsZhas_eeg_coils_and_megZhas_eeg_coils_onlyÚhas_neuromag_122_gradZhas_csd_coilsZ
has_vv_megZhas_vv_only_magZhas_vv_only_gradZlayout_namer8   r’   ÚxyÚidxr   )rm   rv   r…   r   Úfind_layout§  sŒ    ÿý     


ÿÿÿÿ


ÿ
r¥   c                    s˜   | d dk	r&ddl m} | | d ¡S |dkr2dS |dkr>dS |d	krJd
S d‰ ‡ fdd„| d D ƒ}t |¡rrdS t t |¡¡rŒtdƒ‚ntdƒ‚dS )a  Determine the KIT layout.

    Parameters
    ----------
    %(info_not_none)s
    n_grads : int
        Number of KIT-gradiometers in the info.

    Returns
    -------
    kit_layout : str | None
        String naming the detected KIT layout or ``None`` if layout is missing.
    Zkit_system_idNr   )Ú
KIT_LAYOUTé    zKIT-160é}   zKIT-125é�   zKIT-AD)&zMEG  13zMEG  14zMEG  15zMEG  16zMEG  25zMEG  26zMEG  27zMEG  28zMEG  29zMEG  30zMEG  31zMEG  32zMEG  57zMEG  60zMEG  61zMEG  62zMEG  63zMEG  64zMEG  73zMEG  90zMEG  93zMEG  95zMEG  96zMEG 105zMEG 112zMEG 120zMEG 121zMEG 122zMEG 123zMEG 124zMEG 125zMEG 126zMEG 142zMEG 144zMEG 153zMEG 154zMEG 155zMEG 156c                    s(   g | ] }|d  ˆ kr|d d dk ‘qS )rq   Úlocr   r   ©rs   Úch©Ztest_chsr   r   rw   $  s      z$_find_kit_layout.<locals>.<listcomp>rp   zKIT-157zzGuessing sensor layout for legacy UMD files is not implemented. Please convert your files using MNE-Python 0.13 or higher.z+KIT system could not be determined for data)Zio.kit.constantsr¦   ÚgetrK   ÚallÚinvertÚNotImplementedErrorr›   )rv   Zn_gradsr¦   r-   r   r­   r   rž     s     

rž   ç        c                    sf  ddl m} dd„ ‰dd„ ‰t | ¡} tt| dƒƒ‰ ˆdkr˜ˆdkr˜t| ƒd	krZd
‰d
‰n>ˆ t || ƒ¡ \}}ˆ||ƒˆ||ƒ }}||kr”|‰n|‰ˆdkrî|| ˆƒ}	‡ ‡fdd„t|	ƒD ƒ}
t|
ƒdkrÔd
‰nt 	‡fdd„|
D ƒ¡‰nXˆdk�rF|| ˆƒ}‡ ‡fdd„t|ƒD ƒ}
t|
ƒdk�r.d
‰nt 	‡fdd„|
D ƒ¡‰ˆd	| 9 ‰ˆd	| 9 ‰ˆˆfS )aT  Given a series of points, calculate an appropriate box size.

    Parameters
    ----------
    points : array, shape (n_points, 2)
        The centers of the axes as a list of (x, y) coordinate pairs. Normally
        these are points in the range [0, 1] centered at 0.5.
    width : float | None
        An optional box width to enforce. When set, only the box height will be
        calculated by the function.
    height : float | None
        An optional box height to enforce. When set, only the box width will be
        calculated by the function.
    padding : float
        Portion of the box to reserve for padding. The value can range between
        0.0 (boxes will touch, default) to 1.0 (boxes consist of only padding).

    Returns
    -------
    width : float
        Width of the box
    height : float
        Height of the box
    r   )Úpdistc                 S   s   t  | d |d  ¡S )Nr   ©rK   Úabs©ÚaÚbr   r   r   ÚxdiffK  s    z_box_size.<locals>.xdiffc                 S   s   t  | d |d  ¡S )Nr   r´   r¶   r   r   r   ÚydiffN  s    z_box_size.<locals>.ydiffr   Nr   ri   c                    s    g | ]\}}|ˆk rˆ | ‘qS r   r   ©rs   rt   Úd)Úall_combinationsr/   r   r   rw   h  s    ÿz_box_size.<locals>.<listcomp>c                    s   g | ]}ˆ |Ž ‘qS r   r   ©rs   Úc)rº   r   r   rw   q  s     c                    s    g | ]\}}|ˆk rˆ | ‘qS r   r   r»   )r½   r0   r   r   rw   v  s    ÿc                    s   g | ]}ˆ |Ž ‘qS r   r   r¾   )r¹   r   r   rw     s     )
Úscipy.spatial.distancer³   rK   ÚasarrayrŠ   r   rI   Zargminr    ra   )Zpointsr/   r0   r{   r³   r·   r¸   r$   ÚhZhdistÚ
candidatesZvdistr   )r½   r0   r/   r¹   rº   r   r�   0  s:    



r�   c                    s`   t ˆ |dddd�}ˆdk	rJ‡ fdd„|D ƒ}‡fdd„|D ƒ}t |¡}ntˆ ||||d	�}|S )
a[  Guess the E/MEG layout and return appropriate topomap coordinates.

    Parameters
    ----------
    %(info_not_none)s
    picks : str | list | slice | None
        None will choose all channels.
    layout : None | instance of Layout
        Enforce using a specific layout. With None, a new map is generated
        and a layout is chosen based on the channels in the picks
        parameter.
    sphere : array-like | str
        Definition of the head sphere.

    Returns
    -------
    coords : array, shape = (n_chs, 2)
        2 dimensional coordinates for each sensor for a topomap plot.
    r¯   r   F©rm   Zallow_emptyNc                    s   g | ]}ˆ d  | ‘qS ©rp   r   rr   ru   r   r   rw   ¡  s     z(_find_topomap_coords.<locals>.<listcomp>c                    s"   g | ]}ˆ j ˆ j |d  ¡ ‘qS ©rq   )r   r   Úindexr«   rš   r   r   rw   ¢  s     )r—   Ú	to_sphereÚsphere)r   rK   rÁ   Ú_auto_topomap_coords)rv   r8   r…   r—   rÈ   rÉ   rp   r   r   )rv   r…   r   r   ˆ  s       þr   c                    sV  ddl m}m} t|ˆƒ}t d|› �¡ tˆ|dddd�}‡fdd	„|D ƒ‰ t d
d	„ ˆ D ƒ¡}t	ˆ|d��sTt
 d¡ ˆ D ]}|d tjkr~tdƒ‚q~dd	„ ˆd D ƒ}	ˆd dksÈtˆd ƒdkrÐtdƒ‚t dd	„ ˆd D ƒ¡}t|ƒdk�rtdtj ƒ‚t|ƒt|	ƒk�r.tdt|ƒt|	ƒf ƒ‚tt|	|ƒƒ‰t ‡fdd	„ˆ D ƒ¡}d|t |¡ < ||ƒ}
t|ƒdk�rÌt |
¡dk �rÌ|�sÌ‡ fdd	„||
dk ƒjdd� ¡ d D ƒ}tdd |¡ ƒ‚|�rF||dd… 8 }t|ƒ}t|dd…dd…f dd…ddd …f ƒ}||dd…dgf tjd!  9 }||dd"… 7 }ntt|ƒƒ}|S )#a¡  Make a 2 dimensional sensor map from sensor positions in an info dict.

    The default is to use the electrode locations. The fallback option is to
    attempt using digitization points of kind FIFFV_POINT_EEG. This only works
    with EEG and requires an equal number of digitization points and sensors.

    Parameters
    ----------
    %(info_not_none)s
    picks : list | str | slice | None
        None will pick all channels.
    ignore_overlap : bool
        Whether to ignore overlapping positions in the layout. If False and
        positions overlap, an error is thrown.
    to_sphere : bool
        If True, the radial distance of spherical coordinates is ignored, in
        effect fitting the xyz-coordinates to a sphere.
    sphere : array-like | str
        The head sphere definition.

    Returns
    -------
    locs : array, shape = (n_sensors, 2)
        An array of positions of the 2 dimensional map.
    r   )r³   Ú
squareformzGenerating coords using: r¯   r   FrÄ   c                    s   g | ]}ˆ d  | ‘qS rÅ   r   rr   ru   r   r   rw   Ì  s     z(_auto_topomap_coords.<locals>.<listcomp>c                 S   s   g | ]}|d  dd… ‘qS )rª   Nr   r   r«   r   r   r   rw   Ï  s     )rv   r8   a  Did not find any electrode locations (in the info object), will attempt to use digitization points instead. However, if digitization points do not correspond to the EEG electrodes, this will lead to bad results. Please verify that the sensor locations in the plot are accurate.r   zLCannot determine location of MEG/EOG/ECG channels using digitization points.c                 S   s"   g | ]}|d  t jkr|d ‘qS )r   rq   )r
   ÚFIFFV_EEG_CHr«   r   r   r   rw   á  s    ÿrp   ÚdigNzNo digitization points found.c                 S   s"   g | ]}|d  t jkr|d ‘qS )r   Úr)r
   ÚFIFFV_POINT_EEG)rs   Úpointr   r   r   rw   è  s    ÿzNDid not find any digitization points of kind FIFFV_POINT_EEG (%d) in the info.zTNumber of EEG digitization points (%d) doesn't match the number of EEG channels (%d)c                    s   g | ]}ˆ |d   ‘qS rÆ   r   r«   )Úeeg_ch_locsr   r   rw   û  s     r²   r   g»½×Ùß|Û=c                    s   g | ]}ˆ | d  ‘qS rÆ   r   )rs   Zelec_irÅ   r   r   rw     s   ÿrx   zaThe following electrodes have overlapping positions, which causes problems during visualization:
r4   r   éÿÿÿÿç       @r   )rÀ   r³   rË   r   r   Údebugr   rK   rL   r   ÚloggingÚwarningr
   rÌ   r&   rI   r›   rÏ   r}   ÚzipÚisfinitera   rœ   Znonzeror5   r   r   Úpi)rv   r8   r—   rÈ   rÉ   r³   rË   Zlocs3dr¬   Zeeg_ch_namesÚdistZproblematic_electrodesZcart_coordsÚoutr   )rp   rÑ   rv   r   rÊ   ¬  sT    

	
þþ	$
þþ* rÊ   c                 C   sÌ   t  | ¡j\}}t  t  || d || d  ¡¡}|| }|| }|dt  || ¡ 7 }|dt  || ¡ 7 }|d d }|d d }t  t  |d |d  ¡dd¡}t  |¡}t  |¡}t  	|||g¡S )aY  Transform xy-coordinates to sphere.

    Parameters
    ----------
    pos : array-like, shape (n_channels, 2)
        xy-oordinates to transform.
    eegs : list of int
        Indices of EEG channels that are included when calculating the sphere.

    Returns
    -------
    coords : array, shape (n_channels, 3)
        xyz-coordinates.
    r   rg   rÓ   ri   r²   )
rK   rL   ÚTrb   r‹   ÚmeanZclipZarccosÚsinZcolumn_stack)r   ZeegsZxsZysZsqsÚrsZalphasZzsr   r   r   Ú_topo_to_sphere  s    $ 

rà   c                    sL  t tƒ}t| dd|d�}t| ƒ�^}}}}	}|D ]~}
| d |
 }|d }|rz| d¡rz| d¡rz|dd	… }||  |¡ |	r0| d¡r0t|d
d… ƒd d }||  |¡ q0dd„ | ¡ D ƒ}t	|ƒdkrê|rÜt
dƒ‚ntdƒ tƒ S t|g ƒ}| d ‰ ‡ fdd„|D ƒ}|�rDt	|ƒdd	f}t| ||ƒ |¡jdd�}||fS |S dS )ap  Find the picks for pairing grad channels.

    Parameters
    ----------
    %(info_not_none)s
    layout : Layout | None
        The layout if available. Defaults to None.
    topomap_coords : bool
        Return the coordinates for a topomap plot along with the picks. If
        False, only picks are returned. Defaults to True.
    exclude : list of str | str
        List of channels to exclude. If empty, do not exclude any.
        If 'bads', exclude channels in info['bads']. Defaults to 'bads'.
    raise_error : bool
        Whether to raise an error when no pairs are found. If False, raises a
        warning.

    Returns
    -------
    picks : array of int
        Picks for the grad channels, ordered in pairs.
    coords : array, shape = (n_grad_channels, 3)
        Coordinates for a topomap plot (optional, only returned if
        topomap_coords == True).
    r‘   F)rj   rl   rm   rp   rq   ÚMEG©Ú2Ú3r[   rÒ   éýÿÿÿNr   r   c                 S   s   g | ]}t |ƒd kr|‘qS ©r   ©rI   ©rs   Úpr   r   r   rw   h  s      z&_pair_grad_sensors.<locals>.<listcomp>r   zNo 'grad' channel pairs found.r’   c                    s   g | ]}ˆ   |d  ¡‘qS rÆ   )rÇ   r¾   r•   r   r   rw   s  s     rx   )r   rŠ   r   r   Ú
startswithr%   rJ   rN   ÚvaluesrI   r&   r   Úsumr   ÚreshaperÝ   )rv   r…   Ztopomap_coordsrm   Zraise_errorÚpairsZ
grad_picksÚ_r¡   r¢   rt   r¬   rV   ÚkeyÚgrad_chsr8   r(   Zcoordsr   r•   r   Ú_pair_grad_sensors;  s>    


ÿÿrò   c                 C   sh   t tƒ}t| ƒD ]6\}}| d¡r| d¡r|dd… }||  |¡ qdd„ | ¡ D ƒ}t|g ƒ}|S )a  Find the indices for pairing grad channels in a Vectorview system.

    Parameters
    ----------
    ch_names : list of str
        A list of channel names.

    Returns
    -------
    indexes : list of int
        Indices of the grad channels, ordered in pairs.
    rá   râ   r[   rÒ   c                 S   s   g | ]}t |ƒd kr|‘qS ræ   rç   rè   r   r   r   rw   ”  s      z:_pair_grad_sensors_ch_names_vectorview.<locals>.<listcomp>)r   rŠ   r    rê   r%   rJ   rë   rì   ©r’   rî   rt   rV   rð   rñ   r   r   r   Ú&_pair_grad_sensors_ch_names_vectorview€  s    


rô   c                 C   sj   t tƒ}t| ƒD ]8\}}| d¡rt|dd… ƒd d }||  |¡ qdd„ | ¡ D ƒ}t|g ƒ}|S )a  Find the indices for pairing grad channels in a Neuromag 122 system.

    Parameters
    ----------
    ch_names : list of str
        A list of channel names.

    Returns
    -------
    indexes : list of int
        Indices of the grad channels, ordered in pairs.
    rá   rå   Nr   r   c                 S   s   g | ]}t |ƒd kr|‘qS ræ   rç   rè   r   r   r   rw   ¯  s      z;_pair_grad_sensors_ch_names_neuromag122.<locals>.<listcomp>)r   rŠ   r    rê   rN   rJ   rë   rì   ró   r   r   r   Ú'_pair_grad_sensors_ch_names_neuromag122œ  s    

rõ   Úrmsc                 C   s6   |dkrt | |ƒ} n|tks t‚t| |ƒ\} }| |fS )aã  Merge data from channel pairs.

    Parameters
    ----------
    data : array, shape = (n_channels, ..., n_times)
        Data for channels, ordered in pairs.
    ch_type : str
        Channel type.
    names : list
        List of channel names.
    method : str
        Can be 'rms' or 'mean'.

    Returns
    -------
    data : array, shape = (n_channels / 2, ..., n_times)
        The root mean square or mean for each pair.
    names : list
        List of channel names.
    r‘   )Ú_merge_grad_datar	   ÚAssertionErrorÚ_merge_nirs_data)rY   r�   r   Úmethodr   r   r   Ú_merge_ch_dataµ  s
    rû   c                 C   sŠ   |   t| ƒd ddf¡| j } }|dkr8tj| dd�} n2|dkr^t tj| d dd�d ¡} ntd| ƒ‚|   | jdd… |dd…  ¡S )	aq  Merge data from channel pairs using the RMS or mean.

    Parameters
    ----------
    data : array, shape = (n_channels, ..., n_times)
        Data for channels, ordered in pairs.
    method : str
        Can be 'rms' or 'mean'.

    Returns
    -------
    data : array, shape = (n_channels / 2, ..., n_times)
        The root mean square or mean for each pair.
    r   rÒ   rÝ   r   rx   rö   z'method must be "rms" or "mean", got %s.N)rí   rI   r(   rK   rÝ   r‹   rì   r&   )rY   rú   Z
orig_shaper   r   r   r÷   Ò  s     r÷   c           	      C   sÊ   t jdt jd�}t|ƒD ]x\}}d|krt jdt jd�}| d¡}|dd… D ]}t  || |¡¡}qNt j| t  ||¡ dd�| |< t  ||¡}qt  |¡}t	|dd�D ]}||= t  
| |d¡} q¨| |fS )	aŽ  Merge data from multiple nirs channel using the mean.

    Channel names that have an x in them will be merged. The first channel in
    the name is replaced with the mean of all listed channels. The other
    channels are removed.

    Parameters
    ----------
    data : array, shape = (n_channels, ..., n_times)
        Data for channels.
    merged_names : list
        List of strings containing the channel names. Channels that are to be
        merged contain an x between them.

    Returns
    -------
    data : array
        Data for channels with requested channels merged. Channels used in the
        merge are removed from the array.
    r   rC   r-   r   Nrx   T)Úreverse)rK   ÚemptyZint32r    rH   rJ   rÇ   rÝ   ÚuniqueÚsortedÚdelete)	rY   Zmerged_namesZ	to_remover¤   r¬   ÚindicesÚchannelsZsub_chÚremr   r   r   rù   ë  s    

rù   çìQ¸…ë±?çš™™™™™©?ç{®Gáz”?Úecogc	                    sb  ddl m}	 |dkr$t | jd ¡}|dkr:dd„ |D ƒ}t|ƒt|ƒkrRtdƒ‚t|ƒt| ƒkrjtdƒ‚|  ¡  t	¡j
\‰ }
|dk	r¼t|tƒrš|	 |¡n|}ˆ |jd  ‰ |
|jd  }
n8|rôˆ |
fD ]*}|| d¡8 }|| d¡| d¡  }qÈtt ˆ |
g¡j
|d�}dd|d |d f}‡ fd	d„||fD ƒ\}}t ˆ |
||g¡j
}t|||||ƒ}|S )
a¤  Generate a custom 2D layout from xy points.

    Generates a 2-D layout for plotting with plot_topo methods and
    functions. XY points will be normalized between 0 and 1, where
    normalization extremes will be either the min/max of xy, or
    the width/height of bg_image.

    Parameters
    ----------
    xy : ndarray, shape (N, 2)
        The xy coordinates of sensor locations.
    w : float
        The width of each sensor's axis (between 0 and 1).
    h : float
        The height of each sensor's axis (between 0 and 1).
    pad : float
        Portion of the box to reserve for padding. The value can range between
        0.0 (boxes will touch, default) to 1.0 (boxes consist of only padding).
    ch_names : list
        The names of each channel. Must be a list of strings, with one
        string per channel.
    ch_indices : list
        Index of each channel - must be a collection of unique integers,
        one index per channel.
    name : str
        The name of this layout type.
    bg_image : str | ndarray
        The image over which sensor axes will be plotted. Either a path to an
        image file, or an array that can be plotted with plt.imshow. If
        provided, xy points will be normalized by the width/height of this
        image. If not, xy points will be normalized by their own min/max.
    normalize : bool
        Whether to normalize the coordinates to run from 0 to 1. Defaults to
        True.

    Returns
    -------
    layout : Layout
        A Layout object that can be plotted with plot_topo
        functions and methods.

    See Also
    --------
    make_eeg_layout, make_grid_layout

    Notes
    -----
    .. versionadded:: 0.9.0
    r   Nc                 S   s   g | ]}d   |¡‘qS )z{})Úformatrr   r   r   r   rw   H  s     z&generate_2d_layout.<locals>.<listcomp>z)# channel names and indices must be equalz)# channel names and xy vals must be equalr   rz   c                    s"   g | ]}t  |gˆ jd   ¡‘qS )r   )rK   rL   r(   rr   ©r-   r   r   rw   `  s     )Zmatplotlib.pyplotZpyplotrK   r„   r(   rI   r&   ÚcopyZastyperG   rÜ   r�   ÚstrZimreadra   rb   r�   Zvstackr   )r£   r$   rÂ   Úpadr’   Z
ch_indicesrV   Zbg_imager˜   Zpltr.   ZimgZi_dimr   Z
loc_paramsr…   r   r	  r   rŸ     s0    4rŸ   )NT)rg   NNrh   F)NN)Nrh   )NNr²   )NFTN)NTrh   T)rö   )rö   )r  r  r  NNr  NT)3rÕ   Úcollectionsr   Ú	itertoolsr   Úos.pathrc   r]   ÚnumpyrK   Z
transformsr   r   Zio.pickr   r   r	   Zio.constantsr
   Zio.meas_infor   Úutilsr   r   r   r   r   r   r   r  r   Úobjectr   rW   rX   rf   r†   rŽ   r¥   rž   r�   r   rÊ   rà   rò   rô   rõ   rû   r÷   rù   rŸ   r   r   r   r   Ú<module>   s`   $\
m  ÿOFY
.
X    ÿ#
m!  ÿD

%       þ