def test_definition(self): """Test function definition.""" # Default : _ = [RoiObj(k) for k in ['aal', 'talairach', 'brodmann']] # noqa # MIST : levels = [7, 12, 20, 36, 64, 122, 'ROI'] _ = [RoiObj('mist_%s' % str(k)) for k in levels] # noqa
def test_save_and_remove_tmp(self): """Test methods save, reload and remove for tmp files.""" # Define the ROI object and save it : roi_custom = RoiObj('tmp_roi', vol=vol, labels=label, index=roi_index, hdr=hdr) roi_custom.save(tmpfile=True) # Test reloading roi from name only : RoiObj('tmp_roi') clean_tmp()
def test_save_and_remove_tmp(self): """Test methods save, reload and remove for tmp files.""" # Define the ROI object and save it : roi_custom = RoiObj('tmp_roi', vol=vol, labels=label, index=roi_index, hdr=hdr) roi_custom.save(tmpfile=True) # Test reloading roi from name only : RoiObj('tmp_roi') clean_tmp()
def test_save_and_remove(self): """Test methods save, reload and remove.""" # Define the ROI object and save it : roi_custom = RoiObj('mist_roi', vol=vol, labels=label, index=roi_index, hdr=hdr) roi_custom.save() # Test reloading roi from name only : roi_sec = RoiObj('mist_roi') roi_sec.remove()
def test_save_and_remove(self): """Test methods save, reload and remove.""" # Define the ROI object and save it : roi_custom = RoiObj('mist_roi', vol=vol, labels=label, index=roi_index, hdr=hdr) roi_custom.save() # Test reloading roi from name only : roi_sec = RoiObj('mist_roi') roi_sec.remove()
def test_where_is(self): """Test function where_is.""" r = RoiObj('aal') r.where_is('Thalamus') r.where_is(['Thalamus', '(L)'], union=False)
def __init__(self, canvas, **kwargs): """Init.""" # Create a root node : self._vbNode = scene.Node(name='Brain') self._vbNode.transform = vist.STTransform(scale=[self._gl_scale] * 3) logger.debug("Brain rescaled " + str([self._gl_scale] * 3)) PROFILER("Root node", level=1) # ========================= SOURCES ========================= self.sources = CombineSources(kwargs.get('source_obj', None)) if self.sources.name is None: self._obj_type_lst.model().item(4).setEnabled(False) # Disable menu : self.menuDispSources.setChecked(False) self.menuTransform.setEnabled(False) self.sources.parent = self._vbNode PROFILER("Sources object", level=1) # ========================= CONNECTIVITY ========================= self.connect = CombineConnect(kwargs.get('connect_obj', None)) if self.connect.name is None: self._obj_type_lst.model().item(5).setEnabled(False) self.menuDispConnect.setEnabled(False) self.connect.parent = self._vbNode PROFILER("Connect object", level=1) # ========================= TIME-SERIES ========================= self.tseries = CombineTimeSeries(kwargs.get('time_series_obj', None)) if self.tseries.name is None: self._obj_type_lst.model().item(6).setEnabled(False) self.tseries.parent = self._vbNode PROFILER("Time-series object", level=1) # ========================= PICTURES ========================= self.pic = CombinePictures(kwargs.get('picture_obj', None)) if self.pic.name is None: self._obj_type_lst.model().item(7).setEnabled(False) self.pic.parent = self._vbNode PROFILER("Pictures object", level=1) # ========================= VECTORS ========================= self.vectors = CombineVectors(kwargs.get('vector_obj', None)) if self.vectors.name is None: self._obj_type_lst.model().item(8).setEnabled(False) self.vectors.parent = self._vbNode PROFILER("Vectors object", level=1) # ========================= VOLUME ========================= # ----------------- Volume ----------------- if kwargs.get('vol_obj', None) is None: self.volume = VolumeObj('brodmann') self.volume.visible_obj = False else: self.volume = kwargs.get('vol_obj') if self.volume.name not in self.volume.list(): self.volume.save(tmpfile=True) self.volume.parent = self._vbNode PROFILER("Volume object", level=1) # ----------------- ROI ----------------- if kwargs.get('roi_obj', None) is None: self.roi = RoiObj('brodmann') self.roi.visible_obj = False else: self.roi = kwargs.get('roi_obj') if self.roi.name not in self.roi.list(): self.roi.save(tmpfile=True) self.roi.parent = self._vbNode PROFILER("ROI object", level=1) # ----------------- Cross-sections ----------------- if kwargs.get('cross_sec_obj', None) is None: self.cross_sec = CrossSecObj('brodmann') else: self.cross_sec = kwargs.get('cross_sec_obj') if self.cross_sec.name not in self.cross_sec.list(): self.cross_sec.save(tmpfile=True) self.cross_sec.visible_obj = False self.cross_sec.text_size = 2. self.cross_sec.parent = self._csView.wc.scene self._csView.camera = self.cross_sec._get_camera() self.cross_sec.set_shortcuts_to_canvas(self._csView) PROFILER("Cross-sections object", level=1) # ========================= BRAIN ========================= if kwargs.get('brain_obj', None) is None: self.atlas = BrainObj('B1') else: self.atlas = kwargs['brain_obj'] if self.atlas.name not in self.atlas.list(): self.atlas.save(tmpfile=True) self.atlas.scale = self._gl_scale self.atlas.parent = self._vbNode PROFILER("Brain object", level=1)
def test_where_is(self): """Test function where_is.""" r = RoiObj('aal') r.where_is('Thalamus') r.where_is(['Thalamus', '(L)'], union=False)
"""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]
# Project source's activity on the surface of the brain s_mask.project_sources(b_mask, cmap='viridis', radius=15.) sc.add_to_subplot(b_mask, row=2, col=1, title="Project masked source's activity") ############################################################################### # 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
distance=800 * 100, ) CBAR_STATE = dict(cbtxtsz=12, txtsz=10., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.)) sc = SceneObj(camera_state=CAM_STATE, bgcolor=(.1, .1, .1), size=(1400, 1000)) # ============================================================================= # FIND INDEX OF AN ROI # ============================================================================= """Here, we illustrate how to find the integer index of the ROI to plot """ # Method 1 : save all ROI in an excel file and search manually the ROI roi_to_find1 = RoiObj('brodmann') # Use Brodmann areas ref_brod = roi_to_find1.get_labels(vb_path) # Save Brodmann roi_to_find1('aal') # Switch to AAL ref_aal = roi_to_find1.get_labels(vb_path) # Save AAL roi_to_find1('talairach') # Switch to Talairach ref_tal = roi_to_find1.get_labels(vb_path) # Save Talairach # 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
"""Create a source object """ s_obj = SourceObj('ThalamusSources', s_xyz, data=s_data, color='#ab4642', radius_min=10., radius_max=20.) """Create a ROI object. The ROI object comes with three default templates : * '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.),
from visbrain.io import download_file, path_to_visbrain_data save_pic_path = path_to_visbrain_data(folder='Example_pic') # 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
# 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)
s_xyz = np.loadtxt(thalamus_xyz) s_data = np.load(thalamus_data).mean(1) """Create a source object """ s_obj = SourceObj('ThalamusSources', s_xyz, data=s_data, color='#ab4642', radius_min=10., radius_max=20.) """Create a ROI object. The ROI object comes with three default templates : * '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.),
from visbrain.objects.tests._testing_objects import _TestObjects # Source's data : n_sources = 20 s_xyz = np.random.uniform(-20, 20, (n_sources, 3)) s_data = np.random.rand(n_sources) s_color = np.random.uniform(.1, .9, (n_sources, 4)) s_mask = s_data >= .7 s_text = ['S%s' % str(k) for k in range(n_sources)] # Vertices (for projection) n_vertices, n_faces = 100, 50 vertices_x3 = s_xyz.max() * np.random.rand(n_vertices, 3, 3) vertices = s_xyz.max() * np.random.rand(n_vertices, 3) b_obj = BrainObj('B3') roi_obj = RoiObj('talairach') s_obj = SourceObj('S1', s_xyz, data=s_data, color=s_color, alpha=.7, symbol='x', radius_min=10.7, radius_max=25.8, edge_width=1.4, edge_color='green', system='tal', mask=s_mask, mask_color='#ab4642', text=s_text,
############################################################################### # ROIs are defined with two variables : 1) a volume which contains integers # and 2) a vector of labels which link every integer inside the volume with a # label (for example, with the brodmann atlas, the index 4 refers to the label # brodmann 4). Here, we illustrate how to find the index of a region of # interest ##################################### # **Method 1 :** export all ROI labels and indices in an excel file # # This first method load a ROI atlas then, we use the # :class:`visbrain.objects.RoiObj.get_labels` method to save every related ROI # informations in an excel file. This first method implies that you manually # inspect in this file the index of the ROI that you're looking for. roi_to_find1 = RoiObj('brodmann') # Use Brodmann areas ref_brod = roi_to_find1.get_labels(vb_path) # Save Brodmann roi_to_find1('aal') # Switch to AAL ref_aal = roi_to_find1.get_labels(vb_path) # Save AAL roi_to_find1('talairach') # Switch to Talairach # ref_tal = roi_to_find1.get_labels(vb_path) # Save Talairach ##################################### # **Method 2 :** explicitly search where is the ROI that you're looking for # # Here, we use the :class:`visbrain.objects.RoiObj.where_is` method of the ROI # object to explicitly search string patterns # 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
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()
############################################################################### # 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
============================================================================= """) 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)
def test_definition(self): """Test function definition.""" for k in ['aal', 'talairach', 'brodmann']: RoiObj(k)
def __init__(self, canvas, **kwargs): """Init.""" # Create a root node : self._vbNode = scene.Node(name='Engram') self._vbNode.transform = vist.STTransform(scale=[self._gl_scale] * 3) logger.debug("Engram rescaled " + str([self._gl_scale] * 3)) PROFILER("Root node", level=1) # ========================= SOURCES ========================= self.sources = CombineSources(kwargs.get('source_obj', None)) if self.sources.name is None: self._obj_type_lst.model().item(4).setEnabled(False) # Disable menu : self.menuDispSources.setChecked(False) self.menuTransform.setEnabled(False) self.sources.parent = self._vbNode PROFILER("Sources object", level=1) # ========================= CONNECTIVITY ========================= self.connect = CombineConnect(kwargs.get('connect_obj', None)) if self.connect.name is None: self._obj_type_lst.model().item(5).setEnabled(False) self.menuDispConnect.setEnabled(False) self.connect.parent = self._vbNode PROFILER("Connect object", level=1) # ========================= TIME-SERIES ========================= self.tseries = CombineTimeSeries(kwargs.get('time_series_obj', None)) if self.tseries.name is None: self._obj_type_lst.model().item(6).setEnabled(False) self.tseries.parent = self._vbNode PROFILER("Time-series object", level=1) # ========================= PICTURES ========================= self.pic = CombinePictures(kwargs.get('picture_obj', None)) if self.pic.name is None: self._obj_type_lst.model().item(7).setEnabled(False) self.pic.parent = self._vbNode PROFILER("Pictures object", level=1) # ========================= VECTORS ========================= self.vectors = CombineVectors(kwargs.get('vector_obj', None)) if self.vectors.name is None: self._obj_type_lst.model().item(8).setEnabled(False) self.vectors.parent = self._vbNode PROFILER("Vectors object", level=1) # ========================= VOLUME ========================= # ----------------- Volume ----------------- if kwargs.get('vol_obj', None) is None: self.volume = VolumeObj('brodmann') self.volume.visible_obj = False else: self.volume = kwargs.get('vol_obj') if self.volume.name not in self.volume.list(): self.volume.save(tmpfile=True) self.volume.parent = self._vbNode PROFILER("Volume object", level=1) # ----------------- ROI ----------------- if kwargs.get('roi_obj', None) is None: self.roi = RoiObj('brodmann') self.roi.visible_obj = False else: self.roi = kwargs.get('roi_obj') if self.roi.name not in self.roi.list(): self.roi.save(tmpfile=True) self.roi.parent = self._vbNode PROFILER("ROI object", level=1) # ----------------- Cross-sections ----------------- if kwargs.get('cross_sec_obj', None) is None: self.cross_sec = CrossSecObj('brodmann') else: self.cross_sec = kwargs.get('cross_sec_obj') if self.cross_sec.name not in self.cross_sec.list(): self.cross_sec.save(tmpfile=True) self.cross_sec.visible_obj = False self.cross_sec.text_size = 2. self.cross_sec.parent = self._csView.wc.scene self._csView.camera = self.cross_sec._get_camera() self.cross_sec.set_shortcuts_to_canvas(self._csView) PROFILER("Cross-sections object", level=1) # ========================= ENGRAM ========================= if kwargs.get('engram_obj', None) is None: self.atlas = BrainObj('B1') else: self.atlas = kwargs['engram_obj'] if self.atlas.name not in self.atlas.list(): self.atlas.save(tmpfile=True) self.atlas.scale = self._gl_scale self.atlas.parent = self._vbNode PROFILER("Engram object", level=1)
title='Masked sources between [-20., 20.]\nare orange', **S_KW) ############################################################################### # Get anatomical informations of sources ############################################################################### # The region of interest object (RoiObj) is basically a volume where each voxel # is known to be part of an anatomical region. Hence, you can define the RoiObj # and use it to get the anatomical informations of each source # First, create a basic source object s_obj_ba = SourceObj('S4', xyz) # Then, we define a region of interest object (RoiObj). We use brodmann areas # but you should take a look to the complete tutorial on ROIs because visbrain # povides several templates (Brodmann, AAL, Talairach and MIST) roi_obj = RoiObj('brodmann') # If you want to see labels associated with the brodmann areas, uncomment the # following line # print(roi_obj.get_labels()) # Now, analyse sources using the RoiObj. The argument returned by the # `SourceObj.analyse_sources` method is a Pandas dataframe df_brod = s_obj_ba.analyse_sources(roi_obj=roi_obj) # The dataframe contains a column `brodmann` which is the name of the # associated brodmann area. Hence, we use it to color sources according to the # name of brodmann area s_obj_ba.color_sources(analysis=df_brod, color_by='brodmann') # Finally, add the object to the scene sc.add_to_subplot(s_obj_ba, row=1, col=0, title='Color sources according to\n Brodmann area',
"""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]
############################################################################### # ROIs are defined with two variables : 1) a volume which contains integers # and 2) a vector of labels which link every integer inside the volume with a # label (for example, with the brodmann atlas, the index 4 refers to the label # brodmann 4). Here, we illustrate how to find the index of a region of # interest ##################################### # **Method 1 :** export all ROI labels and indices in an excel file # # This first method load a ROI atlas then, we use the # :class:`visbrain.objects.RoiObj.get_labels` method to save every related ROI # informations in an excel file. This first method implies that you manually # inspect in this file the index of the ROI that you're looking for. roi_to_find1 = RoiObj('brodmann') # Use Brodmann areas ref_brod = roi_to_find1.get_labels(vb_path) # Save Brodmann roi_to_find1('aal') # Switch to AAL ref_aal = roi_to_find1.get_labels(vb_path) # Save AAL roi_to_find1('talairach') # Switch to Talairach # ref_tal = roi_to_find1.get_labels(vb_path) # Save Talairach ##################################### # **Method 2 :** explicitly search where is the ROI that you're looking for # # Here, we use the :class:`visbrain.objects.RoiObj.where_is` method of the ROI # object to explicitly search string patterns # 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
class Visuals(object): """Initialize Brain objects. Initialize sources / connectivity / areas / colorbar / projections. Organize them at diffrent levels and make the link with the graphical user interface (if no object is detected, the corresponding panel in the GUI has to be deactivate). """ def __init__(self, canvas, **kwargs): """Init.""" # Create a root node : self._vbNode = scene.Node(name='Brain') self._vbNode.transform = vist.STTransform(scale=[self._gl_scale] * 3) logger.debug("Brain rescaled " + str([self._gl_scale] * 3)) PROFILER("Root node", level=1) # ========================= SOURCES ========================= self.sources = CombineSources(kwargs.get('source_obj', None)) if self.sources.name is None: self._obj_type_lst.model().item(4).setEnabled(False) # Disable menu : self.menuDispSources.setChecked(False) self.menuTransform.setEnabled(False) self.sources.parent = self._vbNode PROFILER("Sources object", level=1) # ========================= CONNECTIVITY ========================= self.connect = CombineConnect(kwargs.get('connect_obj', None)) if self.connect.name is None: self._obj_type_lst.model().item(5).setEnabled(False) self.menuDispConnect.setEnabled(False) self.connect.parent = self._vbNode PROFILER("Connect object", level=1) # ========================= TIME-SERIES ========================= self.tseries = CombineTimeSeries(kwargs.get('time_series_obj', None)) if self.tseries.name is None: self._obj_type_lst.model().item(6).setEnabled(False) self.tseries.parent = self._vbNode PROFILER("Time-series object", level=1) # ========================= PICTURES ========================= self.pic = CombinePictures(kwargs.get('picture_obj', None)) if self.pic.name is None: self._obj_type_lst.model().item(7).setEnabled(False) self.pic.parent = self._vbNode PROFILER("Pictures object", level=1) # ========================= VECTORS ========================= self.vectors = CombineVectors(kwargs.get('vector_obj', None)) if self.vectors.name is None: self._obj_type_lst.model().item(8).setEnabled(False) self.vectors.parent = self._vbNode PROFILER("Vectors object", level=1) # ========================= VOLUME ========================= # ----------------- Volume ----------------- if kwargs.get('vol_obj', None) is None: self.volume = VolumeObj('brodmann') self.volume.visible_obj = False else: self.volume = kwargs.get('vol_obj') if self.volume.name not in self.volume.list(): self.volume.save(tmpfile=True) self.volume.parent = self._vbNode PROFILER("Volume object", level=1) # ----------------- ROI ----------------- if kwargs.get('roi_obj', None) is None: self.roi = RoiObj('brodmann') self.roi.visible_obj = False else: self.roi = kwargs.get('roi_obj') if self.roi.name not in self.roi.list(): self.roi.save(tmpfile=True) self.roi.parent = self._vbNode PROFILER("ROI object", level=1) # ----------------- Cross-sections ----------------- if kwargs.get('cross_sec_obj', None) is None: self.cross_sec = CrossSecObj('brodmann') else: self.cross_sec = kwargs.get('cross_sec_obj') if self.cross_sec.name not in self.cross_sec.list(): self.cross_sec.save(tmpfile=True) self.cross_sec.visible_obj = False self.cross_sec.text_size = 2. self.cross_sec.parent = self._csView.wc.scene self._csView.camera = self.cross_sec._get_camera() self.cross_sec.set_shortcuts_to_canvas(self._csView) PROFILER("Cross-sections object", level=1) # ========================= BRAIN ========================= if kwargs.get('brain_obj', None) is None: self.atlas = BrainObj('B1') else: self.atlas = kwargs['brain_obj'] if self.atlas.name not in self.atlas.list(): self.atlas.save(tmpfile=True) self.atlas.scale = self._gl_scale self.atlas.parent = self._vbNode PROFILER("Brain object", level=1)