U
    f»{j¹ª  ã                   @   sZ  d 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mZ dd
lmZmZ ddl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#m$Z$m%Z%m&Z&m'Z' ed+dd„ƒZ(d,dd„Z)d-dd„Z*d.dd„Z+d/dd„Z,ed0ddd œd!d"„ƒZ-edej.ddddddd#ddd$d%d&d'ddddddddd(dfd)d*„ƒZ/dS )1zFunctions to plot epochs data.é    )ÚCounter)ÚdeepcopyNé   )Ú_setup_channel_selectionsé   )Ú_handle_default)ÚverboseÚloggerÚwarnÚfill_docÚ_check_option)Úcreate_infoÚ_validate_type)Ú_get_channel_typesÚ_picks_to_idxÚ_DATA_CH_TYPES_SPLITÚ_VALID_CHANNEL_TYPES)Útight_layoutÚ_setup_vmin_vmaxÚplt_showÚ
_check_covÚ_handle_precomputeÚ_compute_scalingsÚDraggableColorbarÚ_setup_cmapÚ_handle_decimÚ_set_title_multiple_electrodesÚ_make_combine_callableÚ_set_window_titleÚ_make_event_color_dictÚ_get_channel_plotting_orderç        TFc           @         sê  ddl m} ddlm} tˆtdfdƒ td|ƒ}td|	ƒ}	t|ƒt|	ƒkrTtd	ƒ‚t	ˆj
ˆd
d�\‰}tˆj
ˆƒ‰ |dk	}|dkr”ˆdk	s�|r”d}t|ƒ}|dkrªtƒ n|}d|k}|dk	rÆd|d< ˆjd d  k ræˆjd k rðn ndgng }tddidddd|dd�}|jf |Ž | ¡ }ˆdk�r”|�rL‡ ‡fdd„tˆ ƒD ƒ‰nF|dk�rj‡fdd„ˆD ƒ‰n(t ˆj¡ˆ  ¡ }td||ƒ}|ˆi‰ntˆƒ‰ˆ ¡ D ]Š\}}t ˆ ¡t ˆ|¡ } tt| ƒƒdk�ròd t| ƒ¡}!td ||!¡ƒ‚t|| d |d�ˆ|< t|ƒdk �r¤|�r¤td ||¡ƒ �q¤t||ˆ|||d�‰ˆ ¡ }"dd„ tˆ ƒD ƒ}#ˆ ¡ D �]&\}}$|$d }|$d  } ‡fd!d"„|D ƒ}%t ˆj
d# ¡| }&|"dd…|f }'tˆj
d$ t|&ƒ| gt|ƒ d%�}(|(  ¡ � |%|(d&< W 5 Q R X ||'|(ˆjd d'�})||'|	|   ƒ}*t!|*ˆj||ƒ\}*}+t "|*dk¡},|d(k�rT||*|dd)d*�}*ˆ| j|*|)|,d+� |#|  d,  #|*¡ |#|  d-  #|,¡ �qf|# ¡ D ]:\}-}.|.d, }/t $|/¡}0t"|.d- ƒ}1t%|0|||1ƒ|#|-< �q˜~0~~d.d„ tˆ ƒD ƒ}2ˆ ¡ D �]B\}}$|$d  } |$d/ }3|#|  \}}|$d0 dk�r†td1ƒ &||¡}t'|t(ƒ�r†t|ƒ�r†|dk�r`| )¡ n|}4|4d2k�rrd3n|4}4|d4|4› d5�7 }t*|$d6 |$d7 ˆ||||
d
|$d- ||  |3d||||+||d8�}5ˆ| j|5d9� |�rô|�sô|3d: j+j, -¡  |3d:  .¡ \}6}7t/|6|7ƒ}8t0|6|7ƒ}9|2|- \}:};t/|:|8ƒt0|;|9ƒg|2| < �qô|�r”ˆ 1¡ D ]J}$|$d/ d: }<|$d  }-|�sH|2|- }=d;|k�r†|=ddd… }=|<j2|=Ž  �qHt3|ƒ t t4ˆƒ¡}>t |>t5¡}?t6|?ƒ�rØt 7|>|? |>|?  f¡}>‡fd<d"„|>D ƒS )=uy   Plot Event Related Potential / Fields image.

    Parameters
    ----------
    epochs : instance of Epochs
        The epochs.
    %(picks_good_data)s
        ``picks`` interacts with ``group_by`` and ``combine`` to determine the
        number of figures generated; see Notes.
    sigma : float
        The standard deviation of a Gaussian smoothing window applied along
        the epochs axis of the image. If 0, no smoothing is applied.
        Defaults to 0.
    vmin : None | float | callable
        The min value in the image (and the ER[P/F]). The unit is ÂµV for
        EEG channels, fT for magnetometers and fT/cm for gradiometers.
        If vmin is None and multiple plots are returned, the limit is
        equalized within channel types.
        Hint: to specify the lower limit of the data, use
        ``vmin=lambda data: data.min()``.
    vmax : None | float | callable
        The max value in the image (and the ER[P/F]). The unit is ÂµV for
        EEG channels, fT for magnetometers and fT/cm for gradiometers.
        If vmin is None and multiple plots are returned, the limit is
        equalized within channel types.
    colorbar : bool
        Display or not a colorbar.
    order : None | array of int | callable
        If not ``None``, order is used to reorder the epochs along the y-axis
        of the image. If it is an array of :class:`int`, its length should
        match the number of good epochs. If it is a callable it should accept
        two positional parameters (``times`` and ``data``, where
        ``data.shape == (len(good_epochs), len(times))``) and return an
        :class:`array <numpy.ndarray>` of indices that will sort ``data`` along
        its first axis.
    show : bool
        Show figure if True.
    units : dict | None
        The units of the channel types used for axes labels. If None,
        defaults to ``units=dict(eeg='ÂµV', grad='fT/cm', mag='fT')``.
    scalings : dict | None
        The scalings of the channel types to be applied for plotting.
        If None, defaults to ``scalings=dict(eeg=1e6, grad=1e13, mag=1e15,
        eog=1e6)``.
    cmap : None | colormap | (colormap, bool) | 'interactive'
        Colormap. 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 scale. Up and down arrows can be used to change the
        colormap. If 'interactive', translates to ('RdBu_r', True).
        If None, "RdBu_r" is used, unless the data is all positive, in which
        case "Reds" is used.
    fig : Figure | None
        :class:`~matplotlib.figure.Figure` instance to draw the image to.
        Figure must contain the correct number of axes for drawing the epochs
        image, the evoked response, and a colorbar (depending on values of
        ``evoked`` and ``colorbar``). If ``None`` a new figure is created.
        Defaults to ``None``.
    axes : list of Axes | dict of list of Axes | None
        List of :class:`~matplotlib.axes.Axes` objects in which to draw the
        image, evoked response, and colorbar (in that order). Length of list
        must be 1, 2, or 3 (depending on values of ``colorbar`` and ``evoked``
        parameters). If a :class:`dict`, each entry must be a list of Axes
        objects with the same constraints as above. If both ``axes`` and
        ``group_by`` are dicts, their keys must match. Providing non-``None``
        values for both ``fig`` and ``axes``  results in an error. Defaults to
        ``None``.
    overlay_times : array_like, shape (n_epochs,) | None
        Times (in seconds) at which to draw a line on the corresponding row of
        the image (e.g., a reaction time associated with each epoch). Note that
        ``overlay_times`` should be ordered to correspond with the
        :class:`~mne.Epochs` object (i.e., ``overlay_times[0]`` corresponds to
        ``epochs[0]``, etc).
    %(combine)s
        If callable, the callable must accept one positional input (data of
        shape ``(n_epochs, n_channels, n_times)``) and return an
        :class:`array <numpy.ndarray>` of shape ``(n_epochs, n_times)``. For
        example::

            combine = lambda data: np.median(data, axis=1)

        If ``combine`` is ``None``, channels are combined by computing GFP,
        unless ``group_by`` is also ``None`` and ``picks`` is a list of
        specific channels (not channel types), in which case no combining is
        performed and each channel gets its own figure. See Notes for further
        details. Defaults to ``None``.
    group_by : None | dict
        Specifies which channels are aggregated into a single figure, with
        aggregation method determined by the ``combine`` parameter. If not
        ``None``, one :class:`~matplotlib.figure.Figure` is made per dict
        entry; the dict key will be used as the figure title and the dict
        values must be lists of picks (either channel names or integer indices
        of ``epochs.ch_names``). For example::

            group_by=dict(Left_ROI=[1, 2, 3, 4], Right_ROI=[5, 6, 7, 8])

        Note that within a dict entry all channels must have the same type.
        ``group_by`` interacts with ``picks`` and ``combine`` to determine the
        number of figures generated; see Notes. Defaults to ``None``.
    evoked : bool
        Draw the ER[P/F] below the image or not.
    ts_args : None | dict
        Arguments passed to a call to `~mne.viz.plot_compare_evokeds` to style
        the evoked plot below the image. Defaults to an empty dictionary,
        meaning `~mne.viz.plot_compare_evokeds` will be called with default
        parameters.
    title : None | str
        If :class:`str`, will be plotted as figure title. Otherwise, the
        title will indicate channel(s) or channel type being plotted. Defaults
        to ``None``.
    clear : bool
        Whether to clear the axes before plotting (if ``fig`` or ``axes`` are
        provided). Defaults to ``False``.

    Returns
    -------
    figs : list of Figure
        One figure per channel, channel type, or group, depending on values of
        ``picks``, ``group_by``, and ``combine``. See Notes.

    Notes
    -----
    You can control how channels are aggregated into one figure or plotted in
    separate figures through a combination of the ``picks``, ``group_by``, and
    ``combine`` parameters. If ``group_by`` is a :class:`dict`, the result is
    one :class:`~matplotlib.figure.Figure` per dictionary key (for any valid
    values of ``picks`` and ``combine``). If ``group_by`` is ``None``, the
    number and content of the figures generated depends on the values of
    ``picks`` and ``combine``, as summarized in this table:

    .. cssclass:: table-bordered
    .. rst-class:: midvalign

    +----------+----------------------------+------------+-------------------+
    | group_by | picks                      | combine    | result            |
    +==========+============================+============+===================+
    |          | None, int, list of int,    | None,      |                   |
    | dict     | ch_name, list of ch_names, | string, or | 1 figure per      |
    |          | ch_type, list of ch_types  | callable   | dict key          |
    +----------+----------------------------+------------+-------------------+
    |          | None,                      | None,      |                   |
    |          | ch_type,                   | string, or | 1 figure per      |
    |          | list of ch_types           | callable   | ch_type           |
    | None     +----------------------------+------------+-------------------+
    |          | int,                       | None       | 1 figure per pick |
    |          | ch_name,                   +------------+-------------------+
    |          | list of int,               | string or  | 1 figure          |
    |          | list of ch_names           | callable   |                   |
    +----------+----------------------------+------------+-------------------+
    r   )Úgaussian_filter1dr   )ÚEpochsArrayNÚgroup_byÚunitsÚscalingsz+Scalings and units must have the same keys.T)Zreturn_kindZgfpZylimFZshow_sensorséÿÿÿÿÚcondÚkÚ )ÚcolorsÚtitleÚshowZtruncate_yaxisZtruncate_xaxisÚvlinesZlegendc                    s(   i | ] }|t kr|ˆt ˆ ¡|k “qS © )r   ÚnpÚarray©Ú.0Úch_type)Úch_typesÚpicksr/   úM/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/viz/epochs.pyÚ
<dictcomp>è   s   þ z%plot_epochs_image.<locals>.<dictcomp>c                    s   i | ]}ˆ j | |g“qS r/   )Úch_names)r3   Úpick©Úepochsr/   r7   r8   í   s      r   ú, zBCannot combine sensors of different types; "{}" contains types {}.)r6   r4   r,   z>Only one channel in group "{}"; cannot combine by method "{}".©Úclearc                 S   s   i | ]}|t tƒ tƒ d �“qS ))ÚimagesÚnorm)ÚdictÚlistr2   r/   r/   r7   r8     s   ÿ r6   r4   c                    s   g | ]}ˆ j d  | ‘qS )Úchs)Úinfo)r3   Únr;   r/   r7   Ú
<listcomp>  s     z%plot_epochs_image.<locals>.<listcomp>r9   Úsfreq)rH   r9   r5   rD   )Útminr!   Únearest)ÚsigmaÚaxisÚmode)Úimager<   rA   r@   rA   c                 S   s   i | ]}|d d g“qS )r!   r/   r2   r/   r/   r7   r8   6  s      Úaxesr,   ÚtitlesÚstdz	std. dev.z (ú)rN   r<   )r<   r6   ÚcolorbarÚvminÚvmaxÚcmapÚ
style_axesrA   ÚunitÚaxr-   r,   ÚcombineÚcombine_givenÚoverlay_timesÚevokedÚts_args©Úfigr]   Zinvert_yc                    s   g | ]}ˆ | d  ‘qS r_   r/   )r3   Úgroup)r$   r/   r7   rG   l  s     )8Zscipy.ndimager"   r*   r#   r   rB   r   ÚsetÚ
ValueErrorr   rE   r   r   ÚtimesÚupdateÚcopyr0   r1   r9   Útolistr   r   ÚitemsZin1dÚlenÚjoinÚformatr
   Ú_validate_fig_and_axesÚget_datar   rC   Ú_unlockÚ_order_epochsÚallÚappendÚstackr   ÚgetÚ
isinstanceÚstrÚupperÚ_plot_epochs_imageÚfigureZcanvasZ	draw_idleZget_ylimÚminÚmaxÚvaluesZset_ylimr   Úsortedr   ÚanyÚconcatenate)@r<   r6   rK   rT   rU   rS   Úorderr-   r%   r&   rV   r`   rO   r\   rZ   r$   r]   r^   r,   r?   r"   r#   Zpicked_typesr[   Zcombine_funcZmanual_ylimsr.   Zts_defaultsr9   ÚkeyÚ
this_groupZthese_picksZthis_ch_typeÚtypesÚdataZ	vmin_vmaxZthis_group_dictZthis_ch_infoZthese_ch_namesZ	this_dataZ	this_infoZthis_epochsZ
this_imageZ_overlay_timesZ	this_normr4   Zthis_vmin_vmax_dictZ
image_listZimage_stackrA   Z
auto_ylimsZthis_axes_dictZ_combÚthis_figZthis_botZthis_topZthis_minZthis_maxZcurr_minZcurr_maxrY   ÚargsZreturn_orderZare_ch_typesr/   )r5   r<   r$   r6   r7   Úplot_epochs_image#   s2     

