예제 #1
0
print(ref_brod.loc[idx_ba6])
roi_to_find1('aal')                           # Switch to AAL
idx_sma = roi_to_find1.where_is('Supp Motor Area')

###############################################################################
# Extract the mesh of an ROI
###############################################################################
# Once you have the index of the ROI that you want to plot, use the
# :class:`visbrain.objects.RoiObj.select_roi` method to extract the mesh (i.e
# vertices and faces) of the ROI. Here, we illustrate this question with the
# brodmann 6 ROI

# Load the brodmann 6 atlas, get the index of BA6 and extract the mesh
roi_brod = RoiObj('brodmann')
idx_ba6 = roi_brod.where_is('BA6')
roi_brod.select_roi(select=idx_ba6)
# Define a brain object and add this brain and ROI objects to the scene
b_obj = BrainObj('B1')
sc.add_to_subplot(b_obj, row=0, col=0, use_this_cam=True,
                  title='Brodmann area 6 mesh')
sc.add_to_subplot(roi_brod, row=0, col=0)

###############################################################################
# Set a unique color per ROI mesh
###############################################################################
# If you need, you can set a unique color per plotted ROI mesh. Here, we plot
# the left and right insula and thalamus and set a unique color to each

# Load the AAL atlas
roi_aal = RoiObj('aal')
# Select indicies 29, 30, 77 and 78 (respectively insula left, right and
예제 #2
0
# fMRI activation
###############################################################################

file = download_file('lh.sig.nii.gz', astype='example_data')
b_obj_fmri = BrainObj('inflated', translucent=False, sulcus=True)
b_obj_fmri.add_activation(file=file, clim=(5., 20.), hide_under=5,
                          cmap='viridis', hemisphere='left')
sc.add_to_subplot(b_obj_fmri, row=0, col=0, row_span=2,
                  title='fMRI activation', rotate='top')

###############################################################################
# Region Of Interest (ROI)
###############################################################################

roi_aal = RoiObj('aal')
roi_aal.select_roi(select=[29, 30], unique_color=True, smooth=11)
sc.add_to_subplot(roi_aal, row=0, col=1, title='Region Of Interest (ROI)')
sc.add_to_subplot(BrainObj('B1'), use_this_cam=True, row=0, col=1)

###############################################################################
# Sources
###############################################################################

s_obj = SourceObj('FirstSources', xyz, data=data)
s_obj.color_sources(data=data, cmap='Spectral_r')
sc.add_to_subplot(s_obj, row=1, col=1, title='Sources')
sc.add_to_subplot(BrainObj('B3'), use_this_cam=True, row=1, col=1)

###############################################################################
# 3D Time-series
###############################################################################
예제 #3
0
"""Test RoiObj."""
import numpy as np

from visbrain.objects.tests._testing_objects import _TestVolumeObject
from visbrain.objects import SourceObj, RoiObj
from visbrain.io import (download_file, path_to_visbrain_data, read_nifti,
                         clean_tmp)

roi_obj = RoiObj('brodmann')
roi_obj.select_roi([4, 6])
rnd = np.random.RandomState(0)
xyz = 100. * rnd.rand(50, 3)
xyz[:, 0] -= 50.
xyz[:, 1] -= 50.
s_obj = SourceObj('S1', xyz)

download_file('MIST_ROI.zip', unzip=True)
nifti_file = path_to_visbrain_data('MIST_ROI.nii.gz')
csv_file = path_to_visbrain_data('MIST_ROI.csv')
# Read the .csv file :
arr = np.genfromtxt(csv_file, delimiter=';', dtype=str)
# Get column names, labels and index :
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]
예제 #4
0
print(ref_brod.loc[idx_ba6])
roi_to_find1('aal')  # Switch to AAL
idx_sma = roi_to_find1.where_is('Supp Motor Area')

###############################################################################
# Extract the mesh of an ROI
###############################################################################
# Once you have the index of the ROI that you want to plot, use the
# :class:`visbrain.objects.RoiObj.select_roi` method to extract the mesh (i.e
# vertices and faces) of the ROI. Here, we illustrate this question with the
# brodmann 6 ROI

# Load the brodmann 6 atlas, get the index of BA6 and extract the mesh
roi_brod = RoiObj('brodmann')
idx_ba6 = roi_brod.where_is('BA6')
roi_brod.select_roi(select=idx_ba6)
# Define a brain object and add this brain and ROI objects to the scene
b_obj = BrainObj('B1')
sc.add_to_subplot(b_obj,
                  row=0,
                  col=0,
                  use_this_cam=True,
                  title='Brodmann area 6 mesh')
