コード例 #1
0
 def test_update_cbar_from_obj(self):
     """Test function update_cbar_from_obj."""
     xyz = np.random.rand(10, 3)
     edges = np.random.rand(10, 10)
     s_obj = SourceObj('S1', xyz)
     b_obj = BrainObj('B1')
     c_obj = ConnectObj('C1', xyz, edges)
     im_obj = ImageObj('IM1', np.random.rand(10, 10))
     ColorbarObj(s_obj)
     ColorbarObj(c_obj)
     ColorbarObj(b_obj)
     ColorbarObj(im_obj)
コード例 #2
0
ファイル: plot.py プロジェクト: tianqisong0117/slam
def visbrain_plot(mesh, tex=None, caption=None, cblabel=None, visb_sc=None,
                  cmap='jet'):
    """
    Visualize a trimesh object using visbrain core plotting tool
    :param mesh: trimesh object
    :param tex: numpy array of a texture to be visualized on the mesh
    :return:
    """
    from visbrain.objects import BrainObj, ColorbarObj, SceneObj
    b_obj = BrainObj('gui', vertices=np.array(mesh.vertices),
                     faces=np.array(mesh.faces),
                     translucent=False)
    if not isinstance(visb_sc, SceneObj):
        visb_sc = SceneObj(bgcolor='black', size=(1000, 1000))
    # identify (row, col)
    row, _ = get_visb_sc_shape(visb_sc)
    visb_sc.add_to_subplot(b_obj, row=row, col=0, title=caption)

    if tex is not None:
        b_obj.add_activation(data=tex, cmap=cmap,
                             clim=(np.min(tex), np.max(tex)))
        CBAR_STATE = dict(cbtxtsz=20, txtsz=20., width=.1, cbtxtsh=3.,
                          rect=(-.3, -2., 1., 4.), cblabel=cblabel)
        cbar = ColorbarObj(b_obj, **CBAR_STATE)
        visb_sc.add_to_subplot(cbar, row=row, col=1, width_max=200)

    return visb_sc
コード例 #3
0
def plot_meg_connectome():
    '''
    Plot the MEG brain connectome for the master figure in MEG paper

    '''
    megdata = sio.loadmat('MEG_data_info/total_connecivtiy_coord_label.mat')
    total_con = megdata['connectivity']
    xyz = megdata['ROI_coords']
    normal_con = total_con[:53]
    smci_con = total_con[53:-28]
    pmci_con = total_con[-28:]
    edges = smci_con[8, :, :]

    sc = SceneObj(bgcolor='black')
    c_obj = ConnectObj('default',
                       xyz,
                       edges,
                       select=edges > .026,
                       line_width=3.,
                       dynamic=(0., 1.),
                       dynamic_orientation='center',
                       cmap='bwr',
                       color_by='strength')
    s_obj = SourceObj('sources', xyz, color='red', radius_min=15.)
    cb_obj = ColorbarObj(c_obj, cblabel='Edge strength')

    sc.add_to_subplot(c_obj, title='MEG brain network')
    sc.add_to_subplot(s_obj)
    sc.add_to_subplot(BrainObj('B3'), use_this_cam=True)
    sc.add_to_subplot(cb_obj, col=1, width_max=200)
    sc.preview()
コード例 #4
0
def texture_plot(mesh,
                 tex=None,
                 caption=None,
                 cblabel=None,
                 visb_sc=None,
                 cmap='gnuplot'):
    """
    Projecting Texture onto trimesh object using visbrain core plotting tool
    :param mesh: trimesh object
    :param tex: numpy array of a texture to be visualized
    :return: 0
    """

    b_obj = BrainObj('gui',
                     vertices=np.array(mesh.vertices),
                     faces=np.array(mesh.faces),
                     translucent=False)
    if visb_sc is None:
        visb_sc = SceneObj(bgcolor='black', size=(1400, 1000))
        visb_sc.add_to_subplot(b_obj, title=caption)
        visb_sc_shape = (1, 1)
    else:
        visb_sc_shape = get_visb_sc_shape(visb_sc)
        visb_sc.add_to_subplot(b_obj,
                               row=visb_sc_shape[0] - 1,
                               col=visb_sc_shape[1],
                               title=caption)

    if tex is not None:
        b_obj.add_activation(data=tex,
                             cmap=cmap,
                             clim=(np.min(tex), np.max(tex)))
        CBAR_STATE = dict(cbtxtsz=20,
                          txtsz=20.,
                          width=.1,
                          cbtxtsh=3.,
                          rect=(-.3, -2., 1., 4.),
                          cblabel=cblabel)
        cbar = ColorbarObj(b_obj, **CBAR_STATE)
        visb_sc.add_to_subplot(cbar,
                               row=visb_sc_shape[0] - 1,
                               col=visb_sc_shape[1] + 1,
                               width_max=200)
    return visb_sc
