def _plt_src(name, kw_brain_obj, active_data, active_vert, sources, kw_source_obj, kw_activation, show): # Define a brain object and a source object : logger.info(' Define a Brain and Source objects') from visbrain.objects import BrainObj, SourceObj, SceneObj brain_obj, source_obj = name + '_brain', name + '_sources' b_obj = BrainObj(brain_obj, **kw_brain_obj) s_obj = SourceObj(source_obj, sources, **kw_source_obj) s_obj.visible_obj = False # Add data to the BrainObj if needed : if isinstance(active_data, np.ndarray): logger.info(" Add active data between " "[%2f, %2f]" % (active_data.min(), active_data.max())) b_obj.add_activation(data=active_data, vertices=active_vert, **kw_activation) # Return either a scene or a BrainObj and SourceObj : if show is True: # Display inside the Brain GUI # Define a Brain instance : from visbrain.gui import Brain brain = Brain(brain_obj=b_obj, source_obj=s_obj) brain._brain_template.setEnabled(False) # By default, display colorbar if activation : if isinstance(active_data, np.ndarray): brain.menuDispCbar.setChecked(True) brain._fcn_menu_disp_cbar() brain.show() elif show is 'scene': # return a SceneObj logger.info(" Define a unique scene for the Brain and Source " "objects") sc = SceneObj() sc.add_to_subplot(s_obj) sc.add_to_subplot(b_obj, use_this_cam=True) return sc else: # return the BrainObj and SourceObj s_obj.visible_obj = True return b_obj, s_obj
kwargs['s_data'] = np.random.rand(N) kwargs['s_radiusmin'] = 1. kwargs['s_radiusmax'] = 20. n_connections = 150 rnd_selection = np.random.randint(0, N**2, n_connections) connect = np.random.randint(0, 20, (N, N)) mask = np.ones(N**2, dtype=bool) mask[rnd_selection] = False mask = mask.reshape(N, N) connect = np.ma.masked_array(connect, mask=mask) kwargs['c_connect'] = connect kwargs['ui_bgcolor'] = 'white' vb = Brain(**kwargs) # ============= Sources ============= # # Screenshot of the default view : vb.screenshot('default.png', autocrop=True) # Hide sources that are not in the brain : vb.sources_display('inside') vb.screenshot('inside.png', autocrop=True) # ============= Connectivity ============= # Colorby network density : vb.sources_display('none') vb.connect_control(show=True, cmap='magma', colorby='density',
time = np.tile(time[np.newaxis, ...], (n_sources, 1, 1)) coef = s_xyz[:, 0].reshape(-1, 1, 1) / 2. data = np.sinc(coef * 2 * np.pi * 1. * time) data += .2 * np.random.rand(*data.shape) """If you want to remove some pictures, define a pic_select array of boolean values and specify if those pictures has to be hide or displayed : """ pic_select = np.ones((n_sources,), dtype=bool) pic_to_hide = [2, 6, 10, 11, 31, 35, 41, 44, 51, 55] pic_select[pic_to_hide] = False kwargs['select'] = pic_select kwargs['pic_width'] = 5. # Width kwargs['pic_height'] = 5. # Height kwargs['translate'] = (4., 5., 1.) # Offset along (x, y, z) axis kwargs['clim'] = (.01, 1.12) # Colorbar limits kwargs['cmap'] = 'viridis' # Colormap kwargs['vmin'] = .1 # Vmin kwargs['under'] = 'gray' # Color under vmin kwargs['vmax'] = .9 # Vmax kwargs['over'] = '#ab4642' # Color over vmax kwargs['cblabel'] = '3D Pictures' # Color over vmax """Define the 3-D picture object """ pic = Picture3DObj('Pic', data, s_xyz, **kwargs) vb = Brain(picture_obj=pic, source_obj=s_obj) vb.show()
n_time_points = 700 # Number of time points n_sources = s_xyz.shape[0] # Number of sources time = np.mgrid[0:n_sources, 0:n_time_points][1] / sf # Time vector # Randomize the amplitude and the phase of sine : amp = np.random.randint(2, 20, n_sources).reshape(-1, 1) pha = np.random.randint(1, 7, n_sources).reshape(-1, 1) # Build the time series of shape (n_sources, n_time_points) : ts_data = amp * np.sin(2 * np.pi * pha * time) ts_data += np.random.randn(n_sources, n_time_points) # Use a boolean vector to hide/display time-series : ts_to_mask = [5, 7, 11, 3, 14, 17, 22, 23] ts_select = np.ones((s_xyz.shape[0],), dtype=bool) ts_select[ts_to_mask] = False # Time-series (TS) graphical properties : ts_amp = 5.4 # TS graphical amplitude ts_width = 15.7 # TS graphical width ts_color = 'orange' # TS color ts_dxyz = (1., 2., 5.) # TS offset along the (x, y, z) axes ts_lw = 2.2 # TS line-width """Define the 3-D time-series object """ ts = TimeSeries3DObj('Ts1', ts_data, s_xyz, select=ts_select, ts_amp=ts_amp, ts_width=ts_width, line_width=ts_lw, translate=ts_dxyz, color=ts_color) vb = Brain(time_series_obj=ts, source_obj=s_obj) vb.show()
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 """ data = np.arange(len(select)) b_obj.parcellize(path_to_file2, hemisphere='right', select=select, data=data, cmap='Spectral_r') """Finally, pass the brain object to `Brain` and disply the GUI """ Brain(brain_obj=b_obj).show()
""" Display fMRI activation ======================= Display fMRI activations from a nii.gz file (NiBabel required). See the original example : https://pysurfer.github.io/auto_examples/plot_fmri_activation.html#sphx-glr-auto-examples-plot-fmri-activation-py .. image:: ../../_static/examples/ex_eegmeg_fmri_activations.png """ from visbrain.gui import Brain from visbrain.objects import BrainObj from visbrain.io import download_file """Download file if needed """ file = download_file('lh.sig.nii.gz', astype='example_data') b_obj = BrainObj('inflated', translucent=False, sulcus=True) b_obj.add_activation(file=file, clim=(5., 20.), hide_under=5, cmap='viridis', hemisphere='left') vb = Brain(brain_obj=b_obj) vb.rotate('left') vb.show()
from visbrain.objects import VolumeObj, CrossSecObj, SourceObj from visbrain.io import download_file """Download two NIFTI files """ path_1 = download_file('GG-853-GM-0.7mm.nii.gz', astype='example_data') path_2 = download_file('GG-853-WM-0.7mm.nii.gz', astype='example_data') """Define four sources sources and a Source object """ s_xyz = np.array([[29.9, -37.3, -19.3], [-5.33, 14.00, 20.00], [25.99, 14.00, 34.66], [0., -1.99, 10.66]]) s_obj = SourceObj('MySources', s_xyz) """Define a volume object and a cross-section object """ vol_obj = VolumeObj(path_1) cross_sec_obj = CrossSecObj(path_2) """Localize a source in the cross-section object """ cross_sec_obj.localize_source(s_xyz[2, :]) """Define a Brain instance and pass the source, volume and cross-section object """ vb = Brain(source_obj=s_obj, vol_obj=vol_obj, cross_sec_obj=cross_sec_obj) vb.show()
# Additional inputs for SourceObj : kw_s_obj = dict(color='blue', symbol='square') # Additional inputs for activations (colormap, clim...) : kw_activation = dict(cmap='viridis', hide_under=10000, clim=(active_data.min(), active_data.max()), vmax=20000, over='red') ############################################################################### # Get the brain and source objects ############################################################################### # Note that here, we use `show=False`. In that case, a # :class:`visbrain.objects.BrainObj` and a :class:`visbrain.objects.SourceObj` # are returned. b_obj, s_obj = mne_plot_source_space(fif_file, active_data=active_data, kw_brain_obj=kw_b_obj, kw_source_obj=kw_s_obj, kw_activation=kw_activation, show=False) ############################################################################### # Pass the brain and source objects to the :class:`visbrain.Brain` module ############################################################################### # Note that here, we pass the source object to Brain but by default we set it # as not visible. But if you don't need to see it, simply remove the # `source_obj=s_obj` s_obj.visible_obj = False brain = Brain(brain_obj=b_obj, source_obj=s_obj) brain.show()
.. image:: ../../_static/examples/ex_add_nifti.png """ from __future__ import print_function import numpy as np from visbrain.gui import Brain from visbrain.objects import VolumeObj, CrossSecObj, SourceObj from visbrain.io import download_file """Download two NIFTI files """ path_1 = download_file('GG-853-GM-0.7mm.nii.gz', astype='example_data') path_2 = download_file('GG-853-WM-0.7mm.nii.gz', astype='example_data') """Define four sources sources and a Source object """ s_xyz = np.array([[29.9, -37.3, -19.3], [-5.33, 14.00, 20.00], [25.99, 14.00, 34.66], [0., -1.99, 10.66]]) s_obj = SourceObj('MySources', s_xyz) """Define a volume object and a cross-section object """ vol_obj = VolumeObj(path_1) cross_sec_obj = CrossSecObj(path_2) """Localize a source in the cross-section object """ cross_sec_obj.localize_source(s_xyz[2, :]) """Define a Brain instance and pass the source, volume and cross-section object """ vb = Brain(source_obj=s_obj, vol_obj=vol_obj, cross_sec_obj=cross_sec_obj) vb.show()
n = len(b_obj) # Get the number of vertices dtype = [('vertices', float, 3), ('normals', float, 3)] # Arrows dtype arrows = np.zeros(n, dtype=dtype) # Empty arrows array arrows['vertices'] = b_obj.vertices # Set the vertices arrows['normals'] = b_obj.normals # Set the normals # For the data, we use the distance between 0 and each vertex data = np.linalg.norm(b_obj.vertices, axis=1) # We only select vectors with a distance in [60., 60.2] select = np.logical_and(data >= 60., data <= 60.2) v_obj3 = VectorObj('v3', arrows, data=data, select=select, line_width=2., arrow_size=7., arrow_type='inhibitor_round', antialias=True, cmap='Spectral_r', vmin=60.05, under='gray') # Finally, re-select both brain hemispheres. b_obj.hemisphere = 'both' vb = Brain(brain_obj=b_obj, vector_obj=[v_obj1, v_obj2, v_obj3], source_obj=[s_obj, s_obj2]) vb.show()
# ---------------- ROI // Volume // Cross-sections ---------------- # ROI : roi_obj = RoiObj('brodmann') roi_obj.select_roi([4, 6]) # Volume : vol_obj = VolumeObj('aal') # Cross-sections : cs_obj = CrossSecObj('aal') cs_obj.cut_coords((50, 60, 70)) # ---------------- Application ---------------- vb = Brain(source_obj=[s_obj1, s_obj2], connect_obj=[c_obj, c_obj2], time_series_obj=[ts_obj1, ts_obj2], picture_obj=[p_obj1, p_obj2], roi_obj=roi_obj, vol_obj=vol_obj, cross_sec_obj=cs_obj, verbose='debug') class TestBrain(_TestVisbrain): """Test brain.py.""" ########################################################################### # BRAIN ########################################################################### def test_scene_rotation(self): """Test scene rotations/.""" rotations = [ 'axial_0', 'coronal_0', 'sagittal_0', 'axial_1', 'coronal_1',
connect.mask[np.logical_or(connect.data < min, connect.data > max)] = True return connect """Create two connectivity objects. """ connect_l = create_connect(s_xyz_l, -.5, .2) c_obl_l = ConnectObj('C_left', s_xyz_l, connect_l, color_by='strength', dynamic=(.1, 1.), cmap='viridis', vmin=0., vmax=.1, under='gray', over='red') connect_rb = create_connect(s_xyz_rb, -.5, .2) c_obj_rb = ConnectObj('C_right_back', s_xyz_rb, connect_rb, color_by='count', alpha=.7, cmap='plasma') """Finally, open _Brain_ with those list of objects """ vb = Brain(source_obj=[s_obj_l, s_obj_rb, s_obj_rf], connect_obj=[c_obl_l, c_obj_rb]) vb.show()
def visualise_brain(b_obj): """Opens Visbrain GUI with colored ROI """ vb = Brain(brain_obj=b_obj, bgcolor='black') vb.show()
""" # b_obj = BrainObj('B3', translucent=False) """You can also select a specific hemisphere """ # b_obj = BrainObj('B3', translucent=False, hemisphere='left') # 'right' """For the inflated, white and translucent templates, sulcus can be also used """ # b_obj = BrainObj('inflated', translucent=False, hemisphere='right', # sulcus=True) """Once the brain object created, pass it to the graphical user interface. If you want to control the brain from the GUI, go to the Objects tab and select 'Brain' from the first combo box. You can also use the key shortcut b to display/hide the brain. """ vb = Brain(brain_obj=b_obj, bgcolor='slateblue') """Display opaque right hemisphere of B3 : """ # vb.brain_control(template='B3', hemisphere='right', translucent=False) """ Fixed frontal view """ # vb.rotate(fixed='front') """ Display transparent left hemisphere of B2 """ # vb.brain_control(template='B2', hemisphere='left', alpha=.05) """ Custom rotation * azimuth = -34° * elevation = 74°
See : https://brainder.org/download/flair/ .. image:: ../../_static/examples/ex_crossec_and_volume.png """ from visbrain.gui import Brain from visbrain.objects import CrossSecObj, VolumeObj from visbrain.io import download_file """Import the volume and the associated affine transformation """ volume_name = 'GG-853-WM-0.7mm.nii.gz' # 'GG-853-GM-0.7mm.nii.gz' """Download the file. """ path = download_file(volume_name, astype='example_data') """Define a cross-section object Go to the Objects tab and select 'Cross-section' in the combo box. You can also press x to display the cross-section panel. """ cs_obj = CrossSecObj(path, coords=(0., 0., 0.), cmap='gist_stern') """Define a volume object. Go to the Objects tab and select 'Volume' in the combo box. You can also press x to display the volume panel. """ v_obj = VolumeObj(path) """Create the GUI and pass the cross-section and the volume object """ vb = Brain(cross_sec_obj=cs_obj, vol_obj=v_obj) vb.show()
#print('1 and 2 equivalent :', np.array_equal(select, ~connect.mask + 0)) """Create the connectivity object : """ c_obj = ConnectObj('ConnectObj1', xyz, connect, color_by='strength', cmap='Greys', vmin=small_weight_threshold, vmax=large_weight_threshold, under='blue', over='red', antialias=True) """Finally, pass source and connectivity objects to Brain : """ vb = Brain(source_obj=s_obj, connect_obj=c_obj) vb.brain_control(alpha=0.1, hemisphere='both') rotation = 'axial_0' vb.rotate('axial_0') # top #vb.rotate('axial_1') #bottom #vb.rotate('sagittal_0') # left #vb.rotate('sagittal_1') # right #vb.rotate('coronal_0') # front #vb.rotate('coronal_1') # back # Save the brain vb.screenshot('main2.png', canvas='main', print_size=(10, 20), dpi=300,
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') # Define a Brain instance : vb = Brain(brain_obj=b_obj, source_obj=s_obj, roi_obj=roi_obj) """Select the colorbar of the ROI """ vb.cbar_select('roi') """Eventualy, take a screenshot """ # vb.screenshot('thalamus.png', autocrop=True) # Show the interface : vb.show()
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', vmin=10.1, under='black', vmax=41.2, over='green') vb.sources_control('Sobj', visible=False) # Hide sources vb.rotate(custom=(-160., 10.)) # Rotate the brain vb.brain_control(translucent=False) # Make the brain opaque
"""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', vmin=10.1, under='black', vmax=41.2, over='green') vb.sources_control('Sobj', visible=False) # Hide sources vb.rotate(custom=(-160., 10.)) # Rotate the brain vb.brain_control(translucent=False) # Make the brain opaque """Now, we take a screenthot of the scene but this time, we used the
from visbrain.io import download_file """Download and the load the Custom.npz archive. This file contains vertices and faces of a brain template that is not integrated by default in Visbrain. """ mat = np.load(download_file('Custom.npz', astype='example_data')) """Get vertices and faces from the archive. In this examples, normals are also present in the archive. If you don't have the normals, the BrainObj will compute it automatically. """ vert, faces, norms = mat['vertices'], mat['faces'], mat['normals'] """Define the brain object """ b_obj = BrainObj('Custom', vertices=vert, faces=faces, normals=norms) """Then you have two strategies : * If you are going to use this template a lot and don't want to redefine it every times, use `b_obj.save()`. Once the object saved, it can be reloaded using its name only `BrainObj('Custom')` * If you only need it once, the template is temporaly saved and remove once the GUI is closed. """ # b_obj.save() # b_obj = BrainObj('Custom') """Define the GUI and pass the brain template """ vb = Brain(brain_obj=b_obj) vb.show() # If you want to remove the template : # b_obj.remove()
kwargs['s_data'] = np.random.rand(N) kwargs['s_radiusmin'] = 1. kwargs['s_radiusmax'] = 20. n_connections = 150 rnd_selection = np.random.randint(0, N ** 2, n_connections) connect = np.random.randint(0, 20, (N, N)) mask = np.ones(N ** 2, dtype=bool) mask[rnd_selection] = False mask = mask.reshape(N, N) connect = np.ma.masked_array(connect, mask=mask) kwargs['c_connect'] = connect kwargs['ui_bgcolor'] = 'white' vb = Brain(**kwargs) # ============= Sources ============= # # Screenshot of the default view : vb.screenshot('default.png', autocrop=True) # Hide sources that are not in the brain : vb.sources_display('inside') vb.screenshot('inside.png', autocrop=True) # ============= Connectivity ============= # Colorby network density : vb.sources_display('none') vb.connect_control(show=True, cmap='magma', colorby='density', clim=(0., 35.), vmin=10., vmax=30., under='gray', over='darkred',
"""Create the source object. If you want to previsualize the result without opening Brain, use s_obj.preview() """ s_obj = SourceObj('SourceExample', xyz, **kwargs) # s_obj.preview() """Color sources according to the data """ # s_obj.color_sources(data=kwargs['data'], cmap='viridis') """Colorbar properties """ cb_kw = dict( cblabel="Project source activity", cbtxtsz=3., border=False, ) """Define a brain object with the B3 template and project source's activity onto the surface """ b_obj = BrainObj('B3', **cb_kw) b_obj.project_sources(s_obj, cmap='viridis', vmin=50., under='orange', vmax=550., over='darkred') """Create a Brain instance and pass both of the brain and source object defined After the interface is opened, press C to display the colorbar. """ vb = Brain(source_obj=s_obj, brain_obj=b_obj) vb.show()
""" Display conjunction map ======================= Display a conjunction map from a nii.gz file (NiBabel required). See the original PySurfer example : https://pysurfer.github.io/auto_examples/plot_fmri_conjunction.html#sphx-glr-auto-examples-plot-fmri-conjunction-py .. image:: ../../_static/examples/ex_eegmeg_conjunction_map.png """ from visbrain.gui import Brain from visbrain.objects import BrainObj from visbrain.io import download_file """Download files if needed """ file_1 = download_file('lh.sig.nii.gz', astype='example_data') file_2 = download_file('lh.alt_sig.nii.gz', astype='example_data') b_obj = BrainObj('inflated', translucent=False, sulcus=True) b_obj.add_activation(file=file_1, clim=(4., 30.), hide_under=4, cmap='Reds_r', hemisphere='left') b_obj.add_activation(file=file_2, clim=(4., 30.), hide_under=4, cmap='Blues_r', hemisphere='left') vb = Brain(brain_obj=b_obj) vb.rotate('left') vb.show()
vertices=vertices, smoothing_steps=5, clim=(7., 21.), hide_under=7., cmap='viridis') # Build arrows : dt = np.dtype([('vertices', float, 3), ('normals', float, 3)]) arrows = np.zeros(len(data), dtype=dt) arrows['vertices'] = b_obj.vertices[vertices, :] arrows['normals'] = b_obj.normals[vertices, :] select = data >= 7. # Define the vector object : v_obj = VectorObj('vector', arrows, data=data, inferred_data=True, clim=(7., 21.), antialias=True, cmap='viridis', select=select, line_width=2., arrow_coef=1.2, dynamic=(.2, 1.)) # Finally, pass the brain and vector object to the Brain module : vb = Brain(brain_obj=b_obj, vector_obj=v_obj) vb.rotate('left') vb.show()