Ejemplo n.º 1
0
 def test_parcellize(self):
     """Test function parcellize."""
     b_obj = BrainObj('inflated')
     file_1 = self.need_file(NEEDED_FILES['PARCELLATES_1'])
     file_2 = self.need_file(NEEDED_FILES['PARCELLATES_2'])
     b_obj.parcellize(file_1, hemisphere='left')
     select = ['insula', 'paracentral', 'precentral']
     data = np.arange(len(select))
     b_obj.parcellize(file_2, select=select, data=data, cmap='Spectral_r')
Ejemplo n.º 2
0
def create_brain_obj (annot_file_R, annot_file_L, areas):
    brain_obj = BrainObj(name = 'inflated', hemisphere='both', translucent=False, cbtxtsz = 10., verbose = None) #, cblabel='Parcellates example', cbtxtsz=4.)
    left_areas = []
    right_areas = []

    for area in areas:
        if area[-1] == 'R':
            right_areas. append (area)
        elif area[-1] == 'L':
            left_areas. append (area)

    if len (left_areas) > 0:
        brain_obj.parcellize (annot_file_L, hemisphere='left',  select=left_areas)

    if len (right_areas) > 0:
        brain_obj.parcellize (annot_file_R, hemisphere='right',  select=right_areas)

    return brain_obj
Ejemplo n.º 3
0
    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
Ejemplo n.º 4
0
file1 = 'lh.aparc.a2009s.annot'
file2 = 'rh.aparc.annot'

# Download files if needed :
path_to_file1 = download_file(file1, astype='example_data')
path_to_file2 = download_file(file2, astype='example_data')

# Define a brain object :
b_obj = BrainObj('inflated', hemisphere='both', translucent=False,
                 cblabel='Parcellates example', cbtxtsz=4.)

"""Parcellize the left hemisphere using the Destrieux Atlas. By default, no
parcellates are selected
"""
b_obj.parcellize(path_to_file1, hemisphere='left')

"""If you want to get the list of all predefined parcellates, use the
`get_parcellates` method which returns a pandas DataFrame with the index, the
name and the color associated to each parcellates
"""
df = b_obj.get_parcellates(path_to_file2)
# print(df)

"""Select only some parcellates. Note that this parcellization is using an
other atlas (Desikan-Killiany atlas)
"""
select = ['insula', 'paracentral', 'precentral', 'precuneus', 'frontalpole',
          'temporalpole', 'fusiform', 'cuneus', 'inferiorparietal',
          'inferiortemporal', 'precentral', 'superiorfrontal',
          'superiortemporal']
Ejemplo n.º 5
0
file2 = 'rh.aparc.annot'

# Download files if needed :
path_to_file1 = download_file(file1, astype='example_data')
path_to_file2 = download_file(file2, astype='example_data')

# Define a brain object :
b_obj = BrainObj('inflated',
                 hemisphere='both',
                 translucent=False,
                 cblabel='Parcellates example',
                 cbtxtsz=4.)