sc.add_to_subplot(roi_brod, row=0, col=0)

###############################################################################
# Set a unique color per ROI mesh
###############################################################################
# If you need, you can set a unique color per plotted ROI mesh. Here, we plot
# the left and right insula and thalamus and set a unique color to each
예제 #5
0
###############################################################################
# Project source's activity on the surface of the DMN
###############################################################################
# Here, we first use the MIST ROI to get represent the default mode network and
# then, we project source's activity onto the surface of the DMN

# Define the source and brain objects
s_dmn = SourceObj('dmn', xyz, data=rnd_data, mask=mask, mask_color='gray')
b_mask = BrainObj('B3')
# Define the MIST roi object
roi_dmn = RoiObj('mist_7')
# print(roi_dmn.get_labels())
# Get the index of the DMN and get the mesh
dmn_idx = roi_dmn.where_is('Default mode network')
roi_dmn.select_roi(dmn_idx)
# Project source's activity on the surface of the DMN
s_dmn.project_sources(roi_dmn, cmap='viridis', radius=15.)
sc.add_to_subplot(b_mask, row=2, col=2, use_this_cam=True, row_span=2,
                  title="Project source's activity\non the DMN")
sc.add_to_subplot(roi_dmn, row=2, col=2, row_span=2)

###############################################################################
# Project source's repartition on the surface of the brain
###############################################################################
# Similarly to the example above, we project here the repartition of sources
# which mean the number of contributing sources per vertex

# Define the source and brain objects
s_rep = SourceObj('proj', xyz, data=rnd_data)
b_rep = BrainObj('B3', translucent=False)
예제 #6
0
###############################################################################
# Project source's activity on the surface of the DMN
###############################################################################
# Here, we first use the MIST ROI to get represent the default mode network and
# then, we project source's activity onto the surface of the DMN

# Define the source and brain objects
s_dmn = SourceObj('dmn', xyz, data=rnd_data, mask=mask, mask_color='gray')
b_mask = BrainObj('B3')
# Define the MIST roi object
roi_dmn = RoiObj('mist_7')
# print(roi_dmn.get_labels())
# Get the index of the DMN and get the mesh
dmn_idx = roi_dmn.where_is('Default mode network')
roi_dmn.select_roi(dmn_idx)
# Project source's activity on the surface of the DMN
s_dmn.project_sources(roi_dmn, cmap='viridis', radius=15.)
sc.add_to_subplot(b_mask,
                  row=2,
                  col=2,
                  use_this_cam=True,
                  row_span=2,
                  title="Project source's activity\non the DMN")
sc.add_to_subplot(roi_dmn, row=2, col=2, row_span=2)

###############################################################################
# Project source's repartition on the surface of the brain
###############################################################################
# Similarly to the example above, we project here the repartition of sources
# which mean the number of contributing sources per vertex
예제 #7
0
"""Test RoiObj."""
import numpy as np

from visbrain.objects.tests._testing_objects import _TestVolumeObject
from visbrain.objects import SourceObj, RoiObj
from visbrain.io import (download_file, path_to_visbrain_data, read_nifti,
                         clean_tmp)


roi_obj = RoiObj('brodmann')
roi_obj.select_roi([4, 6])
rnd = np.random.RandomState(0)
xyz = 100. * rnd.rand(50, 3)
xyz[:, 0] -= 50.
xyz[:, 1] -= 50.
s_obj = SourceObj('S1', xyz)

