<commit_before>"""Functions to plot ICA specific data (besides topographies)
"""
from __future__ import print_function

# Authors: <NAME> <<EMAIL>>
#          <NAME> <<EMAIL>>
#          <NAME> <<EMAIL>>
#
# License: Simplified BSD

from functools import partial

import numpy as np

from .utils import tight_layout, _prepare_trellis, _select_bads
from .utils import _layout_figure, _plot_raw_onscroll, _mouse_click
from .utils import _helper_raw_resize, _plot_raw_onkey
from .raw import _prepare_mne_browse_raw, _plot_raw_traces
from .epochs import _prepare_mne_browse_epochs
from .evoked import _butterfly_on_button_press, _butterfly_onpick
from .topomap import _prepare_topo_plot, plot_topomap
from ..utils import logger
from ..defaults import _handle_default
from ..io.meas_info import create_info
from ..io.pick import pick_types
from ..externals.six import string_types


def _ica_plot_sources_onpick_(event, sources=None, ylims=None):
    """Onpick callback for plot_ica_panel"""

    # make sure that the swipe gesture in OS-X doesn't open many figures
    if event.mouseevent.inaxes is None or event.mouseevent.button != 1:
        return

    artist = event.artist
    try:
        import matplotlib.pyplot as plt
        plt.figure()
        src_idx = artist._mne_src_idx
        component = artist._mne_component
        plt.plot(sources[src_idx], 'r' if artist._mne_is_bad else 'k')
        plt.ylim(ylims)
        plt.grid(linestyle='-', color='gray', linewidth=.25)
        plt.title('ICA #%i' % component)
    except Exception as err:
        # matplotlib silently ignores exceptions in event handlers, so we print
        # it here to know what went wrong
        print(err)
        raise err


def plot_ica_sources(ica, inst, picks=None, exclude=None, start=None,
                     stop=None, show=True, title=None, block=False):
    """Plot estimated latent sources given the unmixing matrix.

    Typical usecases:

    1. plot evolution of latent sources over time based on (Raw input)
    2. plot latent source around event related time windows (Epochs input)
    3. plot time-locking in ICA space (Evoked input)


    Parameters
    ----------
    ica : instance of mne.preprocessing.ICA
        The ICA solution.
    inst : instance of mne.io.Raw, mne.Epochs, mne.Evoked
        The object to plot the sources from.
    picks : int | array_like of int | None.
        The components to be displayed. If None, plot will show the
        sources in the order as fitted.
    exclude : array_like of int
        The components marked for exclusion. If None (default), ICA.exclude
        will be used.
    start : int
        X-axis start index. If None, from the beginning.
    stop : int
        X-axis stop index. If None, next 20 are shown, in case of evoked to the
        end.
    show : bool
        Show figure if True.
    title : str | None
        The figure title. If None a default is provided.
    block : bool
        Whether to halt program execution until the figure is closed.
        Useful for interactive selection of components in raw and epoch
        plotter. For evoked, this parameter has no effect. Defaults to False.

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

    Notes
    -----
    For raw and epoch instances, it is possible to select components for
    exclusion by clicking on the line. The selected components are added to
    ``ica.exclude`` on close.

    .. versionadded:: 0.10.0
    """

    from ..io.base import _BaseRaw
    from ..evoked import Evoked
    from ..epochs import _BaseEpochs

    if exclude is None:
        exclude = ica.exclude
    elif len(ica.exclude) > 0:
        exclude = np.union1d(ica.exclude, exclude)
    if isinstance(inst, _BaseRaw):
        fig = _plot_sources_raw(ica, inst, picks, exclude, start=start,
                                stop=stop, show=show, title=title,
                                block=block)
    elif isinstance(inst, _BaseEpochs):
        fig = _plot_sources_epochs(ica, inst, picks, exclude, start=start,
                                   stop=stop, show=show, title=title,
                                   block=block)
    elif isinstance(inst, Evoked):
        sources = ica.get_sources(inst)
        if start is not None or stop is not None:
            inst = inst.crop(start, stop, copy=True)
        fig = _plot_ica_sources_evoked(
            evoked=sources, picks=picks, exclude=exclude, title=title,
            labels=getattr(ica, 'labels_', None), show=show)
    else:
        raise ValueError('Data input must be of Raw or Epochs type')

    return fig


