<commit_before>import os
from os.path import split
from functools import partial

import numpy as np
from scipy import sparse
from scipy.io import loadmat

from mypy import utils
# import matplotlib.pyplot as plt


base_dir = split(__file__)[0]
chan_path = os.path.join(base_dir, 'data', 'chan')


# read channel connectivity
# consider renaming to read_neighbours
def get_neighbours(captype):
    assert isinstance(captype, str), 'captype must be a string.'
    if os.path.exists(captype):
        # file path was given
        file_name = captype
    else:
        # cap type was given
        fls = [f for f in os.listdir(chan_path) if f.endswith('.mat') and
                '_neighbours' in f]
        good_file = [f for f in fls if captype in f]
        if len(good_file) > 0:
            file_name = os.path.join(chan_path, good_file[0])
        else:
            raise ValueError('Could not find specified cap type.')
    return loadmat(file_name, squeeze_me=True)['neighbours']


def construct_adjacency_matrix(ch_names, neighbours, sparse=False):
    # check input
    assert isinstance(ch_names, list), 'ch_names must be a list.'
    assert all(map(lambda x: isinstance(x, str), ch_names)), \
        'ch_names must be a list of strings'

    from scipy import sparse as sprs

    if isinstance(neighbours, str):
        neighbours = get_neighbours(neighbours)
    n_channels = len(ch_names)
    conn = np.zeros((n_channels, n_channels), dtype='bool')

    for ii, chan in enumerate(ch_names):
        ngb_ind = np.where(neighbours['label'] == chan)[0]

        # safty checks:
        if len(ngb_ind) == 0:
            raise ValueError('channel {} was not found in neighbours.'.format(
                             chan))
        elif len(ngb_ind) == 1:
            ngb_ind = ngb_ind[0]
        else:
            raise ValueError('found more than one neighbours entry for '
                             'channel name {}.'.format(chan))

        # find connections and fill up adjacency matrix
        connections = [ch_names.index(ch) for ch in neighbours['neighblabel']
                       [ngb_ind] if ch in ch_names]
        chan_ind = ch_names.index(chan)
        conn[chan_ind, connections] = True
    if sparse:
        return sprs.coo_matrix(conn)
    else:
        return conn


# - [ ] add edit option (runs in interactive mode only)
# - [ ] new lines should have one color
# - [x] 'random' is actually misleading - it follows colorcycle...
# another approach to random colors:
# plt.cm.viridis(np.linspace(0., 1., num=15) , alpha=0.5)
def plot_neighbours(inst, adj_matrix, color='gray', kind='3d'):
    '''Plot channel adjacency.

    Parameters
    ----------
    inst : mne Raw, Epochs or info
        mne-python data container
    adj_matrix : boolean numpy array
        Defines which channels are adjacent to each other.
    color : matplotlib color or 'random'
        Color to plot the web of adjacency relations with.

    Returns
    -------
    fig : matplotlib figure
        Figure.
    '''
    tps = utils.mne_types()
    from .viz import set_3d_axes_equal
    from mne.viz import plot_sensors
    assert isinstance(inst, (tps['raw'], tps['epochs'], tps['info']))
    info = utils.get_info(inst)

    if isinstance(adj_matrix, sparse.coo_matrix):
        adj_matrix = adj_matrix.todense()

    if adj_matrix.dtype == 'int':
        max_lw = 10.
        max_conn = adj_matrix.max()
        def get_lw():
            return adj_matrix[ch, n] / max_conn * max_lw
    elif adj_matrix.dtype == 'bool':<commit_msg>small fixes to plot_neighbours<commit_after>import os
from os.path import split
from functools import partial

import numpy as np
from scipy import sparse
from scipy.io import loadmat

from mypy import utils
# import matplotlib.pyplot as plt


base_dir = split(__file__)[0]
chan_path = os.path.join(base_dir, 'data', 'chan')


# read channel connectivity
# consider renaming to read_neighbours
def get_neighbours(captype):
    assert isinstance(captype, str), 'captype must be a string.'
    if os.path.exists(captype):
        # file path was given
        file_name = captype
    else:
        # cap type was given
        fls = [f for f in os.listdir(chan_path) if f.endswith('.mat') and
                '_neighbours' in f]
        good_file = [f for f in fls if captype in f]
        if len(good_file) > 0:
            file_name = os.path.join(chan_path, good_file[0])
        else:
            raise ValueError('Could not find specified cap type.')
    return loadmat(file_name, squeeze_me=True)['neighbours']


def construct_adjacency_matrix(ch_names, neighbours, sparse=False):
    # check input
    assert isinstance(ch_names, list), 'ch_names must be a list.'
    assert all(map(lambda x: isinstance(x, str), ch_names)), \
        'ch_names must be a list of strings'

    from scipy import sparse as sprs

    if isinstance(neighbours, str):
        neighbours = get_neighbours(neighbours)
    n_channels = len(ch_names)
    conn = np.zeros((n_channels, n_channels), dtype='bool')

    for ii, chan in enumerate(ch_names):
        ngb_ind = np.where(neighbours['label'] == chan)[0]

        # safty checks:
        if len(ngb_ind) == 0:
            raise ValueError('channel {} was not found in neighbours.'.format(
                             chan))
        elif len(ngb_ind) == 1:
            ngb_ind = ngb_ind[0]
        else:
            raise ValueError('found more than one neighbours entry for '
                             'channel name {}.'.format(chan))

        # find connections and fill up adjacency matrix
        connections = [ch_names.index(ch) for ch in neighbours['neighblabel']
                       [ngb_ind] if ch in ch_names]
        chan_ind = ch_names.index(chan)
        conn[chan_ind, connections] = True
    if sparse:
        return sprs.coo_matrix(conn)
    else:
        return conn


# - [ ] add edit option (runs in interactive mode only)
# - [ ] new lines should have one color
# - [x] 'random' is actually misleading - it follows colorcycle...
# another approach to random colors:
# plt.cm.viridis(np.linspace(0., 1., num=15) , alpha=0.5)
def plot_neighbours(inst, adj_matrix, color='gray', kind='3d'):
    '''Plot channel adjacency.

    Parameters
    ----------
    inst : mne Raw, Epochs or info
        mne-python data container
    adj_matrix : boolean numpy array
        Defines which channels are adjacent to each other.
    color : matplotlib color or 'random'
        Color to plot the web of adjacency relations with.

    Returns
    -------
    fig : matplotlib figure
        Figure.
    '''
    tps = utils.mne_types()
    from .viz import set_3d_axes_equal
    from mne.viz import plot_sensors
    assert isinstance(inst, (tps['raw'], tps['epochs'], tps['info']))
    info = utils.get_info(inst)

    if isinstance(adj_matrix, sparse.coo_matrix):
        adj_matrix = adj_matrix.todense()

    if adj_matrix.dtype == 'int':
        max_lw = 5.
        max_conn = adj_matrix.max()
        def get_lw():
            return adj_matrix[ch, n] / max_conn * max_lw
    elif adj_matrix.dtype == 'bool' or (np.unique(adj_matrix) ==
                                        np.array([0., 1.])).all():
{'fraction_non_alphanumeric': 0.10359672267740591, 'fraction_numerical': 0.004860436050548535, 'mean_word_length': 2.489341085271318, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2919983', 'n_tokens_mistral': 2310, 'n_tokens_neox': 2219, 'n_words': 678}