download_file('MIST_ROI.zip', unzip=True, astype='example_data')
nifti_file = path_to_visbrain_data('MIST_ROI.nii.gz', 'example_data')
csv_file = path_to_visbrain_data('MIST_ROI.csv', 'example_data')
# Read the .csv file :
arr = np.genfromtxt(csv_file, delimiter=';', dtype=str)
# Get column names, labels and index :
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]
예제 #8
0
def engram(id):

    from .gui import Engram
    from visbrain.objects import RoiObj
    from .objects import SourceObj, ConnectObj
    from visbrain.io import download_file

    # Create an empty kwargs dictionnary :
    kwargs = {}

    # ____________________________ DATA ____________________________

    # Load the xyz coordinates and corresponding subject name :
    # mat = np.load(download_file('xyz_sample.npz', astype='example_data'))
    # xyz, subjects = mat['xyz'], mat['subjects']

    metadata = id.durations[0].metadata
    binary = id.durations[0].bins[0]

    positions = metadata['stream_pattern']['positions']
    assignments = metadata['stream_pattern']['hierarchy']

    SPACING = 6  # In MNI coordinates
    INITIAL_DISTINCTIONS = []

    n_dims = np.shape(assignments)[1]
    existing_levels = []
    intersection_matrices = {}
    intersection_matrices['indices'] = np.empty([])
    intersection_matrices['streams'] = np.empty([])
    intersection_matrices['positions'] = np.empty([])
    intersection_matrices['hierarchy_lookup'] = []

    # Derive Intersection Matrix
    for k, hierarchy in enumerate(assignments):
        if '' not in hierarchy:
            intersection = []
            for level, v in enumerate(hierarchy):
                if len(intersection_matrices['hierarchy_lookup']) <= level:
                    intersection_matrices['hierarchy_lookup'].append([])
                    intersection_matrices['hierarchy_lookup'][level].extend(
                        [v])
                if v not in intersection_matrices['hierarchy_lookup'][level]:
                    intersection_matrices['hierarchy_lookup'][level].extend(
                        [v])
                distinction = np.where(
                    np.asarray(intersection_matrices['hierarchy_lookup']
                               [level]) == v)[0][0]
                intersection.append(distinction)
            if intersection:
                intersection = np.expand_dims(np.array(intersection), axis=0)
                pos = np.expand_dims(np.array(positions[k]), axis=0)
                stream = np.expand_dims(np.array(metadata['all_streams'][k]),
                                        axis=0)
                source_count = np.expand_dims(np.arange(
                    np.array(
                        sum(binary.nD_labels['1D'] == metadata['all_streams']
                            [k]))),
                                              axis=0)
                if k is 0:
                    intersection_matrices['indices'] = intersection
                    intersection_matrices['streams'] = stream
                    intersection_matrices['sources'] = source_count
                    intersection_matrices['positions'] = pos

                else:
                    intersection_matrices['indices'] = np.append(
                        intersection_matrices['indices'], intersection, axis=0)
                    intersection_matrices['streams'] = np.append(
                        intersection_matrices['streams'], stream, axis=0)
                    intersection_matrices['sources'] = np.append(
                        intersection_matrices['sources'],
                        source_count +
                        intersection_matrices['sources'][k - 1][-1] + 1,
                        axis=0)
                    intersection_matrices['positions'] = np.append(
                        intersection_matrices['positions'], pos, axis=0)

    xyz = position_slicer(intersection_matrices,
                          method=INITIAL_DISTINCTIONS,
                          ignore_streams=True)

    # Convert binary array into visualizable continuous values
    print('Calculating spike durations')
    TRAIL = 100
    TIMEPOINTS = 100000
    spikes = binary.data.T[0:TIMEPOINTS]
    one_array = np.where(spikes == 1)
    if not not one_array:
        lb_1 = one_array[0] - TRAIL
        ub_1 = one_array[0]
        lb_2 = one_array[0]
        ub_2 = one_array[0] + TRAIL
        for ii in range(len(lb_1)):
            if ub_2[ii] > len(spikes):
                ub_2[ii] = len(spikes)
            if lb_1[ii] < 0:
                lb_1[ii] = 0

            spikes[lb_1[ii]:ub_1[ii],
                   one_array[1][ii]] += np.linspace(0, 1, ub_1[ii] - lb_1[ii])
            spikes[lb_2[ii]:ub_2[ii],
                   one_array[1][ii]] += np.linspace(1, 0, ub_2[ii] - lb_2[ii])

    spikes = spikes.T

    N = xyz.shape[0]  # Number of electrodes

    text = ['S' + str(k) for k in range(N)]
    s_obj = SourceObj('SourceObj1',
                      xyz,
                      data=spikes,
                      color='crimson',
                      text=text,
                      alpha=.5,
                      edge_width=2.,
                      radius_min=1.,
                      radius_max=25.)

    connect = np.zeros((N, N, np.shape(spikes)[1]))
    valid = np.empty((N, N, np.shape(spikes)[1]))
    edges = np.arange(N)

    print('Calculating connectivity')
    for ind, activity in enumerate(spikes):
        if ind < len(spikes):
            edge_activity = spikes[ind + 1:-1]
            weight = edge_activity + activity
            valid = ((edge_activity > 0) & (activity > 0)).astype('int')
            connect[ind, ind + 1:-1] = weight * valid

    umin = 0
    umax = np.max(spikes)

    c_obj = ConnectObj('ConnectObj1',
                       xyz,
                       connect,
                       color_by='strength',
                       dynamic=(.1, 1.),
                       cmap='gnuplot',
                       vmin=umin + .1,
                       vmax=umax - 1,
                       line_width=0.1,
                       clim=(umin, umax),
                       antialias=True)

    r_obj = RoiObj('aal')
    idx_rh = r_obj.where_is('Hippocampus (R)')
    idx_lh = r_obj.where_is('Hippocampus (L)')
    r_obj.select_roi(select=[idx_rh, idx_lh],
                     unique_color=False,
                     smooth=7,
                     translucent=True)

    vb = Engram(source_obj=s_obj,roi_obj=r_obj,connect_obj=c_obj,metadata=metadata,\
                rotation=0.1,carousel_metadata=intersection_matrices,\
                    carousel_display_method='text')
    vb.engram_control(template='B1', alpha=.02)
    vb.engram_control(visible=False)
    vb.connect_control(c_obj.name, visible=False)
    vb.sources_control(s_obj.name, visible=True)
    vb.rotate(custom=(180 - 45.0, 0.0))
    vb.show()