def _plot_ica_grid(sources, start, stop,
                   source_idx, ncol, exclude,
                   title, show):
    """Create panel plots of ICA sources

    Clicking on the plot of an individual source opens a new figure showing
    the source.

    Parameters
    ----------
    sources : ndarray
        Sources as drawn from ica.get_sources.
    start : int
        x-axis start index. If None from the beginning.
    stop : int
        x-axis stop index. If None to the end.
    n_components : int
        Number of components fitted.
    source_idx : array-like
        Indices for subsetting the sources.
    ncol : int
        Number of panel-columns.
    title : str
        The figure title. If None a default is provided.
    show : bool
        If True, all open plots will be shown.
    """
    import matplotlib.pyplot as plt

    if source_idx is None:
        source_idx = np.arange(len(sources))
    elif isinstance(source_idx, list):
        source_idx = np.array(source_idx)
    if exclude is None:
        exclude = []

    n_components = len(sources)
    ylims = sources.min(), sources.max()
    xlims = np.arange(sources.shape[-1])[[0, -1]]
    fig, axes = _prepare_trellis(n_components, ncol)
    if title is None:
        fig.suptitle('Reconstructed latent sources', size=16)
    elif title:
        fig.suptitle(title, size=16)

    plt.subplots_adjust(wspace=0.05, hspace=0.05)
    my_iter = enumerate(zip(source_idx, axes, sources))
    for i_source, (i_selection, ax, source) in my_iter:
        component = '[%i]' % i_selection
        # plot+ emebed idx and comp. name to use in callback
        color = 'r' if i_selection in exclude else 'k'
        line = ax.plot(source, linewidth=0.5, color=color, picker=1e9)[0]
        vars(line)['_mne_src_idx'] = i_source
        vars(line)['_mne_component'] = i_selection
        vars(line)['_mne_is_bad'] = i_selection in exclude
        ax.set_xlim(xlims)
        ax.set_ylim(ylims)
        ax.text(0.05, .95, component, transform=ax.transAxes,
                verticalalignment='top')
        plt.setp(ax.get_xticklabels(), visible=False)
        plt.setp(ax.get_yticklabels(), visible=False)
    # register callback
    callback = partial(_ica_plot_sources_onpick_, sources=sources, ylims=ylims)
    fig.canvas.mpl_connect('pick_event', callback)

    if show:
        plt.show()

    return fig


def _plot_ica_sources_evoked(evoked, picks, exclude, title, show, labels=None):
    """Plot average over epochs in ICA space

    Parameters
    ----------
    evoked : instance of mne.Evoked
        The Evoked to be used.
    picks : int | array_like of int | None.
        The components to be displayed. If None, plot will show the
        sources in the order as fitted.
    exclude : array_like of int
        The components marked for exclusion. If None (default), ICA.exclude
        will be used.
    title : str
        The figure title.
    show : bool
        Show figure if True.
    labels : None | dict
        The ICA labels attribute.
    """
    import matplotlib.pyplot as plt
    if title is None:
        title = 'Reconstructed latent sources, time-locked'

    fig, axes = plt.subplots(1)
    ax = axes
    axes = [axes]
    idxs = [0]
    times = evoked.times * 1e3

    # plot unclassified sources and label excluded ones
    lines = list()
    texts = list()
    if picks is None:
        picks = np.arange(evoked.data.shape[0])
    picks = np.sort(picks)
    idxs = [picks]
    color = 'r'

    if labels is not None:
        labels_used = [k for k in labels if '/' not in k]

    exclude_labels = list()
    for ii in picks:
        if ii in exclude:
            line_label = 'ICA %03d' % (ii + 1)
            if labels is not None:
                annot = list()
                for this_label in labels_used:
                    indices = labels[this_label]
                    if ii in indices:
                        annot.append(this_label)
                line_label += (' - ' + ', '.join(annot))
            exclude_labels.append(line_label)
        else:
            exclude_labels.append(None)

    if labels is not None:
        unique_labels = set([k.split(' - ')[1] for k in exclude_labels if k])
        label_colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_labels)))
        label_colors = dict(zip(unique_labels, label_colors))

    for exc_label, ii in zip(exclude_labels, picks):
        if exc_label is not None:<commit_msg>unbound local error fix<commit_after>"""Functions to plot ICA specific data (besides topographies)
"""
from __future__ import print_function

