Example #1
0
def test_plot_sparse_source_estimates():
    """Test plotting of (sparse) source estimates
    """
    # dense version
    vertices = [s['vertno'] for s in sample_src]
    n_time = 5
    n_verts = sum(len(v) for v in vertices)
    stc_data = np.zeros((n_verts * n_time))
    stc_data[(np.random.rand(20) * n_verts * n_time).astype(int)] = 1
    stc_data.shape = (n_verts, n_time)
    stc = SourceEstimate(stc_data, vertices, 1, 1)
    colormap = mne_analyze_colormap(format='matplotlib')
    # don't really need to test matplotlib method since it's not used now...
    colormap = mne_analyze_colormap()
    plot_source_estimates(stc, 'sample', colormap=colormap)

    # now do sparse version
    vertices = sample_src[0]['vertno']
    n_verts = len(vertices)
    stc_data = np.zeros((n_verts * n_time))
    stc_data[(np.random.rand(20) * n_verts * n_time).astype(int)] = 1
    stc_data.shape = (n_verts, n_time)
    inds = np.where(np.any(stc_data, axis=1))[0]
    stc_data = stc_data[inds]
    vertices = vertices[inds]
    stc = SourceEstimate(stc_data, vertices, 1, 1)
    plot_sparse_source_estimates(sample_src, stc, bgcolor=(1, 1, 1),
                                 opacity=0.5, high_resolution=True)
Example #2
0
def test_plot_sparse_source_estimates():
    """Test plotting of (sparse) source estimates
    """
    # dense version
    vertices = [s["vertno"] for s in sample_src]
    n_time = 5
    n_verts = sum(len(v) for v in vertices)
    stc_data = np.zeros((n_verts * n_time))
    stc_data[(np.random.rand(20) * n_verts * n_time).astype(int)] = 1
    stc_data.shape = (n_verts, n_time)
    stc = SourceEstimate(stc_data, vertices, 1, 1)
    colormap = mne_analyze_colormap(format="matplotlib")
    # don't really need to test matplotlib method since it's not used now...
    colormap = mne_analyze_colormap()
    plot_source_estimates(
        stc, "sample", colormap=colormap, config_opts={"background": (1, 1, 0)}, subjects_dir=subjects_dir
    )
    assert_raises(RuntimeError, plot_source_estimates, stc, "sample", figure="foo", hemi="both")

    # now do sparse version
    vertices = sample_src[0]["vertno"]
    n_verts = len(vertices)
    stc_data = np.zeros((n_verts * n_time))
    stc_data[(np.random.rand(20) * n_verts * n_time).astype(int)] = 1
    stc_data.shape = (n_verts, n_time)
    inds = np.where(np.any(stc_data, axis=1))[0]
    stc_data = stc_data[inds]
    vertices = vertices[inds]
    stc = SourceEstimate(stc_data, vertices, 1, 1)
    plot_sparse_source_estimates(sample_src, stc, bgcolor=(1, 1, 1), opacity=0.5, high_resolution=True)
Example #3
0
def test_plot_sparse_source_estimates():
    """Test plotting of (sparse) source estimates
    """
    sample_src = read_source_spaces(op.join(data_dir, 'subjects', 'sample',
                                            'bem', 'sample-oct-6-src.fif'))

    # dense version
    vertices = [s['vertno'] for s in sample_src]
    n_time = 5
    n_verts = sum(len(v) for v in vertices)
    stc_data = np.zeros((n_verts * n_time))
    stc_data[(np.random.rand(20) * n_verts * n_time).astype(int)] = 1
    stc_data.shape = (n_verts, n_time)
    stc = SourceEstimate(stc_data, vertices, 1, 1)
    colormap = mne_analyze_colormap(format='matplotlib')
    # don't really need to test matplotlib method since it's not used now...
    colormap = mne_analyze_colormap()
    plot_source_estimates(stc, 'sample', colormap=colormap,
                          config_opts={'background': (1, 1, 0)},
                          subjects_dir=subjects_dir, colorbar=True)
    assert_raises(TypeError, plot_source_estimates, stc, 'sample',
                  figure='foo', hemi='both')

    # now do sparse version
    vertices = sample_src[0]['vertno']
    n_verts = len(vertices)
    stc_data = np.zeros((n_verts * n_time))
    stc_data[(np.random.rand(20) * n_verts * n_time).astype(int)] = 1
    stc_data.shape = (n_verts, n_time)
    inds = np.where(np.any(stc_data, axis=1))[0]
    stc_data = stc_data[inds]
    vertices = [vertices[inds], np.empty(0, dtype=np.int)]
    stc = SourceEstimate(stc_data, vertices, 1, 1)
    plot_sparse_source_estimates(sample_src, stc, bgcolor=(1, 1, 1),
                                 opacity=0.5, high_resolution=True)