コード例 #5
0
    # Left hemisphere outside :
    b_obj_li = BrainObj('white', translucent=False, hemisphere='left')
    b_obj_li.parcellize(lh_file, select=roi_names, data=lh_data, cmap=cmap)
    sc.add_to_subplot(b_obj_li, rotate='left')

    # Left hemisphere inside :
    b_obj_lo = BrainObj('white', translucent=False, hemisphere='left')
    b_obj_lo.parcellize(lh_file, select=roi_names, data=lh_data, cmap=cmap)
    sc.add_to_subplot(b_obj_lo, col=1, rotate='right')

    # Right hemisphere outside :
    b_obj_ro = BrainObj('white', translucent=False, hemisphere='right')
    b_obj_ro.parcellize(rh_file, select=roi_names, data=rh_data, cmap=cmap)
    sc.add_to_subplot(b_obj_ro, row=1, rotate='right')

    # Right hemisphere inside :
    b_obj_ri = BrainObj('white', translucent=False, hemisphere='right')
    b_obj_ri.parcellize(rh_file, select=roi_names, data=rh_data, cmap=cmap)
    sc.add_to_subplot(b_obj_ri, row=1, col=1, rotate='left')

    # Add the colorbar :
    cbar = ColorbarObj(b_obj_li,
                       txtsz=15,
                       cbtxtsz=20,
                       txtcolor=txtcolor,
                       cblabel='Intensity')
    sc.add_to_subplot(cbar, col=2, row_span=2)

sc.preview()
コード例 #6
0
sc.add_to_subplot(s_obj_2,
                  row=1,
                  col=1,
                  title='Plot only sources in BA4, 6 and 8')
sc.add_to_subplot(roi_brod_2, row=1, col=1, use_this_cam=True)

# =============================================================================
#                   CORTICAL PROJECTION OF SOURCE'S ACTIVITY
# =============================================================================
print("\n-> Project source's activity onto ROI")
# Define the ROI object :
roi_brod_3 = RoiObj('aal')
roi_brod_3.select_roi(select=[29, 30, 77, 78], smooth=11)
# Define a source object :
s_obj_3 = SourceObj('SecondSources', xyz, data=data)
roi_brod_3.project_sources(s_obj_3,
                           cmap='plasma',
                           clim=(-1., 1.),
                           vmin=-.5,
                           vmax=.7,
                           under='gray',
                           over='red')
cb_brod_3 = ColorbarObj(roi_brod_3, cblabel='Source activity', **CBAR_STATE)
sc.add_to_subplot(roi_brod_3,
                  row=1,
                  col=2,
                  title="Project source activity onto ROI")
sc.add_to_subplot(cb_brod_3, row=1, col=3, width_max=200)

sc.preview()
コード例 #7
0
 def test_definition(self):
     """Test definition."""
     ColorbarObj('cbar')
コード例 #8
0
###############################################################################
# The ImageObj allow several custom color properties (such as color
# thresholding, colormap control...)

# Create the image object
im_color = ImageObj('ex3',
                    image,
                    interpolation='bilinear',
                    cmap='Spectral_r',
                    vmin=5.,
                    vmax=20.,
                    under='gray',
                    over='darkred')
sc.add_to_subplot(im_color, row=0, col=2, title='Custom colors', zoom=.9)
# Get the colorbar of the image
cb_im_color = ColorbarObj(im_color, cblabel='Image data', **CBAR_STATE)
sc.add_to_subplot(cb_im_color, row=0, col=3, width_max=150, zoom=.9)

###############################################################################
# Spectrogram
###############################################################################
# Extract time-frequency properties using the Fourier transform

spec = TimeFrequencyObj('spec', data, sf, method='fourier', cmap='RdBu_r')
sc.add_to_subplot(spec, row=1, col=0, title='Spectrogram', zoom=.9)

###############################################################################
# Time-frequency map
###############################################################################
# Extract time-frequency properties using the wavelet convolution
コード例 #9
0
ファイル: plot_brain_obj.py プロジェクト: skjerns/visbrain
# As explain above, we define a source object and project the source's activity
# on the surface of the brain

# First, define a brain object used for the projection
b_obj_proj = BrainObj('B3', hemisphere='both', translucent=False)
# Define the source object
s_obj = SourceObj('iEEG', xyz, data=data, cmap='inferno')
# Just for fun, color sources according to the data :)
s_obj.color_sources(data=data)
# Project source's activity
s_obj.project_sources(b_obj_proj, cmap='plasma')
# Finally, add the source and brain objects to the subplot
sc.add_to_subplot(s_obj, row=0, col=2, title='Project iEEG data', **KW)
sc.add_to_subplot(b_obj_proj, row=0, col=2, rotate='left', use_this_cam=True)
# Finally, add the colorbar :
cb_proj = ColorbarObj(s_obj, cblabel='Projection of niEEG data', **CBAR_STATE)
sc.add_to_subplot(cb_proj, row=0, col=3, width_max=200)