# Authors: <NAME> <<EMAIL>>
#          <NAME> <<EMAIL>>
#          <NAME> <<EMAIL>>
#
# License: Simplified BSD

from functools import partial

import numpy as np

from .utils import tight_layout, _prepare_trellis, _select_bads
from .utils import _layout_figure, _plot_raw_onscroll, _mouse_click
from .utils import _helper_raw_resize, _plot_raw_onkey
from .raw import _prepare_mne_browse_raw, _plot_raw_traces
from .epochs import _prepare_mne_browse_epochs
from .evoked import _butterfly_on_button_press, _butterfly_onpick
from .topomap import _prepare_topo_plot, plot_topomap
from ..utils import logger
from ..defaults import _handle_default
from ..io.meas_info import create_info
from ..io.pick import pick_types
from ..externals.six import string_types


def _ica_plot_sources_onpick_(event, sources=None, ylims=None):
    """Onpick callback for plot_ica_panel"""

    # make sure that the swipe gesture in OS-X doesn't open many figures
    if event.mouseevent.inaxes is None or event.mouseevent.button != 1:
        return

    artist = event.artist
    try:
        import matplotlib.pyplot as plt
        plt.figure()
        src_idx = artist._mne_src_idx
        component = artist._mne_component
        plt.plot(sources[src_idx], 'r' if artist._mne_is_bad else 'k')
        plt.ylim(ylims)
        plt.grid(linestyle='-', color='gray', linewidth=.25)
        plt.title('ICA #%i' % component)
    except Exception as err:
        # matplotlib silently ignores exceptions in event handlers, so we print
        # it here to know what went wrong
        print(err)
        raise err


def plot_ica_sources(ica, inst, picks=None, exclude=None, start=None,
                     stop=None, show=True, title=None, block=False):
    """Plot estimated latent sources given the unmixing matrix.

    Typical usecases:

    1. plot evolution of latent sources over time based on (Raw input)
    2. plot latent source around event related time windows (Epochs input)
    3. plot time-locking in ICA space (Evoked input)


    Parameters
    ----------
    ica : instance of mne.preprocessing.ICA
        The ICA solution.
    inst : instance of mne.io.Raw, mne.Epochs, mne.Evoked
        The object to plot the sources from.
    picks : int | array_like of int | None.
        The components to be displayed. If None, plot will show the
        sources in the order as fitted.
    exclude : array_like of int
        The components marked for exclusion. If None (default), ICA.exclude
        will be used.
    start : int
        X-axis start index. If None, from the beginning.
    stop : int
        X-axis stop index. If None, next 20 are shown, in case of evoked to the
        end.
    show : bool
        Show figure if True.
    title : str | None
        The figure title. If None a default is provided.
    block : bool
        Whether to halt program execution until the figure is closed.
        Useful for interactive selection of components in raw and epoch
        plotter. For evoked, this parameter has no effect. Defaults to False.

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

    Notes
    -----
    For raw and epoch instances, it is possible to select components for
    exclusion by clicking on the line. The selected components are added to
    ``ica.exclude`` on close.

    .. versionadded:: 0.10.0
    """

    from ..io.base import _BaseRaw
    from ..evoked import Evoked
    from ..epochs import _BaseEpochs

    if exclude is None:
        exclude = ica.exclude
    elif len(ica.exclude) > 0:
        exclude = np.union1d(ica.exclude, exclude)
    if isinstance(inst, _BaseRaw):
        fig = _plot_sources_raw(ica, inst, picks, exclude, start=start,
                                stop=stop, show=show, title=title,
                                block=block)
    elif isinstance(inst, _BaseEpochs):
        fig = _plot_sources_epochs(ica, inst, picks, exclude, start=start,
                                   stop=stop, show=show, title=title,
                                   block=block)
    elif isinstance(inst, Evoked):
        sources = ica.get_sources(inst)
        if start is not None or stop is not None:
            inst = inst.crop(start, stop, copy=True)
        fig = _plot_ica_sources_evoked(
            evoked=sources, picks=picks, exclude=exclude, title=title,
            labels=getattr(ica, 'labels_', None), show=show)
    else:
        raise ValueError('Data input must be of Raw or Epochs type')

    return fig


