Esempio n. 1
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()
Esempio n. 2
0
class PlotBrain:
    def __init__(self):
        pass

    def create_scene(self, bgcolor='white', size=(4000, 3000)):
        # Scene creation
        self.sc = SceneObj(bgcolor=bgcolor, size=size)
        # Colorbar default arguments. See `visbrain.objects.ColorbarObj`
        self.CBAR_STATE = dict(cbtxtsz=60,
                               txtsz=60.,
                               width=1,
                               cbtxtsh=60.,
                               rect=(-3, -2., 10., 4.),
                               txtcolor="black")
        self.KW = dict(title_size=60., zoom=2, title_color="black")

    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

    def plot(self,
             data,
             path_to_file1=None,
             path_to_file2=None,
             cmap="videen_style"):
        self.data = data
        # self.min_ji = np.min(self.data)
        # self.max_ji = np.max(self.data)
        self.min_ji = 0
        self.max_ji = 2
        self.create_scene()
        self.parcellize_brain(path_to_file1, path_to_file2, cmap=cmap)
        self.sc.preview()

        return (self.b_obj_parl, self.path_to_file1, self.b_obj_parr,
                self.path_to_file1, self.path_to_file2)
Esempio n. 3
0
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

tf = TimeFrequencyObj('tf', data, sf, method='wavelet')
sc.add_to_subplot(tf, row=1, col=1, title='Time-frequency map', zoom=.9)

###############################################################################
# Multi-taper
###############################################################################
# Extract time-frequency properties using multi-taper (need installation of
# lspopt package)

tf_mt = TimeFrequencyObj('mt',
                         data,
                         sf,
                         method='multitaper',
                         overlap=.7,
                         interpolation='bicubic',
                         cmap='Spectral_r')
sc.add_to_subplot(tf_mt, row=1, col=2, title='Multi-taper', zoom=.9)
cb_tf_win = ColorbarObj(tf_mt, cblabel='Power', **CBAR_STATE)
sc.add_to_subplot(cb_tf_win, row=1, col=3, width_max=150, zoom=.9)

# Display the scene
sc.preview()
Esempio n. 4
0
column_names = arr[0, :]
arr = np.delete(arr, 0, 0)
n_roi = arr.shape[0]
roi_index = arr[:, 0].astype(int)
roi_labels = arr[:, [1, 2]].astype(object)
# Build the struct array :
label = np.zeros(n_roi, dtype=[('label', object), ('name', object)])
label['label'] = roi_labels[:, 0]
label['name'] = roi_labels[:, 1]
# Get the volume and the hdr transformation :
vol, _, hdr = read_nifti(nifti_file, hdr_as_array=True)
# Define the ROI object and save it :
roi_custom = RoiObj('custom_roi', vol=vol, labels=label, index=roi_index,
                    hdr=hdr)
# Find thalamus entries :
idx_thalamus = roi_custom.where_is('THALAMUS')
colors = {55: 'slateblue', 56: 'olive', 63: 'darkred', 64: '#ab4642'}
roi_custom.select_roi(idx_thalamus, roi_to_color=colors)
sc.add_to_subplot(roi_custom, row=1, col=2, zoom=.5,
                  title='Plot dorsal and ventral thalamus with fixed colors')

###############################################################################
# .. note::
#     Once your RoiObj is defined, you can save it using
#     :class:`visbrain.objects.RoiObj.save`. Once the object is saved, you can
#     reload it using the name you've used (here we've used the `custom_roi`
#     name which means that you can reload it later using RoiObj('custom_roi'))

# Finally, display the scene
sc.preview()
Esempio n. 5
0
                             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()
Esempio n. 6
0
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()
        source_object._data = vispy_array(new_data)
        source_object.update()
        source_object.project_sources(brain_obj)
        source_object.color_sources()


app_timer.connect(on_timer)
app_timer.start()

scene.preview()
Esempio n. 7
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()
Esempio n. 8
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()