###############################################################################
# .. note::
#     Here, we used s_obj.project_sources(b_obj) to project source's activity
#     on the surface. We could also have used to b_obj.project_sources(s_obj)

###############################################################################
# Parcellize the brain
###############################################################################
# Here, we parcellize the brain (using all parcellated included in the file).
# Note that those parcellates files comes from MNE-python.

# Download the annotation file of the left hemisphere lh.aparc.a2009s.annot
path_to_file1 = download_file('lh.aparc.a2009s.annot', astype='example_data')
コード例 #10
0
                             hemisphere='right',
                             cmap='hot_r',
                             vmin=0,
                             vmax=1,
                             clim=(0, 1))
b_obj_proj_rl.add_activation(texturerl,
                             hemisphere='right',
                             cmap='hot_r',
                             vmin=0,
                             vmax=1,
                             clim=(0, 1),
                             hide_under=0)

cb_proj = ColorbarObj(b_obj_proj_rl,
                      cblabel='Correlation',
                      cmap='hot_r',
                      vmin=0,
                      vmax=1,
                      **CBAR_STATE)

sc2.add_to_subplot(b_obj_proj_ll, row=0, col=0, rotate='left')

sc2.add_to_subplot(b_obj_proj_lr, row=0, col=1, rotate='right')

sc2.add_to_subplot(b_obj_proj_rl, row=0, col=2, rotate='left')

sc2.add_to_subplot(b_obj_proj_rr, row=0, col=3, rotate='right')

sc2.add_to_subplot(cb_proj, row=0, col=4, width_max=100)

sc2.preview()
コード例 #11
0
ファイル: plot_topo_obj.py プロジェクト: skjerns/visbrain
###############################################################################
# Create a scene with a white background

sc = SceneObj(bgcolor='white', size=(1600, 900))

###############################################################################
# Topoplot based on channel names
###############################################################################
# First definition using channel names only

# Define some EEG channels and set one data value per channel
ch_names = ['C3', 'C4', 'Cz', 'Fz', 'Pz']
data_names = [10, 20, 30, 10, 10]
# Create the topoplot and the associated colorbar
t_obj = TopoObj('topo', data_names, channels=ch_names, **kw_top)
cb_obj = ColorbarObj(t_obj, cblabel='Colorbar label', **kw_cbar)
# Add both objects to the scene
# Add the topoplot and the colorbar to the scene :
sc.add_to_subplot(t_obj,
                  row=0,
                  col=0,
                  title='Definition using channel names',
                  title_color='black',
                  width_max=400)
sc.add_to_subplot(cb_obj, row=0, col=1, width_max=100)

###############################################################################
# Topoplot based on channel (x, y) coordinates
###############################################################################
# Second definition using channel (x, y) coordinates
コード例 #12
0
data_par = [10., .1, 5., 7., 11., 8., 4., 6.]
b_obj_parr.parcellize(path_to_file2,
                      select=select_par,
                      hemisphere='right',
                      cmap='inferno',
                      data=data_par,
                      vmin=1.,
                      vmax=10,
                      under='gray',
                      over='darkred')
sc.add_to_subplot(b_obj_parr,
                  row=1,
                  col=2,
                  rotate='right',
                  title='Send data to Desikan-Killiany parcellates')
cb_parr = ColorbarObj(b_obj_parr, cblabel='Data to parcellates', **CBAR_STATE)
sc.add_to_subplot(cb_parr, row=1, col=3, width_max=200)

print("""
# =============================================================================
#                          Add a custom brain template
# =============================================================================
""")
mat = np.load(download_file('Custom.npz'))
vert, faces, norms = mat['vertices'], mat['faces'], mat['normals']
b_obj_custom = BrainObj('Custom',
                        vertices=1000 * vert,
                        faces=faces,
                        normals=norms,
                        translucent=False)
