How to use the mne.utils._validate_type function in mne

To help you get started, we’ve selected a few mne examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mne-tools / mne-python / mne / viz / _3d.py View on Github external
idx = np.argmax(dipole.gof)
    elif idx == 'amplitude':
        idx = np.argmax(np.abs(dipole.amplitude))
    else:
        idx = _ensure_int(idx, 'idx', 'an int or one of ["gof", "amplitude"]')

    vox, ori, pos, data = _get_dipole_loc(
        dipole, trans, subject, subjects_dir, coord_frame)

    dims = len(data)  # Symmetric size assumed.
    dd = dims // 2
    if ax is None:
        fig = plt.figure()
        ax = Axes3D(fig)
    else:
        _validate_type(ax, Axes3D, "ax", "Axes3D")
        fig = ax.get_figure()

    gridx, gridy = np.meshgrid(np.linspace(-dd, dd, dims),
                               np.linspace(-dd, dd, dims), indexing='ij')
    params = {'ax': ax, 'data': data, 'idx': idx, 'dipole': dipole,
              'vox': vox, 'gridx': gridx, 'gridy': gridy,
              'ori': ori, 'coord_frame': coord_frame,
              'show_all': show_all, 'pos': pos,
              'color': color, 'highlight_color': highlight_color}
    _plot_dipole(**params)
    ax.view_init(elev=30, azim=-140)

    callback_func = partial(_dipole_changed, params=params)
    fig.canvas.mpl_connect('scroll_event', callback_func)
    fig.canvas.mpl_connect('key_press_event', callback_func)
github mne-tools / mne-python / mne / viz / evoked.py View on Github external
+-------------+----------------+------------------------------------------+
    """
    import matplotlib.pyplot as plt
    from ..evoked import Evoked, _check_evokeds_ch_names_times

    # build up evokeds into a dict, if it's not already
    if isinstance(evokeds, Evoked):
        evokeds = [evokeds]
    if isinstance(evokeds, (list, tuple)):
        evokeds = {str(idx + 1): evk for idx, evk in enumerate(evokeds)}
    if not isinstance(evokeds, dict):
        raise TypeError('"evokeds" must be a dict, list, or instance of '
                        'mne.Evoked; got {}'.format(type(evokeds).__name__))
    evokeds = deepcopy(evokeds)  # avoid modifying dict outside function scope
    for cond, evoked in evokeds.items():
        _validate_type(cond, 'str', 'Conditions')
        if isinstance(evoked, Evoked):
            evokeds[cond] = [evoked]  # wrap singleton evokeds in a list
        for evk in evokeds[cond]:
            _validate_type(evk, Evoked, 'All evokeds entries ', 'Evoked')
    # ensure same channels and times across all evokeds
    all_evoked = sum(evokeds.values(), [])
    _check_evokeds_ch_names_times(all_evoked)
    del all_evoked

    # get some representative info
    conditions = list(evokeds)
    one_evoked = evokeds[conditions[0]][0]
    times = one_evoked.times
    info = one_evoked.info
    sphere = _check_sphere(sphere, info)
    tmin, tmax = times[0], times[-1]
github mne-tools / mne-python / mne / viz / ica.py View on Github external
fig : list
        List of matplotlib figures.

    Notes
    -----
    .. versionadded:: 0.13
    """
    from ..io.base import BaseRaw
    from ..epochs import BaseEpochs
    from ..preprocessing import ICA
    from ..io import RawArray

    # input checks and defaults
    # -------------------------
    _validate_type(inst, (BaseRaw, BaseEpochs), "inst", "Raw or Epochs")
    _validate_type(ica, ICA, "ica", "ICA")
    if isinstance(plot_std, bool):
        num_std = 1. if plot_std else 0.
    elif isinstance(plot_std, (float, int)):
        num_std = plot_std
        plot_std = True
    else:
        raise ValueError('plot_std has to be a bool, int or float, '
                         'got %s instead' % type(plot_std))

    # if no picks given - plot the first 5 components
    limit = min(5, ica.n_components_) if picks is None else len(ica.ch_names)
    picks = _picks_to_idx(ica.info, picks, 'all')[:limit]
    if axes is None:
        fig, axes = _create_properties_layout(figsize=figsize)
    else:
        if len(picks) > 1:
github mne-tools / mne-python / mne / simulation / evoked.py View on Github external
def _add_noise(inst, cov, iir_filter, random_state, allow_subselection=True):
    """Add noise, possibly with channel subselection."""
    from ..cov import Covariance
    from ..io import BaseRaw
    from ..epochs import BaseEpochs
    from ..evoked import Evoked
    _validate_type(cov, Covariance, 'cov')
    _validate_type(inst, (BaseRaw, BaseEpochs, Evoked),
                   'inst', 'Raw, Epochs, or Evoked')
    _check_preload(inst, 'Adding noise')
    data = inst._data
    assert data.ndim in (2, 3)
    if data.ndim == 2:
        data = data[np.newaxis]
    # Subselect if necessary
    info = inst.info
    info._check_consistency()
    picks = gen_picks = slice(None)
    if allow_subselection:
        use_chs = list(set(info['ch_names']) & set(cov['names']))
        picks = np.where(np.in1d(info['ch_names'], use_chs))[0]
        logger.info('Adding noise to %d/%d channels (%d channels in cov)'
                    % (len(picks), len(info['chs']), len(cov['names'])))
github mne-tools / mne-python / mne / channels / channels.py View on Github external
from ..cov import Covariance
    from ..io.base import BaseRaw
    from ..io.meas_info import Info
    from ..epochs import BaseEpochs
    from ..evoked import Evoked
    from ..forward import Forward
    from ..time_frequency import _BaseTFR, CrossSpectralDensity

    # Instances need to have a `ch_names` attribute and a `pick_channels`
    # method that supports `ordered=True`.
    allowed_types = (BaseRaw, BaseEpochs, Evoked, _BaseTFR, Forward,
                     Covariance, CrossSpectralDensity, Info)
    allowed_types_str = ("Raw, Epochs, Evoked, TFR, Forward, Covariance, "
                         "CrossSpectralDensity or Info")
    for inst in instances:
        _validate_type(inst, allowed_types, "Instances to be modified",
                       allowed_types_str)

    chan_template = instances[0].ch_names
    logger.info('Identifying common channels ...')
    channels = [set(inst.ch_names) for inst in instances]
    common_channels = set(chan_template).intersection(*channels)
    all_channels = set(chan_template).union(*channels)
    dropped = list(set(all_channels - common_channels))

    # Preserve the order of chan_template
    order = np.argsort([chan_template.index(ch) for ch in common_channels])
    common_channels = np.array(list(common_channels))[order].tolist()

    # Update all instances to match the common_channels list
    reordered = False
    equalized_instances = []