""")
file = download_file('lh.sig.nii.gz')
b_obj_fmri = BrainObj('inflated', translucent=False, sulcus=True)
b_obj_fmri.add_activation(file=file, clim=(5., 20.), hide_under=5,
                          cmap='viridis', hemisphere='left')
sc.add_to_subplot(b_obj_fmri, row=0, col=0, row_span=2,
                  title='fMRI activation', rotate='top')


print("""
===============================================================================
                           Region Of Interest (ROI)
===============================================================================
""")
roi_aal = RoiObj('aal')
roi_aal.select_roi(select=[29, 30], unique_color=True, smooth=11)
sc.add_to_subplot(roi_aal, row=0, col=1, title='Region Of Interest (ROI)')
sc.add_to_subplot(BrainObj('B1'), use_this_cam=True, row=0, col=1)

print("""
=============================================================================
                                    Sources
=============================================================================
""")
s_obj = SourceObj('FirstSources', xyz, data=data)
s_obj.color_sources(data=data, cmap='Spectral_r')
sc.add_to_subplot(s_obj, row=1, col=1, title='Sources')
sc.add_to_subplot(BrainObj('B3'), use_this_cam=True, row=1, col=1)


print("""
예제 #10
0
# Method 2 : use the `where_is` method
roi_to_find1('brodmann')  # Switch to Brodmann
idx_ba6 = roi_to_find1.where_is('BA6')  # Find only BA6
print(ref_brod.loc[idx_ba6])
roi_to_find1('aal')  # Switch to AAL
idx_sma = roi_to_find1.where_is(['Supp Motor Area', '(L)'], union=False)

# =============================================================================
#                              BRAIN + BA6
# =============================================================================
print('\n-> Plot brodmann area 6')
b_obj = BrainObj('B1')
roi_brod = RoiObj('brodmann')
idx_ba6 = roi_brod.where_is('BA6')
roi_brod.select_roi(select=idx_ba6)
roi_brod.get_labels(save_to_path=vb_path)  # print available brodmann labels
sc.add_to_subplot(roi_brod, row=0, col=0, title='Brodmann area 6')
sc.add_to_subplot(b_obj, row=0, col=0, use_this_cam=True)

# =============================================================================
#                       MULTIPLE ROI + UNIQUE COLORS
# =============================================================================
print('\n-> Select and plot multiple ROI with random unique colors')
roi_aal = RoiObj('aal')
roi_aal.select_roi(select=[29, 30, 77, 78], unique_color=True, smooth=11)
roi_aal.get_labels(save_to_path=vb_path)  # save available AAL labels
sc.add_to_subplot(roi_aal,
                  row=0,
                  col=1,
                  title='Select and plot multiple ROI with unique colors')
예제 #11
0
* 'brodmann' : Brodmann areas
* 'aal' : Automatic Anatomical Labeling
* 'talairach'

You can also define your own RoiObj with your own labels.
"""
roi_obj = RoiObj('aal', cblabel="Alpha power", border=False)
"""Find index of the thalamus and get the mesh.

If you want to get all of the index of the ROI template use :
* `roi_obj.get_labels()` : return a pandas DatFrame
* `roi_obj.get_labels('/home/')` : save all supported ROI and labels in an
  excel file.