sc.add_to_subplot(b_obj_custom,
コード例 #13
0
aal_col = {'Precentral (R)': 'green',
           'Precentral (L)': 'orange',
           'Insula (R)': 'blue'}
s_obj_aal.color_sources(analysis=df_aal, color_by='aal', roi_to_color=aal_col,
                        color_others='white')
sc.add_to_subplot(s_obj_aal, row=1, col=1,
                  title='Color only sources in precentral and insula')

"""Use a random data vector to color sources
"""
data = np.random.uniform(low=-10., high=10., size=(n_sources,))
s_obj_data = SourceObj('S3', xyz, data=data)
s_obj_data.color_sources(data=data, cmap='plasma', clim=(-10, 10), vmin=-8.,
                         vmax=8., under='gray', over='red')
sc.add_to_subplot(s_obj_data, row=1, col=2, title='Color sources using data')
cb_data = ColorbarObj(s_obj_data, cblabel='Random data', border=False,
                      **CBAR_STATE)
sc.add_to_subplot(cb_data, row=1, col=3, width_max=60)

"""Display only sources in the left hemisphere
"""
s_obj_left = SourceObj('S_left', xyz, color='#ab4642')
s_obj_left.set_visible_sources('left')
sc.add_to_subplot(s_obj_left, row=2, col=0,
                  title='Display sources in left hemisphere')

"""Create a sphere using VisPy
"""
sphere = create_sphere(rows=100, cols=100, radius=50)
sphere_vertices = sphere.get_vertices()

"""Force sources to fit on the vertices of the sphere. Then, we color sources
コード例 #14
0
def generate_img(l_file,
                 r_file,
                 activated_areas,
                 brain_name,
                 out_file,
                 views,
                 add_hemispheres,
                 is_estimate=False,
                 cmap='copper',
                 vmin=0.,
                 vmax=0.01,
                 save_gif=False):
    """Generate .png and .gif animation of rotating brains
    """
    sc = SceneObj(size=(1000 * (len(views) // 2 +
                                (1 if add_hemispheres else 0)),
                        1000 * (len(views) > 1)),
                  bgcolor='black')
    KW = dict(title_size=14., zoom=2.)  # zoom not working
    CBAR_STATE = dict(cbtxtsz=12,
                      txtsz=10.,
                      width=.1,
                      cbtxtsh=3.,
                      rect=(-.3, -2., 1., 4.))
    # PLOT OBJECTS
    for i, rot in enumerate(views):
        # cannot use the same object
        b_obj = create_brain_obj(l_file,
                                 r_file,
                                 activated_areas,
                                 brain_name,
                                 cmap=cmap,
                                 vmin=vmin,
                                 vmax=vmax)
        sc.add_to_subplot(b_obj,
                          row=i // 2,
                          col=i % 2,
                          rotate=rot,
                          title=rot,
                          **KW)
        # Get the colorbar of the brain object and add it to the scene
        # Identical brain ==> same colorbar
    if add_hemispheres:
        # add left brain
        b_obj = create_brain_obj(l_file,
                                 r_file,
                                 activated_areas,
                                 brain_name,
                                 hemisphere='right',
                                 cmap=cmap,
                                 vmin=vmin,
                                 vmax=vmax)
        sc.add_to_subplot(b_obj,
                          row=i // 2 + 1,
                          col=0,
                          rotate='left',
                          title='right half',
                          **KW)
        b_obj = create_brain_obj(l_file,
                                 r_file,
                                 activated_areas,
                                 brain_name,
                                 hemisphere='left',
                                 cmap=cmap,
                                 vmin=vmin,
                                 vmax=vmax)
        sc.add_to_subplot(b_obj,
                          row=i // 2 + 1,
                          col=1,
                          rotate='right',
                          title='left half',
                          **KW)
    if is_estimate:
        # cmap needs to be set for all objects
        cb_parr = ColorbarObj(b_obj,
                              cblabel='Data to parcellates',
                              **CBAR_STATE)
        # not working properly and can't find a way to rotate that bar
        # sc.add_to_subplot(cb_parr, row=0, col=2, row_span=i//2+1, width_max=200)
    # gif and png
    # sc.preview()
    if save_gif:
        sc.record_animation(out_file + ('_est' if is_estimate else '') +
                            "_areas.gif")
    sc.screenshot(saveas=out_file + ('_est' if is_estimate else '') +
                  "_areas.png")
    return sc.render()
コード例 #15
0
                       antialias=True,
                       cmap='bwr',
                       line_width=4.)
    s_obj = SourceObj('s',
                      xyz,
                      data=radius,
                      radius_min=5,
                      radius_max=15,
                      text=names,
                      text_size=10,
                      text_color='white',
                      text_translate=(0., 0., 0.))
    s_obj.color_sources(data=radius, cmap='inferno')
    cbar = ColorbarObj(c_obj,
                       txtcolor='white',
                       txtsz=15,
                       cblabel='Connectivity',
                       cbtxtsz=20)
    band = _parse_string(connect_file, freq_band_names)
    title = 'Connectivity on {} band'.format(band)
    sc.add_to_subplot(c_obj,
                      title=title,
                      title_size=14,
                      title_bold=True,
                      title_color='white',
                      row=nf)
    sc.add_to_subplot(s_obj, rotate='top', zoom=.5, use_this_cam=True, row=nf)
    sc.add_to_subplot(cbar, col=1, width_max=200, row=nf)

sc.preview()
コード例 #16
0
    clim = (psds.min(), psds.max())

    # Find indices of frequencies :
    idx_fplt = np.abs(
        (freqs.reshape(1, 1, -1) - freq_bands[..., np.newaxis])).argmin(2)
    psdf = np.array([psds[:, k[0]:k[1]].mean(1) for k in idx_fplt])
    radius = normalize(np.c_[psdf.min(1), psdf.max(1)], 5, 25).astype(float)

    for num, (fb, fbn, psd,
              rx) in enumerate(zip(freq_bands, freq_band_names, psdf, radius)):
        s_obj = SourceObj('s',
                          xyz,
                          data=psd,
                          radius_min=rx[0],
                          radius_max=rx[1])  # noqa
        s_obj.color_sources(data=psd, cmap='cool', clim=clim)
        sc.add_to_subplot(s_obj,
                          col=num,
                          title=str(fb) + ' - ' + fbn,
                          title_color='white',
                          rotate='top',
                          zoom=.6)
    cbar = ColorbarObj(s_obj,
                       txtcolor='white',
                       cblabel='PSD',
                       txtsz=15,
                       cbtxtsz=20)
    sc.add_to_subplot(cbar, col=len(freq_bands), width_max=200)

sc.preview()
コード例 #17
0
def vis_brainSurface_by_padj(padj_parcellates,
                             gci_parcellates,
                             tt,
                             ptype='significant',
                             cmap='jet',
                             use_log=False,
                             use_1_p=False,
                             use_p=True):
    # '''visualize the brain surface based on the FDR-adjusted GCI values or FDR-adjusted p values'''

    # Define the default camera state used for each subplot
    CAM_STATE = dict(
        azimuth=0,  # azimuth angle
        elevation=90,  # elevation angle
        scale_factor=180  # distance to the camera
    )
    S_KW = dict(camera_state=CAM_STATE)
    # Create the scene
    CBAR_STATE = dict(cbtxtsz=12,
                      txtsz=13.,
                      width=.5,
                      cbtxtsh=2.,
                      rect=(1., -2., 1., 4.))
    sc = SceneObj(bgcolor='black', size=(1300, 1000))
    # n_sources = all_coord.shape[0]  #sig_roi_coord.shape[0]
    # data = np.random.rand(n_sources)

    # 1. significant regions
    b_obj_1 = BrainObj('white', translucent=False)

    # parcellize brain based on desikan atlas
    path_to_file1 = download_file('lh.aparc.annot', astype='example_data')
    path_to_file2 = download_file('rh.aparc.annot', astype='example_data')

    #  dataframe type varaible inlcuding index, label, color for each brain region in DKT atlas
    lh_df = b_obj_1.get_parcellates(path_to_file1)
    rh_df = b_obj_1.get_parcellates(path_to_file2)

    # lh_df.to_excel('output/lh.aparc.xlsx')

    def select_rois(df, row=1, col=1):
        select_val = list(np.array(df.iloc[row:, col]))
        select_val.pop(3)
        return select_val

    select_roi1 = select_rois(lh_df)
    select_roi2 = select_rois(rh_df)

    #  get log FDR-adjusted p values (optional)
    # log_p_parce, l_p, s_p = get_log_pval(padj_parcellates, basis=2)

    l_p = np.max(gci_parcellates)
    s_p = np.min(gci_parcellates)
    #         print('-----#####',l_p,s_p)

    if ptype == 'significant' or ptype == 'unsignificant':

        def get_hemisphere_rois(lh_padj,
                                lh_gci,
                                lh_rois,
                                select='significant',
                                cal_log=True):
            if select == 'significant':
                lh_sig_ind = np.where(np.array(lh_padj) <= 0.05)[0]
            else:
                lh_sig_ind = np.where(np.array(lh_padj) > 0.05)[0]

            lh_sig_rois = [lh_rois[i] for i in lh_sig_ind]

            if cal_log:
                log_p, _, _ = get_log_pval(lh_padj,
                                           basis=2)  # calculate "log2(padj)"
                lh_sig_padj = list(np.array(log_p)[lh_sig_ind])
            else:
                # lh_sig_padj = list(np.array(lh_padj)[lh_sig_ind])
                lh_sig_gci = list(np.array(lh_gci)[lh_sig_ind])

            # max_p= np.max(np.array(lh_sig_padj))
            # min_p= np.min(np.array(lh_sig_padj))
            # return lh_sig_rois,lh_sig_padj,max_p,min_p

            max_gci = np.max(np.array(lh_sig_gci))
            min_gci = np.min(np.array(lh_sig_gci))

            return lh_sig_rois, lh_sig_gci, max_gci, min_gci

        # (1). set (log-padj) as values for color mapping

        # select_regions_L,lh_padj,_,_ = get_hemisphere_rois(padj_parcellates[:34], gci_parcellates[:34], select_roi1, select = ptype, cal_log=use_log)
        # select_regions_R,rh_padj,_,_ = get_hemisphere_rois(padj_parcellates[34:], gci_parcellates[34:], select_roi2, select = ptype, cal_log=use_log)

        # clab = 'Log FDR-adjusted p value'
        # b_obj_1.parcellize(path_to_file1, select= select_regions_L,data=lh_padj,cmap=cmap,clim=[s_p,l_p])
        # b_obj_1.parcellize(path_to_file2, select= select_regions_R,data=rh_padj,cmap=cmap,clim=[s_p,l_p])
        # cb_1 = ColorbarObj(b_obj_1, clim= [s_p,l_p], cblabel=clab, border=False, **CBAR_STATE)

        # plot GCI value-4/23/2020

        select_regions_L, lh_gci, _, _ = get_hemisphere_rois(
            padj_parcellates[:34],
            gci_parcellates[:34],
            select_roi1,
            select=ptype,
            cal_log=use_log)
        select_regions_R, rh_gci, _, _ = get_hemisphere_rois(
            padj_parcellates[34:],
            gci_parcellates[34:],
            select_roi2,
            select=ptype,
            cal_log=use_log)

        clab = 'GCI value'
        b_obj_1.parcellize(path_to_file1, select=select_regions_L,
                           data=lh_gci)  #clim=[s_p,l_p]
        b_obj_1.parcellize(path_to_file2,
                           select=select_regions_R,
                           data=rh_gci,
                           cmap=cmap)  #, clim=[s_p,l_p])
        cb_1 = ColorbarObj(b_obj_1,
                           clim=[1.76, 1.80],
                           cblabel=clab,
                           border=False,
                           **CBAR_STATE)

    elif ptype == 'together':
        select_regions_L = select_roi1
        select_regions_R = select_roi2
        if use_log:
            # (1). set (log-padj) as values for color mapping
            clab = 'Log FDR-adjusted p value'
            lh_padj = log_p_parce[:34]
            rh_padj = log_p_parce[34:]
            b_obj_1.parcellize(path_to_file1,
                               select=select_regions_L,
                               data=lh_padj,
                               cmap=cmap,
                               clim=[s_p, l_p])
            b_obj_1.parcellize(path_to_file2,
                               select=select_regions_R,
                               data=rh_padj,
                               cmap=cmap,
                               clim=[s_p, l_p])
            cb_1 = ColorbarObj(b_obj_1,
                               clim=[s_p, l_p],
                               cblabel=clab,
                               border=False,
                               **CBAR_STATE)
        if use_1_p:

            # (2). set (1-padj) as values for color mapping
            clab = tt  #'1-FDR-adjusted p value'
            # clab = '1-FDR-adjusted p value'
            padj_0 = [1 - i for i in padj_parcellates]
            b_obj_1.parcellize(path_to_file1,
                               select=select_regions_L,
                               data=padj_0[:34],
                               cmap=cmap)
            b_obj_1.parcellize(path_to_file2,
                               select=select_regions_R,
                               data=padj_0[34:],
                               cmap=cmap)
            cb_1 = ColorbarObj(b_obj_1,
                               cblabel=clab,
                               border=False,
                               **CBAR_STATE)  #Log FDR-adjusted p value

        if use_p:
            # (2). set (1-padj) as values for color mapping
            print('--------use p-------')
            clab = tt  #'1-FDR-adjusted p value'
            mx = np.array(gci_parcellates).max()
            mi = np.array(gci_parcellates).min()
            b_obj_1.parcellize(path_to_file1,
                               select=select_regions_L,
                               data=gci_parcellates[:34],
                               cmap=cmap,
                               clim=[mi, mx])
            b_obj_1.parcellize(path_to_file2,
                               select=select_regions_R,
                               data=gci_parcellates[34:],
                               cmap=cmap,
                               clim=[mi, mx])
            cb_1 = ColorbarObj(b_obj_1,
                               cblabel=clab,
                               border=False,
                               **CBAR_STATE)  #Log FDR-adjusted p value

    b_obj_1.animate(iterations=10, step=30, interval=1.2)
    sc.add_to_subplot(b_obj_1, row=0, col=0, rotate='front')
    sc.add_to_subplot(cb_1, row=0, col=1, width_max=90)
    # sc.record_animation('output/%s_pvalue_projection.gif'%ptype, n_pic=10)
    # sc.record_animation('output/pmci_degree.gif', n_pic=8)

    sc.preview()
コード例 #18
0
# Define the source object
s_obj_data = SourceObj('S3',
                       xyz,
                       data=rnd_data,
                       radius_min=radius_min,
                       radius_max=radius_max)
# Color sources according to a data vector
s_obj_data.color_sources(
    data=rnd_data,
    cmap='viridis',
    clim=(-100, 100),
)
# Get the colorbar of the source object
cb_data = ColorbarObj(s_obj_data,
                      cblabel='Random data',
                      border=False,
                      **CBAR_STATE)
# Add the source and colorbar objects to the scene
sc.add_to_subplot(s_obj_data,
                  row=1,
                  col=3,
                  title='Color sources using data',
                  **S_KW)
sc.add_to_subplot(cb_data, row=1, col=4, width_max=60)

###############################################################################
# Project source's activity on the surface of the brain
###############################################################################
# As explained in the BrainObj tutorial, source's activity can be projected on
# the surface of the brain which can be particularly convenient for represent
# source's activity across several intracranially implanted subjects
コード例 #19
0
def vis_sources_by_pval(padj, all_coord, short_label):
    ''' 
    1. visualize the sources (brain regions) based on the FDR-adjusted p values
    display both the source objects and the brain object
    
    '''

    # Define the default camera state used for each subplot
    CAM_STATE = dict(
        azimuth=0,  # azimuth angle
        elevation=90,  # elevation angle
        scale_factor=180  # distance to the camera
    )
    S_KW = dict(camera_state=CAM_STATE)

    # Create the scene
    CBAR_STATE = dict(cbtxtsz=12,
                      txtsz=13.,
                      width=.5,
                      cbtxtsh=2.,
                      rect=(1., -2., 1., 4.))
    sc = SceneObj(bgcolor='black', size=(1600, 1000))

    # mask = padj<=0.05  # significant regions with true label

    data0, max_p, min_p = get_log_pval(padj)

    b_obj = BrainObj('white', hemisphere='both', translucent=True)
    b_obj.animate(iterations=10, step=30, interval=1)
    s_obj = SourceObj(
        's1',
        all_coord,  #all_coord, 
        # mask = mask,
        # mask_color='white',
        # mask_radius = 15,
        color=padj * 100,
        data=data0,
        text=short_label,
        text_size=10,
        text_bold=True,
        text_color='yellow',
        symbol='disc',
        visible=True,
        radius_min=10,
        radius_max=40,
        alpha=0.65)

    s_obj_1.set_visible_sources('left')

    s_obj.color_sources(data=data0, cmap='jet', clim=(min_p, max_p))
    cb_data = ColorbarObj(s_obj,
                          cblabel='Log FDR-adjusted p value',
                          border=False,
                          **CBAR_STATE)

    sc.add_to_subplot(b_obj, row=0, col=0, rotate='front')
    sc.add_to_subplot(s_obj, row=0, col=0)
    sc.add_to_subplot(cb_data, row=0, col=1, width_max=90)

    # recording animation and save it
    sc.record_animation('output/animate_pvalue_projection.gif', n_pic=10)
    sc.preview()
コード例 #20
0
# Define the roi object using the MIST at resolution 7
roi_dmn = RoiObj('mist_7')
roi_dmn.get_labels(save_to_path=vb_path)  # save the labels
dmn_idx = roi_dmn.where_is('Default mode network')
roi_dmn.select_roi(select=dmn_idx)
# Define the source object and project source's data on the DMN
s_dmn = SourceObj('SecondSources', xyz, data=data)
s_dmn.project_sources(roi_dmn,
                      cmap='plasma',
                      clim=(-1., 1.),
                      vmin=-.5,
                      vmax=.7,
                      under='gray',
                      over='red')
# Get the colorbar of the projection
cb_dmn = ColorbarObj(s_dmn, cblabel='Source activity', **CBAR_STATE)
# Add those objects to the scene
sc.add_to_subplot(roi_dmn,
                  row=0,
                  col=2,
                  rotate='top',
                  zoom=.4,
                  title="Project source's activity onto the DMN")
sc.add_to_subplot(cb_dmn, row=0, col=3, width_max=200)

###############################################################################
# Get anatomical informations of sources
###############################################################################
# If you defined sources (like intracranial recording sites, MEG source
# reconstruction...) you can use the SourceObj to defined those sources and
# then, the RoiObj to identify where are those sources located using the ROI
コード例 #21
0
# Project source's activity
source_object.project_sources(brain_obj)
source_object.color_sources(data=data[:, 0])

# Finally, add the source and brain objects to the subplot
scene.add_to_subplot(source_object,
                     row=0,
                     col=0,
                     title='Project iEEG data',
                     **KW)
scene.add_to_subplot(brain_obj, row=0, col=0, rotate='left', use_this_cam=True)

# Finally, add the colorbar :
colorbar = ColorbarObj(source_object,
                       cblabel='Projection of niEEG data',
                       **CBAR_STATE)
scene.add_to_subplot(colorbar, row=0, col=1, width_max=200, rotate='up')

# Animation

app_timer = Timer(app=CONFIG['VISPY_APP'], interval='auto', iterations=-1)


def on_timer(*args, **kwargs):
    if hasattr(brain_obj, 'camera'):
        brain_obj.camera.azimuth += 1
        t = app_timer.elapsed
        frame = int(np.floor(t * sampling_frequency))

        new_data = data[:, frame % data.shape[1]].ravel()
コード例 #22
0
ファイル: PlotBrain.py プロジェクト: pedrocklein/toolbox
    def parcellize_brain(self,
                         path_to_file1=None,
                         path_to_file2=None,
                         cmap="videen_style"):
        # Here, we parcellize the brain (using all parcellated included in the file).
        # Note that those parcellates files comes from MNE-python.

        # Download the annotation file of the left hemisphere lh.aparc.a2009s.annot
        if path_to_file1 == None:
            path_to_file1 = download_file('lh.aparc.annot',
                                          astype='example_data')
        # Define the brain object (now you should know how to do it)
        b_obj_parl = BrainObj('inflated', hemisphere='left', translucent=False)
        # From the list of printed parcellates, we only select a few of them
        select_par = [
            b
            for b in b_obj_parl.get_parcellates(path_to_file1)['Labels'].values
            if b not in
            ["unknown", "corpuscallosum", "FreeSurfer_Defined_Medial_Wall"]
        ]
        print("Selected parcelations:", select_par)
        # Now we define some data for each parcellates (one value per pacellate)
        #data_par = self.data[0:34]
        data_par = self.data[0:7]

        # Finally, parcellize the brain and add the brain to the scene
        b_obj_parl.parcellize(
            path_to_file1,
            select=select_par,
            hemisphere='left',
            cmap=cmap,
            data=data_par,
            clim=[self.min_ji, self.max_ji],
            #cmap='videen_style', data=data_par, clim=[self.min_ji, self.max_ji],
            vmin=self.min_ji,
            vmax=self.max_ji,
            under='lightgray',
            over='darkred')
        self.sc.add_to_subplot(b_obj_parl,
                               row=0,
                               col=0,
                               col_span=3,
                               rotate='left',
                               title='Left Hemisphere',
                               **self.KW)

        # Again, we download an annotation file, but this time for the right hemisphere

        # Download the annotation file of the right hemisphere rh.aparc.annot
        if path_to_file2 == None:
            path_to_file2 = download_file('rh.aparc.annot',
                                          astype='example_data')
        # Define the brain object (again... I know, this is redundant)
        b_obj_parr = BrainObj('inflated',
                              hemisphere='right',
                              translucent=False)
        print(b_obj_parr)

        select_par = [
            b
            for b in b_obj_parr.get_parcellates(path_to_file2)['Labels'].values
            if b not in
            ["unknown", "corpuscallosum", "FreeSurfer_Defined_Medial_Wall"]
        ]
        print("Selected parcelations:", select_par)
        #data_par = self.data[49:-1]
        data_par = self.data[7:]

        b_obj_parr.parcellize(
            path_to_file2,
            select=select_par,
            hemisphere='right',
            cmap=cmap,
            data=data_par,
            clim=[self.min_ji, self.max_ji],
            #cmap='videen_style', data=data_par, clim=[self.min_ji, self.max_ji],
            vmin=self.min_ji,
            vmax=self.max_ji,
            under='lightgray',
            over='darkred')

        # Add the brain object to the scene
        self.sc.add_to_subplot(b_obj_parr,
                               row=0,
                               col=4,
                               col_span=3,
                               rotate='right',
                               title='Right Hemisphere',
                               **self.KW)
        # Get the colorbar of the brain object and add it to the scene
        cb_parr = ColorbarObj(b_obj_parl,
                              cblabel='Feedback Inhibitory Synaptic Coupling',
                              **self.CBAR_STATE)
        #self.sc.add_to_subplot(cb_parr, row=0, col=3, width_max=2000)
        self.b_obj_parl = b_obj_parl
        self.path_to_file1 = path_to_file1
        self.b_obj_parr = b_obj_parr
        self.path_to_file2 = path_to_file2
コード例 #23
0
"""Test ColorbarObj."""
import numpy as np

from visbrain.objects.tests._testing_objects import _TestObjects
from visbrain.objects import (SourceObj, ConnectObj, BrainObj, ImageObj,
                              ColorbarObj)

cbar_obj = ColorbarObj('cbar', cmap='inferno')


class TestColorbarObj(_TestObjects):
    """Test ColorbarObj."""

    OBJ = cbar_obj

    def test_definition(self):
        """Test definition."""
        ColorbarObj('cbar')

    def test_update_cbar_from_obj(self):
        """Test function update_cbar_from_obj."""
        xyz = np.random.rand(10, 3)
        edges = np.random.rand(10, 10)
        s_obj = SourceObj('S1', xyz)
        b_obj = BrainObj('B1')
        c_obj = ConnectObj('C1', xyz, edges)
        im_obj = ImageObj('IM1', np.random.rand(10, 10))
        ColorbarObj(s_obj)
        ColorbarObj(c_obj)
        ColorbarObj(b_obj)
        ColorbarObj(im_obj)