github mne-tools / mne-python / mne / channels / montage.py View on Github external
The measurement info to update.
    %(montage)s
    raise_if_subset: bool
        If True, ValueError will be raised when montage.ch_names is a
        subset of info['ch_names']. This parameter was introduced for
        backward compatibility when set to False.

        Defaults to False in 0.19, it will change to default to True in
        0.20, and will be removed in 0.21.

        .. versionadded: 0.19
    Notes
    -----
    This function will change the info variable in place.
    """
    _validate_type(montage, types=(DigMontage, type(None), str),
                   item_name='montage')
    _set_montage_deprecation_helper(montage, None, None, raise_if_subset)

    if isinstance(montage, str):  # load builtin montage
        _check_option('montage', montage, _BUILT_IN_MONTAGES)
        montage = make_standard_montage(montage)

    if isinstance(montage, DigMontage):
        _mnt = _get_montage_in_head(montage)

        def _backcompat_value(pos, ref_pos):
            if any(np.isnan(pos)):
                return np.full(6, np.nan)
            else:
                return np.concatenate((pos, ref_pos))
github mne-tools / mne-python / mne / viz / evoked.py View on Github external
# build up evokeds into a dict, if it's not already
    if isinstance(evokeds, Evoked):
        evokeds = [evokeds]
    if isinstance(evokeds, (list, tuple)):
        evokeds = {str(idx + 1): evk for idx, evk in enumerate(evokeds)}
    if not isinstance(evokeds, dict):
        raise TypeError('"evokeds" must be a dict, list, or instance of '
                        'mne.Evoked; got {}'.format(type(evokeds).__name__))
    evokeds = deepcopy(evokeds)  # avoid modifying dict outside function scope
    for cond, evoked in evokeds.items():
        _validate_type(cond, 'str', 'Conditions')
        if isinstance(evoked, Evoked):
            evokeds[cond] = [evoked]  # wrap singleton evokeds in a list
        for evk in evokeds[cond]:
            _validate_type(evk, Evoked, 'All evokeds entries ', 'Evoked')
    # ensure same channels and times across all evokeds
    all_evoked = sum(evokeds.values(), [])
    _check_evokeds_ch_names_times(all_evoked)
    del all_evoked

    # get some representative info
    conditions = list(evokeds)
    one_evoked = evokeds[conditions[0]][0]
    times = one_evoked.times
    info = one_evoked.info
    sphere = _check_sphere(sphere, info)
    tmin, tmax = times[0], times[-1]
    # set some defaults
    if ylim is None:
        ylim = dict()
    if vlines == 'auto':
github mne-tools / mne-python / mne / bem.py View on Github external
.. versionadded:: 0.19
    %(verbose)s

    Returns
    -------
    dig : array, shape (n_pts, 3)
        The digitization points (in head coordinates) to use for fitting.

    Notes
    -----
    This will exclude digitization locations that have ``z < 0 and y > 0``,
    i.e. points on the nose and below the nose on the face.

    .. versionadded:: 0.14
    """
    _validate_type(info, "info")
    if info['dig'] is None:
        raise RuntimeError('Cannot fit headshape without digitization '
                           ', info["dig"] is None')
    if isinstance(dig_kinds, str):
        if dig_kinds == 'auto':
            # try "extra" first
            try:
                return get_fitting_dig(info, 'extra')
            except ValueError:
                pass
            return get_fitting_dig(info, ('extra', 'eeg'))
        else:
            dig_kinds = (dig_kinds,)
    # convert string args to ints (first make dig_kinds mutable in case tuple)
    dig_kinds = list(dig_kinds)
    for di, d in enumerate(dig_kinds):
github mne-tools / mne-python / mne / simulation / evoked.py View on Github external
def _add_noise(inst, cov, iir_filter, random_state, allow_subselection=True):
    """Add noise, possibly with channel subselection."""
    from ..cov import Covariance
    from ..io import BaseRaw
    from ..epochs import BaseEpochs
    from ..evoked import Evoked
    _validate_type(cov, Covariance, 'cov')
    _validate_type(inst, (BaseRaw, BaseEpochs, Evoked),
                   'inst', 'Raw, Epochs, or Evoked')
    _check_preload(inst, 'Adding noise')
    data = inst._data
    assert data.ndim in (2, 3)
    if data.ndim == 2:
        data = data[np.newaxis]
    # Subselect if necessary
    info = inst.info
    info._check_consistency()
    picks = gen_picks = slice(None)
    if allow_subselection:
        use_chs = list(set(info['ch_names']) & set(cov['names']))
        picks = np.where(np.in1d(info['ch_names'], use_chs))[0]
        logger.info('Adding noise to %d/%d channels (%d channels in cov)'
                    % (len(picks), len(info['chs']), len(cov['names'])))
        info = pick_info(inst.info, picks)
github mne-tools / mne-python / mne / forward / forward.py View on Github external
----------
    fwds : list of Forward
        Forward solutions to average. Each entry (dict) should be a
        forward solution.
    weights : array | None
        Weights to apply to each forward solution in averaging. If None,
        forward solutions will be equally weighted. Weights must be
        non-negative, and will be adjusted to sum to one.

    Returns
    -------
    fwd : Forward
        The averaged forward solution.
    """
    # check for fwds being a list
    _validate_type(fwds, list, "fwds")
    if not len(fwds) > 0:
        raise ValueError('fwds must not be empty')

    # check weights
    if weights is None:
        weights = np.ones(len(fwds))
    weights = np.asanyarray(weights)  # in case it's a list, convert it
    if not np.all(weights >= 0):
        raise ValueError('weights must be non-negative')
    if not len(weights) == len(fwds):
        raise ValueError('weights must be None or the same length as fwds')
    w_sum = np.sum(weights)
    if not w_sum > 0:
        raise ValueError('weights cannot all be zero')
    weights /= w_sum