.  þ
ÿ

 ÿ
ÿ
 ÿ
ÿÿ
þ
 ÿ
ÿÿ
            ú

ÿ


ÿr†   c                 C   s  ddl m}m}m} dt|ƒ t|ƒ }	d}
t |
¡t d||g¡ }
d ||¡}| dk	rr|dk	rrt	d | |¡ƒ‚| dk�r
|dk�r
t
ƒ }|r”d	nd
}|r dnd}d}|D ]\}|ƒ }t||ƒ ||d|||d� |rè||d|d|d� |rþ||dd||d� |j||< q¬| dk	�rÄt| jƒ|	|	d fk�rDt	d ||	t| jƒ¡ƒ‚tt|ƒƒdk�rpt	d t|ƒd |¡¡ƒ‚t|ƒd }|�rºdd„ | jD ƒ}t| jƒ|	k�r°| jd  ¡  t| |ƒ || ji}t||ƒ�rÖ|g}t|tjƒ�rð| ¡  ¡ }t|tƒ�r`t|ƒ|	k�r t	d ||	t|ƒ¡ƒ‚tt|ƒƒdk�rLt	d t|ƒd |¡¡ƒ‚t|ƒd }||i}t|t
ƒ�rþt|ƒt|ƒk�r–t	d t|ƒt|ƒ¡ƒ‚| ¡ D ]^\}}t|ƒ|	k�rÊt	d ||	t|ƒ¡ƒ‚|d  ¡ || d< dd„ t|
|ƒD ƒ|| d< �qž|S ) zBCheck user-provided fig/axes compatibility with plot_epochs_image.r   )rx   ÚAxesÚsubplot2gridr   )rN   r]   rS   Tz!Since evoked={} and colorbar={}, NzBAt least one of "fig" or "axes" must be None; got fig={}, axes={}.é	   é
   r   é   )r‹   rŠ   )r   r   )ÚcolspanÚrowspanr`   )r   r   )r   r‰   z%{}"fig" must contain {} axes, got {}.zHWhen "fig" is not None, "group_by" can only have one group (got {}: {}).r=   c                 S   s   g | ]}|  ¡ ‘qS r/   r>   )r3   rY   r/   r/   r7   rG   �  s     z*_validate_fig_and_axes.<locals>.<listcomp>r'   z#{}"axes" must be length {}, got {}.zAWhen axes is a list, can only plot one group (got {} groups: {}).zIIf "axes" is a dict its keys ({}) must match the keys in "group_by" ({}).z9{}each value in "axes" must be a list of {} axes, got {}.r`   c                 S   s   i | ]\}}||“qS r/   r/   )r3   r€   rL   r/   r/   r7   r8   É  s      z*_validate_fig_and_axes.<locals>.<dictcomp>rO   )Úmatplotlib.pyplotrx   r‡   rˆ   Úintr0   r1   Úwhererk   rc   rB   r   rO   ri   rC   rj   Úremovert   ZndarrayZravelrg   rb   rh   Ú