Example #4
0
def test_plot_sparse_source_estimates():
    """Test plotting of (sparse) source estimates
    """
    sample_src = read_source_spaces(op.join(data_dir, 'subjects', 'sample',
                                            'bem', 'sample-oct-6-src.fif'))

    # dense version
    vertices = [s['vertno'] for s in sample_src]
    n_time = 5
    n_verts = sum(len(v) for v in vertices)
    stc_data = np.zeros((n_verts * n_time))
    stc_data[(np.random.rand(20) * n_verts * n_time).astype(int)] = 1
    stc_data.shape = (n_verts, n_time)
    stc = SourceEstimate(stc_data, vertices, 1, 1)
    colormap = mne_analyze_colormap(format='matplotlib')
    # don't really need to test matplotlib method since it's not used now...
    colormap = mne_analyze_colormap()
    plot_source_estimates(stc, 'sample', colormap=colormap,
                          config_opts={'background': (1, 1, 0)},
                          subjects_dir=subjects_dir, colorbar=True)
    assert_raises(TypeError, plot_source_estimates, stc, 'sample',
                  figure='foo', hemi='both')

    # now do sparse version
    vertices = sample_src[0]['vertno']
    inds = [111, 333]
    stc_data = np.zeros((len(inds), n_time))
    stc_data[0, 1] = 1.
    stc_data[1, 4] = 2.
    vertices = [vertices[inds], np.empty(0, dtype=np.int)]
    stc = SourceEstimate(stc_data, vertices, 1, 1)
    plot_sparse_source_estimates(sample_src, stc, bgcolor=(1, 1, 1),
                                 opacity=0.5, high_resolution=False)
Example #5
0
def test_process_clim_round_trip():
    """Test basic input-output support."""
    # With some negative data
    out = _process_clim('auto', 'auto', True, -1.)
    want = dict(
        colormap=mne_analyze_colormap([0, 0.5, 1], 'matplotlib'),
        clim=dict(kind='value', pos_lims=[1, 1, 1]),
        transparent=True,
    )
    _assert_mapdata_equal(out, want)
    out2 = _process_clim(**out)
    _assert_mapdata_equal(out, out2)
    _linearize_map(out)  # smoke test
    ticks = _get_map_ticks(out)
    assert_allclose(ticks, [-1, 0, 1])

    # With some positive data
    out = _process_clim('auto', 'auto', True, 1.)
    want = dict(
        colormap=plt.get_cmap('hot'),
        clim=dict(kind='value', lims=[1, 1, 1]),
        transparent=True,
    )
    _assert_mapdata_equal(out, want)
    out2 = _process_clim(**out)
    _assert_mapdata_equal(out, out2)
    _linearize_map(out)
    ticks = _get_map_ticks(out)
    assert_allclose(ticks, [1])

    # With some actual inputs
    clim = dict(kind='value', pos_lims=[0, 0.5, 1])
    out = _process_clim(clim, 'auto', True)
    want = dict(colormap=mne_analyze_colormap([0, 0.5, 1], 'matplotlib'),
                clim=clim,
                transparent=True)
    _assert_mapdata_equal(out, want)
    _linearize_map(out)
    ticks = _get_map_ticks(out)
    assert_allclose(ticks, [-1, -0.5, 0, 0.5, 1])

    clim = dict(kind='value', pos_lims=[0.25, 0.5, 1])
    out = _process_clim(clim, 'auto', True)
    want = dict(colormap=mne_analyze_colormap([0, 0.5, 1], 'matplotlib'),
                clim=clim,
                transparent=True)
    _assert_mapdata_equal(out, want)
    _linearize_map(out)
    ticks = _get_map_ticks(out)
    assert_allclose(ticks, [-1, -0.5, -0.25, 0, 0.25, 0.5, 1])