"""
idx_thalamus = roi_obj.where_is('Thalamus')
roi_obj.select_roi(idx_thalamus, smooth=5)
"""Once the ROI object created, we can project source's alpha modulations
directly on the thalamus
"""
roi_obj.project_sources(s_obj,
                        cmap='Spectral_r',
                        clim=(200., 2000.),
                        vmin=300.,
                        under='gray',
                        vmax=1800.,
                        over='darkred')
"""You can also force sources to fit onto the thalamus
"""
# s_obj.fit_to_vertices(roi_obj.vertices)
"""
"""
예제 #12
0
# Load the xyz coordinates and corresponding subject name :
s_xyz = np.load(download_file('xyz_sample.npz', astype='example_data'))['xyz']

"""Create a source object with random data between [-50,50]
"""
s_data = np.random.uniform(-50, 50, s_xyz.shape[0])
s_obj = SourceObj('Sobj', s_xyz, data=s_data, color='darkred', alpha=.5,
                  radius_min=2., radius_max=8., edge_width=0.)

"""Create a Region of Interest Object (ROI) and display brodmann area 4 and 6
"""
roi_obj = RoiObj('brodmann')
idx_4_6 = roi_obj.where_is(['BA4', 'BA6'], exact=True)
roi_color = {idx_4_6[0]: 'red',    # BA4 in red and BA6 in green
             idx_4_6[1]: 'green'}
roi_obj.select_roi(idx_4_6, unique_color=True, roi_to_color=roi_color,
                   smooth=7)

"""Create a brain object
"""
b_obj = BrainObj('B1', hemisphere='both', translucent=True)

"""Pass the brain, source and ROI object to the GUI
"""
vb = Brain(brain_obj=b_obj, source_obj=s_obj, roi_obj=roi_obj)

"""Render the scene and save the jpg picture with a 300dpi
"""
save_as = os.path.join(save_pic_path, '0_main_brain.jpg')
vb.screenshot(save_as, dpi=300, print_size=(10, 10), autocrop=True)

"""Project source's activity onto the surface
예제 #13
0
                  data=s_data,
                  color='darkred',
                  alpha=.5,
                  radius_min=2.,
                  radius_max=8.,
                  edge_width=0.)
"""Create a Region of Interest Object (ROI) and display brodmann area 4 and 6
"""
roi_obj = RoiObj('brodmann')
idx_4_6 = roi_obj.where_is(['BA4', 'BA6'], exact=True)
roi_color = {
    idx_4_6[0]: 'red',  # BA4 in red and BA6 in green
    idx_4_6[1]: 'green'
}
roi_obj.select_roi(idx_4_6,
                   unique_color=True,
                   roi_to_color=roi_color,
                   smooth=7)
"""Create a brain object
"""
b_obj = BrainObj('B1', hemisphere='both', translucent=True)
"""Pass the brain, source and ROI object to the GUI
"""
vb = Brain(brain_obj=b_obj, source_obj=s_obj, roi_obj=roi_obj)
"""Render the scene and save the jpg picture with a 300dpi
"""
save_as = os.path.join(save_pic_path, '0_main_brain.jpg')
vb.screenshot(save_as, dpi=300, print_size=(10, 10), autocrop=True)
"""Project source's activity onto the surface
"""
vb.cortical_projection(clim=(0, 50),
                       cmap='Spectral_r',
예제 #14
0
* 'aal' : Automatic Anatomical Labeling
* 'talairach'

You can also define your own RoiObj with your own labels.
"""
roi_obj = RoiObj('aal', cblabel="Alpha power", border=False)

"""Find index of the thalamus and get the mesh.

If you want to get all of the index of the ROI template use :
* `roi_obj.get_labels()` : return a pandas DatFrame
* `roi_obj.get_labels('/home/')` : save all supported ROI and labels in an
  excel file.
"""
idx_thalamus = roi_obj.where_is('Thalamus')
roi_obj.select_roi(idx_thalamus, smooth=5)

"""Once the ROI object created, we can project source's alpha modulations
directly on the thalamus
"""
roi_obj.project_sources(s_obj, cmap='Spectral_r', clim=(200., 2000.),
                        vmin=300., under='gray', vmax=1800., over='darkred')

"""You can also force sources to fit onto the thalamus
"""
# s_obj.fit_to_vertices(roi_obj.vertices)

"""
"""
b_obj = BrainObj('B3')