"""Parcellize the left hemisphere using the Destrieux Atlas. By default, no
parcellates are selected
"""
b_obj.parcellize(path_to_file1, hemisphere='left')
"""If you want to get the list of all predefined parcellates, use the
`get_parcellates` method which returns a pandas DataFrame with the index, the
name and the color associated to each parcellates
"""
df = b_obj.get_parcellates(path_to_file2)
# print(df)
"""Select only some parcellates. Note that this parcellization is using an
other atlas (Desikan-Killiany atlas)
"""
select = [
    'insula', 'paracentral', 'precentral', 'precuneus', 'frontalpole',
    'temporalpole', 'fusiform', 'cuneus', 'inferiorparietal',
    'inferiortemporal', 'precentral', 'superiorfrontal', 'superiortemporal'
]
"""Instead of using predefined colors inside the annot file, we use some data
Ejemplo n.º 6
0
#     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')
# Define the brain object (now you should know how to do it)
b_obj_parl = BrainObj('inflated', hemisphere='left', translucent=False)
# Print parcellates included in the file
# print(b_obj_parl.get_parcellates(path_to_file1))
# Finally, parcellize the brain and add the brain to the scene
b_obj_parl.parcellize(path_to_file1)
sc.add_to_subplot(b_obj_parl,
                  row=1,
                  col=1,
                  rotate='left',
                  title='Parcellize using the Desikan Atlas',
                  **KW)

###############################################################################
# .. note::
#     Those annotations files from MNE-python are only compatibles with the
#     inflated, white and sphere templates

###############################################################################
# Send data to parcellates
###############################################################################
Ejemplo n.º 7
0
    # Load files :
    with open(label_file, 'rb') as f:
        ar = pickle.load(f)
        names, xyz, colors = ar['ROI_names'], ar['ROI_coords'], ar[
            'ROI_colors']  # noqa
    ts = np.squeeze(np.load(inverse_file))
    cen = np.array([k.mean(0) for k in xyz])

    # Get the data of the left / right hemisphere :
    lh_data, rh_data = ts[::2, time_pts], ts[1::2, time_pts]
    clim = (ts[:, time_pts].min(), ts[:, time_pts].max())
    roi_names = [k[0:-3] for k in np.array(names)[::2]]

    # 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)
Ejemplo n.º 8
0
#     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')
# Define the brain object (now you should know how to do it)
b_obj_parl = BrainObj('inflated', hemisphere='left', translucent=False)
# Print parcellates included in the file
# print(b_obj_parl.get_parcellates(path_to_file1))
# Finally, parcellize the brain and add the brain to the scene
b_obj_parl.parcellize(path_to_file1)
sc.add_to_subplot(b_obj_parl, row=1, col=1, rotate='left',
                  title='Parcellize using the Desikan Atlas', **KW)

###############################################################################
# .. note::
#     Those annotations files from MNE-python are only compatibles with the
#     inflated, white and sphere templates

###############################################################################
# Send data to parcellates
###############################################################################
# Again, we download an annotation file, but this time for the right hemisphere
# The difference with the example above, is that this time we send some data
# to some specific parcellates
Ejemplo n.º 9
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()
Ejemplo n.º 10
0
for inverse_file, label_file in zip(time_series_files, label_files):
    # Load files :
    with open(label_file, 'rb') as f:
        ar = pickle.load(f)
        names, xyz, colors = ar['ROI_names'], ar['ROI_coords'], ar['ROI_colors']  # noqa
    ts = np.squeeze(np.load(inverse_file))
    cen = np.array([k.mean(0) for k in xyz])

    # Get the data of the left / right hemisphere :
    lh_data, rh_data = ts[::2, time_pts], ts[1::2, time_pts]
    clim = (ts[:, time_pts].min(), ts[:, time_pts].max())
    roi_names = [k[0:-3] for k in np.array(names)[::2]]

    # 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='viridis')  # noqa
    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='viridis')  # noqa
    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='viridis')  # noqa
    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='viridis')  # noqa
Ejemplo n.º 11
0
sc.add_to_subplot(b_obj_rw,
                  row=0,
                  col=2,
                  rotate='left',
                  title='Right hemisphere',
                  use_this_cam=True)

print("""
# =============================================================================
#                   Parcellize the brain (using all parcellates)
# =============================================================================
""")
path_to_file1 = download_file('lh.aparc.a2009s.annot')
b_obj_parl = BrainObj('inflated', hemisphere='left', translucent=False)
# print(b_obj_parl.get_parcellates(path_to_file1))  # available parcellates
b_obj_parl.parcellize(path_to_file1)
sc.add_to_subplot(b_obj_parl,
                  row=1,
                  col=1,
                  rotate='left',
                  title='Parcellize using the Desikan Atlas')

print("""
# =============================================================================
#                          Send data to parcellates
# =============================================================================
""")
path_to_file2 = download_file('rh.aparc.annot')
b_obj_parr = BrainObj('inflated', hemisphere='right', translucent=False)
# print(b_obj_parr.get_parcellates(path_to_file2))  # available parcellates
select_par = [
Ejemplo n.º 12
0
def create_brain_obj(l_file,
                     r_file,
                     activated_areas,
                     brain_name,
                     hemisphere='both',
                     cmap='copper',
                     vmin=0.,
                     vmax=0.01):
    """Create BrainObj, add areas, and return object

    Input:
    --------
    l_file: str
    r_file: str
    brain_areas: pd.DataFrame
        dataframe of selected areas, shape ['index', 'values']
    brain_name: str
        parameter for the BrainObj, in ('white', 'inflated')
    hemisphere: str
        parameter for the BrainObj, in ('both', 'left', 'right)
    cmap: str
        maplotlib colomap to use. For pvalues, 'copper' should be used; for estimates, 'coolwarm'.
    clim: tuple
        colorbar limits. For pvalues, (0,pmax) should be used; for estimates, a symetrical interval.
    
    Output:
    --------
    b_obj: visbrain.objects.BrainObj
    """
    b_obj = BrainObj(brain_name, translucent=False, hemisphere=hemisphere)
    annot_data = b_obj.get_parcellates(l_file)

    # errors if missing labels - removing labels not in annot_data
    annot_select = pd.merge(annot_data.reset_index()[['index', 'Labels']],
                            activated_areas,
                            on=['index'],
                            validate="one_to_one")
    annot_select['is_left'] = annot_select['Labels'].apply(
        lambda x: x[-1] == 'L')

    if annot_select[annot_select.is_left].shape[0] > 0:
        b_obj.parcellize(
            l_file,
            hemisphere='left',
            select=annot_select[annot_select.is_left]['Labels'].tolist(),
            data=annot_select[annot_select.is_left]['values'].tolist(),
            cmap=cmap,
            vmin=vmin,
            vmax=vmax,
            clim=(vmin, vmax))
    if annot_select[~annot_select.is_left].shape[0] > 0:
        b_obj.parcellize(
            r_file,
            hemisphere='right',
            select=annot_select[~annot_select.is_left]['Labels'].tolist(),
            data=annot_select[~annot_select.is_left]['values'].tolist(),
            cmap=cmap,
            vmin=vmin,
            vmax=vmax,
            clim=(vmin, vmax))
    return b_obj