Example #6
0
def test_plot_topo_image_epochs():
    """Test plotting of epochs image topography."""
    title = 'ERF images - MNE sample data'
    epochs = _get_epochs()
    epochs.load_data()
    cmap = mne_analyze_colormap(format='matplotlib')
    data_min = epochs._data.min()
    plt.close('all')
    fig = plot_topo_image_epochs(epochs,
                                 sigma=0.5,
                                 vmin=-200,
                                 vmax=200,
                                 colorbar=True,
                                 title=title,
                                 cmap=cmap)
    assert epochs._data.min() == data_min
    num_figures_before = len(plt.get_fignums())
    _fake_click(fig, fig.axes[0], (0.08, 0.64))
    assert num_figures_before + 1 == len(plt.get_fignums())
    # test for auto-showing a colorbar when only 1 sensor type
    ep = epochs.copy().pick_types(meg=False, eeg=True)
    fig = plot_topo_image_epochs(ep,
                                 vmin=None,
                                 vmax=None,
                                 colorbar=None,
                                 cmap=cmap)
    ax = [x for x in fig.get_children() if isinstance(x, matplotlib.axes.Axes)]
    qm_cmap = [
        y.cmap for x in ax for y in x.get_children()
        if isinstance(y, matplotlib.collections.QuadMesh)
    ]
    assert qm_cmap[0] is cmap
    plt.close('all')
def test_plot_topo_image_epochs():
    """Test plotting of epochs image topography."""
    import matplotlib.pyplot as plt
    title = 'ERF images - MNE sample data'
    epochs = _get_epochs()
    cmap = mne_analyze_colormap(format='matplotlib')
    fig = plot_topo_image_epochs(epochs, sigma=0.5, vmin=-200, vmax=200,
                                 colorbar=True, title=title, cmap=cmap)
    _fake_click(fig, fig.axes[2], (0.08, 0.64))
    plt.close('all')
def test_plot_topo_image_epochs():
    """Test plotting of epochs image topography
    """
    import matplotlib.pyplot as plt
    title = 'ERF images - MNE sample data'
    epochs = _get_epochs()
    cmap = mne_analyze_colormap(format='matplotlib')
    plot_topo_image_epochs(epochs, sigma=0.5, vmin=-200, vmax=200,
                           colorbar=True, title=title, cmap=cmap)
    plt.close('all')
def plot_stc_time_point(stc, subject, limits=[5, 10, 15], time_index=0,
                        surf='inflated', measure='dSPM', subjects_dir=None):
    """Plot a time instant from a SourceEstimate using matplotlib

    The same could be done with mayavi using proper 3D.

    Parameters
    ----------
    stc : instance of SourceEstimate
        The SourceEstimate to plot.
    subject : string
        The subject name (only needed if surf is a string).
    time_index : int
        Time index to plot.
    surf : str, or instance of surfaces
        Surface to use (e.g., 'inflated' or 'white'), or pre-loaded surfaces.
    measure : str
        The label for the colorbar. None turns the colorbar off.
    subjects_dir : str, or None
        Path to the SUBJECTS_DIR. If None, the path is obtained by using
        the environment variable SUBJECTS_DIR.
    """
    subjects_dir = get_subjects_dir(subjects_dir)
    pl.figure(facecolor='k', figsize=(8, 5))
    hemis = ['lh', 'rh']
    if isinstance(surf, str):
        surf = [read_surface(op.join(subjects_dir, subject, 'surf',
                                     '%s.%s' % (h, surf))) for h in hemis]
    my_cmap = mne_analyze_colormap(limits)
    for hi, h in enumerate(hemis):
        coords = surf[hi][0][stc.vertno[hi]]
        if hi == 0:
            vals = stc_all_cluster_vis.lh_data[:, time_index]
        else:
            vals = stc_all_cluster_vis.rh_data[:, time_index]
        ax = pl.subplot(1, 2, 1 - hi, axis_bgcolor='none')
        pl.tick_params(labelbottom='off', labelleft='off')
        flipper = -1 if hi == 1 else 1
        sc = ax.scatter(flipper * coords[:, 1], coords[:, 2], c=vals,
                        vmin=-limits[2], vmax=limits[2], cmap=my_cmap,
                        edgecolors='none', s=5)
        ax.set_aspect('equal')
        pl.axis('off')
    try:
        pl.tight_layout(0)
    except:
        pass
    if measure is not None:
        cax = pl.axes([0.85, 0.15, 0.025, 0.15], axisbg='k')
        cb = pl.colorbar(sc, cax, ticks=[-limits[2], 0, limits[2]])
        cb.set_label(measure, color='w')
    pl.setp(pl.getp(cb.ax, 'yticklabels'), color='w')
    pl.draw()
    pl.show()