def _plot_ica_grid(sources, start, stop,
                   source_idx, ncol, exclude,
                   title, show):
    """Create panel plots of ICA sources

    Clicking on the plot of an individual source opens a new figure showing
    the source.

    Parameters
    ----------
    sources : ndarray
        Sources as drawn from ica.get_sources.
    start : int
        x-axis start index. If None from the beginning.
    stop : int
        x-axis stop index. If None to the end.
    n_components : int
        Number of components fitted.
    source_idx : array-like
        Indices for subsetting the sources.
    ncol : int
        Number of panel-columns.
    title : str
        The figure title. If None a default is provided.
    show : bool
        If True, all open plots will be shown.
    """
    import matplotlib.pyplot as plt

    if source_idx is None:
        source_idx = np.arange(len(sources))
    elif isinstance(source_idx, list):
        source_idx = np.array(source_idx)
    if exclude is None:
        exclude = []

    n_components = len(sources)
    ylims = sources.min(), sources.max()
    xlims = np.arange(sources.shape[-1])[[0, -1]]
    fig, axes = _prepare_trellis(n_components, ncol)
    if title is None:
        fig.suptitle('Reconstructed latent sources', size=16)
    elif title:
        fig.suptitle(title, size=16)

    plt.subplots_adjust(wspace=0.05, hspace=0.05)
    my_iter = enumerate(zip(source_idx, axes, sources))
    for i_source, (i_selection, ax, source) in my_iter:
        component = '[%i]' % i_selection
        # plot+ emebed idx and comp. name to use in callback
        color = 'r' if i_selection in exclude else 'k'
        line = ax.plot(source, linewidth=0.5, color=color, picker=1e9)[0]
        vars(line)['_mne_src_idx'] = i_source
        vars(line)['_mne_component'] = i_selection
        vars(line)['_mne_is_bad'] = i_selection in exclude
        ax.set_xlim(xlims)
        ax.set_ylim(ylims)
        ax.text(0.05, .95, component, transform=ax.transAxes,
                verticalalignment='top')
        plt.setp(ax.get_xticklabels(), visible=False)
        plt.setp(ax.get_yticklabels(), visible=False)
    # register callback
    callback = partial(_ica_plot_sources_onpick_, sources=sources, ylims=ylims)
    fig.canvas.mpl_connect('pick_event', callback)

    if show:
        plt.show()

    return fig


def _plot_ica_sources_evoked(evoked, picks, exclude, title, show, labels=None):
    """Plot average over epochs in ICA space

    Parameters
    ----------
    evoked : instance of mne.Evoked
        The Evoked to be used.
    picks : int | array_like of int | None.
        The components to be displayed. If None, plot will show the
        sources in the order as fitted.
    exclude : array_like of int
        The components marked for exclusion. If None (default), ICA.exclude
        will be used.
    title : str
        The figure title.
    show : bool
        Show figure if True.
    labels : None | dict
        The ICA labels attribute.
    """
    import matplotlib.pyplot as plt
    if title is None:
        title = 'Reconstructed latent sources, time-locked'

    fig, axes = plt.subplots(1)
    ax = axes
    axes = [axes]
    idxs = [0]
    times = evoked.times * 1e3

    # plot unclassified sources and label excluded ones
    lines = list()
    texts = list()
    if picks is None:
        picks = np.arange(evoked.data.shape[0])
    picks = np.sort(picks)
    idxs = [picks]
    color = 'r'

    if labels is not None:
        labels_used = [k for k in labels if '/' not in k]

    exclude_labels = list()
    for ii in picks:
        if ii in exclude:
            line_label = 'ICA %03d' % (ii + 1)
            if labels is not None:
                annot = list()
                for this_label in labels_used:
                    indices = labels[this_label]
                    if ii in indices:
                        annot.append(this_label)
                line_label += (' - ' + ', '.join(annot))
            exclude_labels.append(line_label)
        else:
            exclude_labels.append(None)

    if labels is not None:
        unique_labels = set([k.split(' - ')[1] for k in exclude_labels if k])
        label_colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_labels)))
        label_colors = dict(zip(unique_labels, label_colors))
    else:
        label_colors = dict((k, 'red') for k in exclude_labels)

    for exc_label, ii in zip(exclude_labels, picks):
        if exc_label is not None:
{'fraction_non_alphanumeric': 0.0876068376068376, 'fraction_numerical': 0.005259697567389875, 'mean_word_length': 2.3229564900782815, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '567390', 'n_tokens_mistral': 5585, 'n_tokens_neox': 5384, 'n_words': 1826}