get_figureÚzip)r`   rO   r$   r]   rS   r?   rx   r‡   rˆ   Zn_axesZax_namesÚprefixrŒ   r�   Úshaper�   r„   r€   Ú_Zthis_axes_listr/   r/   r7   rl   o  sª     ÿ

ÿ
ÿ
ÿ
  ÿ þ

  ÿ þ þ þÿrl   c                 C   s   t | ƒ}|dk	rŠt |ƒ|kr6tdt |ƒ› d|› d�ƒ‚t |¡}t |¡}t |¡}||d k sl||d krŠtd|d › d|d › d	�ƒ t|ƒrœ||| ƒ}|dk	røt |ƒ|krÖtd
t|ƒj	› dt |ƒ› d|› d�ƒ‚t |¡}| | } |dk	rø|| }| |fS )z:Sort epochs image data (2D). Helper for plot_epochs_image.Nz!size of overlay_times parameter (z') does not match the number of epochs (z).r   r'   zOSome values in overlay_times fall outside of the epochs time interval (between z s and z s)zIf order is a z, its length (z%) must match the length of the data ()
ri   rc   r0   r1   ry   rz   r
   ÚcallableÚtypeÚ__name__)rƒ   rd   r   r\   Ún_epochsZ	times_minZ	times_maxr/   r/   r7   ro   Î  s*    ÿ



&
ro   c               
   C   s`  ddl m} |	dkr |rdnd}	|jd }|jd }|