Example #10
0
def test_plot_sparse_source_estimates():
    """Test plotting of (sparse) source estimates
    """
    # dense version
    vertices = [s['vertno'] for s in sample_src]
    n_time = 5
    n_verts = sum(len(v) for v in vertices)
    stc_data = np.zeros((n_verts * n_time))
    stc_data[(np.random.rand(20) * n_verts * n_time).astype(int)] = 1
    stc_data.shape = (n_verts, n_time)
    stc = SourceEstimate(stc_data, vertices, 1, 1)
    colormap = mne_analyze_colormap(format='matplotlib')
    # don't really need to test matplotlib method since it's not used now...
    colormap = mne_analyze_colormap()
    plot_source_estimates(stc,
                          'sample',
                          colormap=colormap,
                          config_opts={'background': (1, 1, 0)})
    assert_raises(RuntimeError,
                  plot_source_estimates,
                  stc,
                  'sample',
                  figure='foo',
                  hemi='both')

    # now do sparse version
    vertices = sample_src[0]['vertno']
    n_verts = len(vertices)
    stc_data = np.zeros((n_verts * n_time))
    stc_data[(np.random.rand(20) * n_verts * n_time).astype(int)] = 1
    stc_data.shape = (n_verts, n_time)
    inds = np.where(np.any(stc_data, axis=1))[0]
    stc_data = stc_data[inds]
    vertices = vertices[inds]
    stc = SourceEstimate(stc_data, vertices, 1, 1)
    plot_sparse_source_estimates(sample_src,
                                 stc,
                                 bgcolor=(1, 1, 1),
                                 opacity=0.5,
                                 high_resolution=True)
Example #11
0
def test_plot_topo_image_epochs():
    """Test plotting of epochs image topography."""
    import matplotlib.pyplot as plt
    title = 'ERF images - MNE sample data'
    epochs = _get_epochs()
    epochs.load_data()
    cmap = mne_analyze_colormap(format='matplotlib')
    data_min = epochs._data.min()
    fig = plot_topo_image_epochs(epochs, sigma=0.5, vmin=-200, vmax=200,
                                 colorbar=True, title=title, cmap=cmap)
    assert_equal(epochs._data.min(), data_min)
    _fake_click(fig, fig.axes[2], (0.08, 0.64))
    plt.close('all')
Example #12
0
def test_plot_topo_image_epochs():
    """Test plotting of epochs image topography."""
    title = 'ERF images - MNE sample data'
    epochs = _get_epochs()
    epochs.load_data()
    cmap = mne_analyze_colormap(format='matplotlib')
    data_min = epochs._data.min()
    plt.close('all')
    fig = plot_topo_image_epochs(epochs, sigma=0.5, vmin=-200, vmax=200,
                                 colorbar=True, title=title, cmap=cmap)
    assert epochs._data.min() == data_min
    num_figures_before = len(plt.get_fignums())
    _fake_click(fig, fig.axes[0], (0.08, 0.64))
    assert num_figures_before + 1 == len(plt.get_fignums())
    plt.close('all')
