Ejemplo n.º 1
0
def _plot_glm_contrast_topo(inst, contrast, figsize=(12, 7), sphere=None):

    info = deepcopy(inst if isinstance(inst, Info) else inst.info)

    # Extract types. One subplot is created per type (hbo/hbr)
    types = np.unique(_get_channel_types(info))

    # Extract values to plot and rescale to uM
    estimates = contrast.effect[0]
    estimates = estimates * 1e6

    # Create subplots for figures
    fig, axes = plt.subplots(nrows=1, ncols=len(types), figsize=figsize)
    # Create limits for colorbar
    vmax = np.max(np.abs(estimates))
    vmin = vmax * -1.
    cmap = mpl.cm.RdBu_r
    norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)

    for t_idx, t in enumerate(types):

        estmrg, pos, chs, sphere = _handle_overlaps(info, t, sphere, estimates)

        # Deal with case when only a single chroma is available
        if len(types) == 1:
            ax = axes
        else:
            ax = axes[t_idx]

        # Plot the topomap
        plot_topomap(estmrg,
                     pos,
                     extrapolate='local',
                     names=chs,
                     vmin=vmin,
                     vmax=vmax,
                     cmap=cmap,
                     axes=ax,
                     show=False,
                     sphere=sphere)
        # Sets axes title
        if t == 'hbo':
            ax.set_title('Oxyhaemoglobin')
        elif t == 'hbr':
            ax.set_title('Deoxyhaemoglobin')
        else:
            ax.set_title(t)

    # Create a single colorbar for all types based on limits above
    ax1_divider = make_axes_locatable(ax)
    cax1 = ax1_divider.append_axes("right", size="7%", pad="2%")
    cbar = mpl.colorbar.ColorbarBase(cax1,
                                     cmap=cmap,
                                     norm=norm,
                                     orientation='vertical')
    cbar.set_label('Contrast Effect', rotation=270)

    return fig
Ejemplo n.º 2
0
def test_pick_chpi():
    """Test picking cHPI."""
    # Make sure we don't mis-classify cHPI channels
    info = read_info(op.join(io_dir, 'tests', 'data', 'test_chpi_raw_sss.fif'))
    _assert_channel_types(info)
    channel_types = _get_channel_types(info)
    assert 'chpi' in channel_types
    assert 'seeg' not in channel_types
    assert 'ecog' not in channel_types
Ejemplo n.º 3
0
def test_cov_rank_estimation(rank_method, proj, meg):
    """Test cov rank estimation."""
    # Test that our rank estimation works properly on a simple case
    evoked = read_evokeds(ave_fname,
                          condition=0,
                          baseline=(None, 0),
                          proj=False)
    cov = read_cov(cov_fname)
    ch_names = [
        ch for ch in evoked.info['ch_names']
        if '053' not in ch and ch.startswith('EEG')
    ]
    cov = prepare_noise_cov(cov, evoked.info, ch_names, None)
    assert cov['eig'][0] <= 1e-25  # avg projector should set this to zero
    assert (cov['eig'][1:] > 1e-16).all()  # all else should be > 0

    # Now do some more comprehensive tests
    raw_sample = read_raw_fif(raw_fname)
    assert not _has_eeg_average_ref_proj(raw_sample.info['projs'])

    raw_sss = read_raw_fif(hp_fif_fname)
    assert not _has_eeg_average_ref_proj(raw_sss.info['projs'])
    raw_sss.add_proj(compute_proj_raw(raw_sss, meg=meg))

    cov_sample = compute_raw_covariance(raw_sample)
    cov_sample_proj = compute_raw_covariance(raw_sample.copy().apply_proj())

    cov_sss = compute_raw_covariance(raw_sss)
    cov_sss_proj = compute_raw_covariance(raw_sss.copy().apply_proj())

    picks_all_sample = pick_types(raw_sample.info, meg=True, eeg=True)
    picks_all_sss = pick_types(raw_sss.info, meg=True, eeg=True)

    info_sample = pick_info(raw_sample.info, picks_all_sample)
    picks_stack_sample = [('eeg', pick_types(info_sample, meg=False,
                                             eeg=True))]
    picks_stack_sample += [('meg', pick_types(info_sample, meg=True))]
    picks_stack_sample += [('all', pick_types(info_sample, meg=True,
                                              eeg=True))]

    info_sss = pick_info(raw_sss.info, picks_all_sss)
    picks_stack_somato = [('eeg', pick_types(info_sss, meg=False, eeg=True))]
    picks_stack_somato += [('meg', pick_types(info_sss, meg=True))]
    picks_stack_somato += [('all', pick_types(info_sss, meg=True, eeg=True))]

    iter_tests = list(
        itt.product(
            [(cov_sample, picks_stack_sample, info_sample),
             (cov_sample_proj, picks_stack_sample, info_sample),
             (cov_sss, picks_stack_somato, info_sss),
             (cov_sss_proj, picks_stack_somato, info_sss)],  # sss
            [dict(mag=1e15, grad=1e13, eeg=1e6)],
        ))

    for (cov, picks_list, iter_info), scalings in iter_tests:
        rank = compute_rank(cov, rank_method, scalings, iter_info, proj=proj)
        rank['all'] = sum(rank.values())
        for ch_type, picks in picks_list:

            this_info = pick_info(iter_info, picks)

            # compute subset of projs, active and inactive
            n_projs_applied = sum(proj['active'] and len(
                set(proj['data']['col_names'])
                & set(this_info['ch_names'])) > 0 for proj in cov['projs'])
            n_projs_info = sum(
                len(
                    set(proj['data']['col_names'])
                    & set(this_info['ch_names'])) > 0
                for proj in this_info['projs'])

            # count channel types
            ch_types = _get_channel_types(this_info)
            n_eeg, n_mag, n_grad = [
                ch_types.count(k) for k in ['eeg', 'mag', 'grad']
            ]
            n_meg = n_mag + n_grad
            has_sss = (n_meg > 0 and len(this_info['proc_history']) > 0)
            if has_sss:
                n_meg = _get_rank_sss(this_info)

            expected_rank = n_meg + n_eeg
            if rank_method is None:
                if meg == 'combined' or not has_sss:
                    if proj:
                        expected_rank -= n_projs_info
                    else:
                        expected_rank -= n_projs_applied
            else:
                # XXX for now it just uses the total count
                assert rank_method == 'info'
                if proj:
                    expected_rank -= n_projs_info

            assert rank[ch_type] == expected_rank