d }| ¡ }t|	|d�}	t| ƒ}||d|g}|j| |||	d d	d
d|d�}|rÎ| |¡ | d¡ |s¨| 	d¡ | 
d	¡ | 
d¡ |jddddd� |dk	rþ|j|dt |¡ ddd� | ||¡ |�rÞddlm} |�r|nd}t|ƒdk�r2dgnd}|dt|jdd�ƒif||
d |dœ|—Ž |
d  ||¡ |
d jd  d¡ |
d jd  d¡ |
d  ¡  |
d |¡ |j ¡ }|
d j |¡ |
d j |ƒ ¡ |�rTddlm} |||
d d �}|jj|d!d"d#� |	d �r(t ||ƒ|_!t"j#dd$�� t" $d%¡ t%|d&� W 5 Q R X t&|ƒ |S )'z9Plot epochs image. Helper function for plot_epochs_image.r   )ÚAutoLocatorNZRedsZRdBu_rr'   rN   )rA   ÚautoÚlowerrJ   )rT   rU   rV   ZaspectÚoriginÚinterpolationÚextentÚEpochszTime (s)Ztightr)   r   z--)ÚcolorÚ	linewidthZ	linestyleç      à?r   )r£   )Úplot_compare_evokedsr(   F)rf   r]   )r6   rO   rZ   T)rS   rS   )Zcaxi  é   )ÚrotationZlabelpad)ÚrecordÚignorer_   )'Zmatplotlib.tickerr›   rd   r’   r   ri   ZimshowÚ	set_titleÚ
set_ylabelZ
set_xlabelrL   ZaxvlineZplotr0   ÚarangeZset_xlimr*   r¥   rC   Ziter_evokedÚlinesZset_clip_onÚcollectionsZget_shared_x_axesrj   ZxaxisZget_major_locatorZset_major_locatorZyaxisrŽ   rS   rY   r   ZCBÚwarningsÚcatch_warningsÚsimplefilterr   r   ) rN   rW   r<   r6   rT   rU   rS   r-   rX   rV   rY   r\   r,   r]   r^   rZ   r[   rA   r›   rI   ÚtmaxZax_imr`   rš   r    Zimr¥   Zpass_combineZ_picksÚlocZcbarZthis_colorbarr/   r/   r7   rw   î  sr    

  ÿ




ÿ þþ


rw   é   Ú	lightgrayçš™™™™™é?©ZIGNOREDc                    sÈ  ddl m} ddlm}	 |	| ˆ ƒ}
|
|k r8t d¡ dS t‡ fdd„| D ƒƒ}t‡ fdd„| D ƒƒ}t‡ fd	d„| D ƒƒ}t 	t
| ¡ ƒ¡}t 	t
| ¡ ƒ¡}| ¡ \}}|› d
|› d|
d›d�}|dk	rØ|› d|› �}| |¡ t|ƒdk�r|jdddddd� |S t‡ fdd„| D ƒƒ}t|t|ƒƒ}t |¡}d| | }t t |¡¡}|j|||d|…  ||dd� | |¡ |j||d|…  dddd� | d¡ |jdd� td|d� t|ƒ |S ) a¯  Show the channel stats based on a drop_log from Epochs.

    Parameters
    ----------
    drop_log : list of list
        Epoch drop log from Epochs.drop_log.
    threshold : float
        The percentage threshold to use to decide whether or not to
        plot. Default is zero (always plot).
    n_max_plot : int
        Maximum number of channels to show stats for.
    subject : str | None
        The subject name to use in the title of the plot. If ``None``, do not
        display a subject name.

        .. versionchanged:: 0.23
           Added support for ``None``.

        .. versionchanged:: 1.0
           Defaults to ``None``.
    color : tuple | str
        Color to use for the bars.
    width : float
        Width of the bars.
    ignore : list
        The drop reasons to ignore.
    show : bool
        Show figure if True.

    Returns
    -------
    fig : instance of matplotlib.figure.Figure
        The figure.
    r   Nr   )Ú_drop_log_statszCPercent dropped epochs < supplied threshold; not plotting drop log.c                    s.   g | ]&}t |ƒrt‡ fd d„|D ƒƒs|‘qS )c                 3   s   | ]}|ˆ kV  qd S ©Nr/   ©r3   Úy©r©   r/   r7   Ú	<genexpr>b  s     ú+plot_drop_log.<locals>.<listcomp>.<genexpr>)ri   r}   ©r3   Úxr¼   r/   r7   rG   a  s     ÿz!plot_drop_log.<locals>.<listcomp>c                    s&   g | ]}t ‡ fd d„|D ƒƒs|‘qS )c                 3   s   | ]}|ˆ kV  qd S r¹   r/   rº   r¼   r/   r7   r½   d  s     r¾   )r}   r¿   r¼   r/   r7   rG   c  s    ÿc                    s"   g | ]}|D ]}|ˆ kr|‘qqS r/   r/   )r3   ÚdÚchr¼   r/   r7   rG   f  s
        z of z epochs removed (z.1fz%)z: r¤   zNo dropsÚcenteré   )ZhaZfontsizec                    s.   g | ]&}t ‡ fd d„|D ƒƒp(t|ƒdk‘qS )c                 3   s   | ]}|ˆ kV  qd S r¹   r/   )r3   rÂ   r¼   r/   r7   r½   t  s     r¾   r   )r}   ri   )r3   rÁ   r¼   r/   r7   rG   t  s   ÿéd   )r¢   ÚwidthÚaligné-   rŠ   Úright)r§   ÚsizeZhorizontalalignmentz% of epochs removedr»   )rL   r   )Úpadr`   )rŽ   Zpyplotr<   r¸   r	   rE   ri   r   r0   r1   rC   Úkeysr{   Zsubplotsrª   ÚtextÚsumry   r¬   ZflipudZargsortÚbarZ
set_xticksZset_xticklabelsr«   Úgridr   r   )Zdrop_logÚ	thresholdZ
n_max_plotÚsubjectr¢   rÆ   r©   r-   Zpltr¸   ÚpercentÚabsoluteZn_epochs_before_dropZscoresr9   Úcountsr`   rY   r,   Zn_usedZn_barsrÀ   r»   r   r/   r¼   r7   Úplot_drop_log5  sH    %


ÿ
 
ÿ
rÖ   rœ   r˜   )ÚthemeÚoverview_modec          =   1   C   sÄ  ddl m} |  ¡  | j ¡ }|d }|d }tj|| jtd�}| jsd| 	¡ � t
ƒ |d< W 5 Q R X tddƒ}t|| ƒ}td|ƒ}|d	 d
kr–d|d	< tddƒ}tddƒ}t| j ¡ |dƒ\}}t|| jƒ}dd„ |pØi  ¡ D ƒ} td|dƒ t|t
dfdƒ |dk	�r¤t|ƒt| jƒk�r>dt| ƒ› dt|ƒ› d�}!t|!ƒ‚t|ƒD ]\\}"}#t|#t
d|"› d�ƒ t|#ƒt| jƒk�rFd|"› dt|#ƒ› dt| jƒ› d�}!t|!ƒ‚�qFt|t| ƒƒ}t| ƒt| jƒ }$|t| jƒ | }%t t| ƒd ¡t| jƒ | }&|dk	�rN|dd…df }'|dd…df }(t| jƒ})| jdd…dgf t ddg¡|  d¡  }*t |*dd…dgf |(k|(|*dd…dgf k ¡}+dd„ |+jD ƒ},d }-t
ƒ }.t
ƒ }/t|(|'|,ƒD ]„\}0}1}2| jdd…df |2 }3t|3ƒdk�rô|-�sôt d!¡ d"}-|0|3 |  d¡ }4|2|) |4 | }5|.  |5¡ |/  |1gt|2ƒ ¡ �q²t |/¡}'t |.¡}.nd}'d}.t!|||ƒ}6t"||ƒ}t|t|ƒƒ}t | j¡}7t |  #¡ ¡}8t$||8|ƒ}d}9|d#k�rät%| ||ƒ}9t &t
|9 '¡ ƒ¡}t
|9ƒd }:t|9|: ƒ}|dk�r| j(}|dk�st|ƒdk�r0d$}nt)|t*ƒ�s0t+d%t,|ƒ› �ƒ‚t-|ƒ}t.| |||7|8||d|… ||||9d|%|$dd&||&| |6|'|.||| jd"dd||dk	|||d'|d(||d|||d)||||d*�/};|f |	|
d+œ|;—Ž}<|<S ),a   Visualize epochs.

    Bad epochs can be marked with a left click on top of the epoch. Bad
    channels can be selected by clicking the channel name on the left side of
    the main axes. Calling this function drops all the selected bad epochs as
    well as bad epochs marked beforehand with rejection parameters.

    Parameters
    ----------
    epochs : instance of Epochs
        The epochs object.
    %(picks_good_data)s
    %(scalings)s
    n_epochs : int
        The number of epochs per view. Defaults to 20.
    n_channels : int
        The number of channels per view. Defaults to 20.
    title : str | None
        The title of the window. If None, epochs name will be displayed.
        Defaults to None.
    events : None | array, shape (n_events, 3)
        Events to show with vertical bars. You can use `~mne.viz.plot_events`
        as a legend for the colors. By default, the coloring scheme is the
        same. Defaults to ``None``.

        .. warning::  If the epochs have been resampled, the events no longer
            align with the data.

        .. versionadded:: 0.14.0
    %(event_color)s
        Defaults to ``None``.
    order : array of str | None
        Order in which to plot channel types.

        .. versionadded:: 0.18.0
    show : bool
        Show figure if True. Defaults to True.
    block : bool
        Whether to halt program execution until the figure is closed.
        Useful for rejecting bad trials on the fly by clicking on an epoch.
        Defaults to False.
    decim : int | 'auto'
        Amount to decimate the data during display for speed purposes.
        You should only decimate if the data are sufficiently low-passed,
        otherwise aliasing can occur. The 'auto' mode (default) uses
        the decimation that results in a sampling rate at least three times
        larger than ``info['lowpass']`` (e.g., a 40 Hz lowpass will result in
        at least a 120 Hz displayed sample rate).

        .. versionadded:: 0.15.0
    noise_cov : instance of Covariance | str | None
        Noise covariance used to whiten the data while plotting.
        Whitened data channels are scaled by ``scalings['whitened']``,
        and their channel names are shown in italic.
        Can be a string to load a covariance from disk.
        See also :meth:`mne.Evoked.plot_white` for additional inspection
        of noise covariance properties when whitening evoked data.
        For data processed with SSS, the effective dependence between
        magnetometers and gradiometers may introduce differences in scaling,
        consider using :meth:`mne.Evoked.plot_white`.

        .. versionadded:: 0.16.0
    butterfly : bool
        Whether to directly call the butterfly view.

        .. versionadded:: 0.18.0
    %(show_scrollbars)s
    %(show_scalebars)s

        .. versionadded:: 0.24.0
    epoch_colors : list of (n_epochs) list (of n_channels) | None
        Colors to use for individual epochs. If None, use default colors.
    event_id : dict | None
        Dictionary of event labels (e.g. 'aud_l') as keys and associated event
        integers as values. Useful when ``events`` contains event numbers not
        present in ``epochs.event_id`` (e.g., because of event subselection).
        Values in ``event_id`` will take precedence over those in
        ``epochs.event_id`` when there are overlapping keys.

        .. versionadded:: 0.20
    %(group_by_browse)s
    %(precompute)s
    %(use_opengl)s
    %(theme_pg)s

        .. versionadded:: 1.0
    %(overview_mode)s

        .. versionadded:: 1.1

    Returns
    -------
    %(browser)s

    Notes
    -----
    The arrow keys (up/down/left/right) can be used to navigate between
    channels and epochs and the scaling can be adjusted with - and + (or =)
    keys, but this depends on the backend matplotlib is configured to use
    (e.g., mpl.use(``TkAgg``) should work). Full screen mode can be toggled
    with f11 key. The amount of epochs and channels per view can be adjusted
    with home/end and page down/page up keys. ``h`` key plots a histogram of
    peak-to-peak values along with the used rejection thresholds. Butterfly
    plot can be toggled with ``b`` key. Left mouse click adds a vertical line
    to the plot. Click 'help' button at bottom left corner of the plotter to
    view all the options.

    .. versionadded:: 0.10.0
    r   )Ú_get_browserrH   Úprojs)Zdtyper¢   NZscalings_plot_rawZwhitenedrœ   g      ð?r%   r&   c                 S   s   i | ]\}}||“qS r/   r/   )r3   r)   Úvr/   r/   r7   r8     s      zplot_epochs.<locals>.<dictcomp>r$   )Ú	selectionÚpositionÚoriginalr˜   Úepoch_colorsz=epoch_colors must have length equal to the number of epochs (z); got length Ú.zepoch_colors[ú]zepoch colors for epoch z has length z, expected r   r   r'   c                 S   s   g | ]}t  |¡d  ‘qS )r   )r0   Znonzero)r3   Úar/   r/   r7   rG   2  s     zplot_epochs.<locals>.<listcomp>FzTYou seem to have overlapping epochs. Some event lines may be duplicated in the plot.T)rÜ   rÝ   r¡   z&title must be None or a string, got a Úfloatrµ   )r   r   r   zEpoch number)/ÚinstrE   rš   r9   r5   Zch_orderr6   Ú
n_channelsÚ
picks_datar$   Zch_selectionsZt_startÚdurationÚn_timesZ
first_timeÚtime_formatÚdecimÚboundary_timesÚevent_id_revÚevent_color_dictÚ
event_numsÚevent_timesrÚ   Úprojs_onZ
apply_projZ	remove_dcZfilter_coefsZfilter_boundsÚ	noise_covZuse_noise_covr&   r%   Úunit_scalingsZch_color_badZch_color_dictZepoch_color_badrß   Ú	butterflyZclippingZscrollbars_visibleZscalebars_visibleZwindow_titleZxlabelÚ
precomputeÚ
use_openglr×   rØ   )r-   Úblock)/Z_figurerÙ   Zdrop_badrE   rf   r0   Z	full_likeÚprojÚboolrn   rC   r   r   r   r   rh   r   r   ri   Úeventsrc   Ú	enumerater9   ry   rd   r¬   r1   Ztime_as_indexÚlogical_andÚTr“   r	   Úextendr   r   Zget_channel_typesr    r   r~   r{   Ú_namert   ru   Ú	TypeErrorr˜   r   rB   )=r<   r6   r&   rš   rå   r,   rù   Zevent_colorr   r-   rö   rê   rñ   ró   Zshow_scrollbarsZshow_scalebarsrß   Zevent_idr$   rô   rõ   r×   rØ   rÙ   rE   rH   rÚ   rð   r¢   r%   rò   ræ   rì   ÚmsgZixZthis_colorsrè   rç   rë   rî   Zevent_sampsZepoch_n_sampsZ
boundariesZ	in_boundsZ	event_ixsZwarnedrï   Zevent_numbersZsampÚnumZ_ixsZrelevant_epoch_eventsÚoffsetsZthis_event_timesrí   r9   r5   Z
selectionsZdefault_selectionÚparamsr`   r/   r/   r7   Úplot_epochs†  s   u