Example #13
0
def test_plot_topo_image_epochs():
    """Test plotting of epochs image topography."""
    title = 'ERF images - MNE sample data'
    epochs = _get_epochs()
    epochs.load_data()
    cmap = mne_analyze_colormap(format='matplotlib')
    data_min = epochs._data.min()
    plt.close('all')
    fig = plot_topo_image_epochs(epochs, sigma=0.5, vmin=-200, vmax=200,
                                 colorbar=True, title=title, cmap=cmap)
    assert epochs._data.min() == data_min
    num_figures_before = len(plt.get_fignums())
    _fake_click(fig, fig.axes[0], (0.08, 0.64))
    assert num_figures_before + 1 == len(plt.get_fignums())
    # test for auto-showing a colorbar when only 1 sensor type
    ep = epochs.copy().pick_types(meg=False, eeg=True)
    fig = plot_topo_image_epochs(ep, vmin=None, vmax=None, colorbar=None,
                                 cmap=cmap)
    ax = [x for x in fig.get_children() if isinstance(x, matplotlib.axes.Axes)]
    qm_cmap = [y.cmap for x in ax for y in x.get_children()
               if isinstance(y, matplotlib.collections.QuadMesh)]
    assert qm_cmap[0] is cmap
    plt.close('all')
# Visualize the clusters

print('Visualizing clusters.')
import os
os.environ["SUBJECTS_DIR"] = "/mnt/file1/binder/KRNS/anatomies/surfaces/"
os.environ["subjects_dir"] = "/mnt/file1/binder/KRNS/anatomies/surfaces/"

#    Now let's build a convenient representation of each cluster, where each
#    cluster becomes a "time point" in the SourceEstimate
stc_all_cluster_vis = summarize_clusters_stc(clu, tstep=tstep,
                                             vertno=fsave_vertices,
                                             subject='fsaverage')

#    Let's actually plot the first "time point" in the SourceEstimate, which
#    shows all the clusters, weighted by duration
colormap = mne_analyze_colormap(limits=[0, 10, 50])
#subjects_dir = op.join(data_path, 'subjects')
# blue blobs are for condition A < condition B, red for A > B
brain = stc_all_cluster_vis.plot('fsaverage', 'inflated', 'lh', colormap,
                                 time_label='Duration significant (ms)', time_viewer = True)
brain.set_data_time_index(0)
# The colormap requires brain data to be scaled -fmax -> fmax
brain.scale_data_colormap(fmin=-50, fmid=0, fmax=50, transparent=False)
brain.show_view('lateral')
brain.save_image('clusters.png')