Ejemplo n.º 4
0
def _plot_glm_topo(inst,
                   glm_estimates,
                   design_matrix,
                   requested_conditions=None,
                   axes=None,
                   vmin=None,
                   vmax=None,
                   colorbar=True,
                   figsize=(12, 7),
                   sphere=None):

    info = deepcopy(inst if isinstance(inst, Info) else inst.info)

    if not (info.ch_names == list(glm_estimates.keys())):
        if len(info.ch_names) < len(list(glm_estimates.keys())):
            warn("Reducing GLM results to match MNE data")
            glm_estimates = {a: glm_estimates[a] for a in info.ch_names}
        else:
            raise RuntimeError('MNE data structure does not match regression '
                               f'results. Raw = {len(info.ch_names)}. '
                               f'GLM = {len(list(glm_estimates.keys()))}')

    estimates = np.zeros((len(glm_estimates), len(design_matrix.columns)))

    for idx, name in enumerate(glm_estimates.keys()):
        estimates[idx, :] = glm_estimates[name].theta.T

    types = np.unique(_get_channel_types(info))

    if requested_conditions is None:
        requested_conditions = design_matrix.columns
    requested_conditions = [
        x for x in design_matrix.columns if x in requested_conditions
    ]

    # Plotting setup
    if axes is None:
        fig, axes = plt.subplots(nrows=len(types),
                                 ncols=len(requested_conditions),
                                 figsize=figsize)

    estimates = estimates[:, [
        c in requested_conditions for c in design_matrix.columns
    ]]

    estimates = estimates * 1e6
    design_matrix = design_matrix[requested_conditions]

    if vmax is None:
        vmax = np.max(np.abs(estimates))
    if vmin is None:
        vmin = vmax * -1.
    cmap = mpl.cm.RdBu_r
    norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)

    for t_idx, t in enumerate(types):

        estmrg, pos, chs, sphere = _handle_overlaps(info, t, sphere, estimates)

        for idx, label in enumerate(design_matrix.columns):
            if label in requested_conditions:

                # Deal with case when only a single
                # chroma or condition is available
                if (len(requested_conditions) == 1) & (len(types) == 1):
                    ax = axes
                elif (len(requested_conditions) == 1) & (len(types) > 1):
                    ax = axes[t_idx]
                elif (len(requested_conditions) > 1) & (len(types) == 1):
                    ax = axes[idx]
                else:
                    ax = axes[t_idx, idx]

                plot_topomap(estmrg[:, idx],
                             pos,
                             extrapolate='local',
                             names=chs,
                             vmin=vmin,
                             vmax=vmax,
                             cmap=cmap,
                             axes=ax,
                             show=False,
                             sphere=sphere)
                ax.set_title(label)

        if colorbar:
            ax1_divider = make_axes_locatable(ax)
            cax1 = ax1_divider.append_axes("right", size="7%", pad="2%")
            cbar = mpl.colorbar.ColorbarBase(cax1,
                                             cmap=cmap,
                                             norm=norm,
                                             orientation='vertical')
            cbar.set_label('Haemoglobin (uM)', rotation=270)

    return _get_fig_from_axes(axes)