ÿ
" 

ÿÿ






Ê8r  ÚlengthÚblackZlinearrQ   g…ëQ¸Õ?Zbadsc                 C   sR   ddl m} || ||
||||||||||||||||||||	d|d�}t|ƒ |S )aD  %(plot_psd_doc)s.

    Parameters
    ----------
    epochs : instance of Epochs
        The epochs object.
    fmin : float
        Start frequency to consider.
    fmax : float
        End frequency to consider.
    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.
    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
    %(picks_plot_psd_good_data)s
    ax : instance of Axes | None
        Axes to plot into. If None, axes will be created.
    %(color_plot_psd)s
    %(xscale_plot_psd)s
    %(area_mode_plot_psd)s
    %(area_alpha_plot_psd)s
    %(dB_plot_psd)s
    %(estimate_plot_psd)s
    %(show)s
    %(n_jobs)s
    %(average_plot_psd)s
    %(line_alpha_plot_psd)s
    %(spatial_colors_plot_psd)s
    %(sphere_topomap_auto)s
    exclude : list of str | 'bads'
        Channels names to exclude from being shown. If 'bads', the bad channels
        are excluded. Pass an empty list to plot all channels (including
        channels marked "bad", if any).

        .. versionadded:: 0.24.0
    %(verbose)s

    Returns
    -------
    fig : instance of Figure
        Figure with frequency spectra of the data channels.
    r   )Ú_psd_figureZhamming)rä   r÷   r6   rO   rI   r²   ÚfminÚfmaxÚsphereÚxscaleÚdBÚaverageÚestimateÚ	area_modeÚ
line_alphaÚ
area_alphar¢   Úspatial_colorsÚn_jobsÚ	bandwidthÚadaptiveÚlow_biasÚnormalizationZwindowÚexclude)Z_mpl_figurer  r   )r<   r  r	  rI   r²   r÷   r  r  r  r  r6   rY   r¢   r  r  r  r  r  r-   r  r  r  r  r
  r  r   r  r`   r/   r/   r7   Úplot_epochs_psdš  s<    >                  ùr  )Nr!   NNTNTNNNNNNNNTNNF)F)NN)TNNNNFFNNNNNFNNFF)r   r´   Nrµ   r¶   r·   T)NNr´   r´   NNNNTFrœ   NFTTNNr˜   NN)0Ú__doc__r®   r   rf   r   r¯   Únumpyr0   Úrawr   Údefaultsr   Úutilsr   r	   r
   r   r   Zio.meas_infor   r   Zio.pickr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r†   rl   ro   rw   rÖ   r  Úinfr  r/   r/   r/   r7   Ú<module>   sÎ   @                            û  M
_
                          ü
G       þ
Q                            û ú  
               ú