##########################################################################################################################33
##########################################################################################################################33
##############################################################################################################################3
##############################################################################################################################3
## Transform to common cortical space
def plot_stc_time_point(stc,
                        subject,
                        limits=[5, 10, 15],
                        time_index=0,
                        surf='inflated',
                        measure='dSPM',
                        subjects_dir=None):
    """Plot a time instant from a SourceEstimate using matplotlib

    The same could be done with mayavi using proper 3D.

    Parameters
    ----------
    stc : instance of SourceEstimate
        The SourceEstimate to plot.
    subject : string
        The subject name (only needed if surf is a string).
    time_index : int
        Time index to plot.
    surf : str, or instance of surfaces
        Surface to use (e.g., 'inflated' or 'white'), or pre-loaded surfaces.
    measure : str
        The label for the colorbar. None turns the colorbar off.
    subjects_dir : str, or None
        Path to the SUBJECTS_DIR. If None, the path is obtained by using
        the environment variable SUBJECTS_DIR.
    """
    subjects_dir = get_subjects_dir(subjects_dir)
    pl.figure(facecolor='k', figsize=(8, 5))
    hemis = ['lh', 'rh']
    if isinstance(surf, str):
        surf = [
            read_surface(
                op.join(subjects_dir, subject, 'surf', '%s.%s' % (h, surf)))
            for h in hemis
        ]
    my_cmap = mne_analyze_colormap(limits)
    for hi, h in enumerate(hemis):
        coords = surf[hi][0][stc.vertno[hi]]
        if hi == 0:
            vals = stc_all_cluster_vis.lh_data[:, time_index]
        else:
            vals = stc_all_cluster_vis.rh_data[:, time_index]
        ax = pl.subplot(1, 2, 1 - hi, axis_bgcolor='none')
        pl.tick_params(labelbottom='off', labelleft='off')
        flipper = -1 if hi == 1 else 1
        sc = ax.scatter(flipper * coords[:, 1],
                        coords[:, 2],
                        c=vals,
                        vmin=-limits[2],
                        vmax=limits[2],
                        cmap=my_cmap,
                        edgecolors='none',
                        s=5)
        ax.set_aspect('equal')
        pl.axis('off')
    try:
        pl.tight_layout(0)
    except:
        pass
    if measure is not None:
        cax = pl.axes([0.85, 0.15, 0.025, 0.15], axisbg='k')
        cb = pl.colorbar(sc, cax, ticks=[-limits[2], 0, limits[2]])
        cb.set_label(measure, color='w')
    pl.setp(pl.getp(cb.ax, 'yticklabels'), color='w')
    pl.draw()
    pl.show()
Example #16
0
###############################################################################
# Visualize the clusters

print 'Visualizing clusters.'

#    Now let's build a convenient representation of each cluster, where each
#    cluster becomes a "time point" in the SourceEstimate
stc_all_cluster_vis = summarize_clusters_stc(clu,
                                             tstep=tstep,
                                             vertno=fsave_vertices,
                                             subject='fsaverage')

#    Let's actually plot the first "time point" in the SourceEstimate, which
#    shows all the clusters, weighted by duration
colormap = mne_analyze_colormap(limits=[0, 10, 50])
subjects_dir = op.join(data_path, 'subjects')
# blue blobs are for condition A < condition B, red for A > B
brains = stc_all_cluster_vis.plot('fsaverage',
                                  'inflated',
                                  'both',
                                  colormap,
                                  subjects_dir=subjects_dir,
                                  time_label='Duration significant (ms)')
for idx, brain in enumerate(brains):
    brain.set_data_time_index(0)
    # The colormap requires brain data to be scaled -fmax -> fmax
    brain.scale_data_colormap(fmin=-50, fmid=0, fmax=50, transparent=False)
    brain.show_view('lateral')
    brain.save_image('clusters-%s.png' % ('lh' if idx == 0 else 'rh'))
n_signals_tot = 1 + len(vertices[0]) + len(vertices[1])

indices = seed_target_indices([0], np.arange(1, n_signals_tot))

# Compute the PSI in the frequency range 8Hz..30Hz. We exclude the baseline
# period from the connectivity estimation
fmin = 8.
fmax = 30.
tmin_con = 0.
sfreq = raw.info['sfreq']  # the sampling frequency

psi, freqs, times, n_epochs, _ = phase_slope_index(comb_ts, mode='multitaper',
    indices=indices, sfreq=sfreq, fmin=fmin, fmax=fmax, tmin=tmin_con)

# Generate a SourceEstimate with the PSI. This is simple since we used a single
# seed (inspect the indices variable to see how the PSI scores are arranged in
# the output)
psi_stc = mne.SourceEstimate(psi, vertices=vertices, tmin=0, tstep=1,
                             subject='sample')

# Now we can visualize the PSI using the plot method. We use a custom colormap
# to show signed values
v_max = np.max(np.abs(psi))
colormap = mne_analyze_colormap(limits=[0, v_max / 3, v_max])
brain = psi_stc.plot(surface='inflated', hemi='lh',
                     time_label='Phase Slope Index (PSI)',
                     subjects_dir=subjects_dir, colormap=colormap)
brain.scale_data_colormap(fmin=-v_max, fmid=0., fmax=v_max, transparent=False)
brain.show_view('medial')
brain.add_label(fname_label, color='green', alpha=0.7)