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
software (https://github.com/nipy/PySurfer/). Parcellation file comes from MNE-Python (https://github.com/mne-tools/mne-python). """ import numpy as np from visbrain.objects import BrainObj, ColorbarObj, SceneObj, SourceObj from visbrain.io import download_file, read_stc ############################################################################### # Scene creation ############################################################################### # The SceneObj is Matplotlib subplot like in which, you can add visbrain's # objects. We first create the scene with a black background, a fixed size # Scene creation sc = SceneObj(bgcolor='black', size=(1400, 1000)) # Colorbar default arguments. See `visbrain.objects.ColorbarObj` CBAR_STATE = dict(cbtxtsz=12, txtsz=10., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.)) KW = dict(title_size=14., zoom=1.2) ############################################################################### # .. note:: # The BrainObj can interact with sources (SourceObj). For example, if the # source object represent intracranial data (e.g iEEG) those sources can # be projected on the surface of the brain. This is an important feature # because intracranial implantations is usually subject dependant and the # projection is a good way to plot results across subjects. To illustrate # this feature, we provide a set of intracranial MNI coordinates. # Download iEEG coordinates and define some random data
# # .. warning:: To use this pipeline, we need a cortical segmentation of MRI # data, that could be provided by Freesurfer ############################################################################## import pickle # noqa from ephypype.gather.gather_results import get_results # noqa from visbrain.objects import BrainObj, ColorbarObj, SceneObj # noqa time_series_files, label_files = get_results(main_workflow.base_dir, main_workflow.name, pipeline='inverse') time_pts = 30 sc = SceneObj(size=(800, 500), bgcolor=(0, 0, 0)) lh_file = op.join(subjects_dir, 'fsaverage', 'label/lh.aparc.annot') rh_file = op.join(subjects_dir, 'fsaverage', 'label/rh.aparc.annot') cmap = 'bwr' txtcolor = 'white' 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]
""" Plot x3d files ============== This example illustrate how to plot .x3d files. 6 brain templates are going to be downloaded (total of 26.3Mo). Additional templates can be downloaded from : https://scalablebrainatlas.incf.org """ from visbrain.objects import BrainObj, SceneObj from visbrain.io import download_file sc = SceneObj(size=(1500, 800)) ############################################################################### # Ferret brain ############################################################################### # Hutchinson EB, Schwerin SC, Radomski KL, Sadeghi N, Jenkins J, Komlosh ME, # Irfanoglu MO, Juliano SL, Pierpaoli C (2017) "Population based MRI and DTI # templates of the adult ferret brain and tools for voxelwise analysis" # Neuroimage 152:575–589. [doi 10.1016/j.neuroimage.2017.03.009] ferret_file = download_file('ferret.x3d', astype='example_data') b_ferret_obj = BrainObj(ferret_file, translucent=False) sc.add_to_subplot(b_ferret_obj, title='Ferret brain (Hutchinson et al. 2017)') ############################################################################### # Macaque brain (1) ############################################################################### # Markov NT, Ercsey-Ravasz MM, Ribeiro Gomes AR, Lamy C, Magrou L, Vezoli J, # Misery P, Falchier A, Quilodran R, Gariel MA, Sallet J, Gamanut R, # Huissoud C, Clavagnier S, Giroud P, Sappey-Marinier D, Barone P, Dehay C,
# .. note:: The power pipeline in the **source space** is implemented by the # function :func:`ephypype.pipelines.power.create_pipeline_power_src_space` # and its Node :class:`ephypype.interfaces.mne.power.Power` compute the PSD # by the welch function of the scipy package. ############################################################################## from ephypype.gather import get_results # noqa from visbrain.objects import SourceObj, SceneObj, ColorbarObj # noqa from visbrain.utils import normalize # noqa from nipype.utils.filemanip import split_filename # noqa psd_files, channel_coo_files = get_results(main_workflow.base_dir, main_workflow.name, pipeline='power') sc = SceneObj(size=(1800, 500), bgcolor=(.1, .1, .1)) for psd_file, channel_coo_file in zip(psd_files, channel_coo_files): path_xyz, basename, ext = split_filename(psd_file) arch = np.load(psd_file) psds, freqs = arch['psds'], arch['freqs'] xyz = np.genfromtxt(channel_coo_file, dtype=float) freq_bands = np.asarray(freq_bands) clim = (psds.min(), psds.max()) # Find indices of frequencies : idx_fplt = np.abs((freqs.reshape(1, 1, -1) - freq_bands[..., np.newaxis])).argmin(2) psdf = np.array([psds[:, k[0]:k[1]].mean(1) for k in idx_fplt]) radius = normalize(np.c_[psdf.min(1), psdf.max(1)], 5, 25).astype(float)
* RoiObj : source's activity and repartition can be projected on the surface of region of interest. In addition, ROI objects can also be used to get anatomical informations of sources """ import numpy as np from visbrain.objects import SourceObj, SceneObj, ColorbarObj, BrainObj, RoiObj, ConnectObj from visbrain.io import download_file # Create the scene CAM_STATE = dict( azimuth=0, # azimuth angle elevation=90, # elevation angle scale_factor=180 # distance to the camera ) sc = SceneObj(bgcolor='white', size=(1600, 1000)) b_obj = BrainObj('B3', translucent=False) sc.add_to_subplot(b_obj) sc.screenshot('plain_brain.png') sc.preview() ############################################################################### # .. warning:: # To be clear with the vocabulary used, the SourceObj has a different # meaning depending on the recording type. For scalp or intracranial EEG, # sources reflect electrode, in MEG it could be sensors or source # reconstruction. ############################################################################### # Download data ###############################################################################
############################################################################### # The SceneObj is Matplotlib subplot like in which, you can add visbrain's # objects. We first create the scene with a black background, a fixed size # Download intracranial EEG electodes mat = np.load(download_file('xyz_sample.npz', astype='example_data')) xyz, subjects = mat['xyz'], mat['subjects'] n_sources = xyz.shape[0] # Generate random data and random connectivity data = np.random.uniform(low=-1., high=1., size=(n_sources,)) conn = np.triu(np.random.uniform(-1., 1., (n_sources, n_sources))) conn_select = (-.005 < conn) & (conn < .005) # Scene creation sc = SceneObj() ############################################################################### # Animate a single brain object ############################################################################### # Here we set an animation for a single brain object. b_obj_1 = BrainObj('inflated', translucent=False) b_obj_1.animate() sc.add_to_subplot(b_obj_1, rotate='left', title='Animate a single object') ############################################################################### # Animate multiple objects ############################################################################### # Here we animate multiple objects inside a subplot
# Get the path to Visbrain data and download deep sources mat = np.load(download_file('xyz_sample.npz', astype='example_data')) xyz, subjects = mat['xyz'], mat['subjects'] data = np.random.uniform(low=-1., high=1., size=(xyz.shape[0],)) ############################################################################### # Scene creation ############################################################################### CAM_STATE = dict(azimuth=0, # azimuth angle elevation=90, # elevation angle ) CBAR_STATE = dict(cbtxtsz=12, txtsz=10., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.)) sc = SceneObj(camera_state=CAM_STATE, size=(1400, 1000)) ############################################################################### # 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) ###############################################################################
from tensorpac.utils import pac_signals_wavelet from visbrain.objects import PacmapObj, SceneObj """Generate artificillly coupled signals : - First coupling between 10hz phase with a 80hz amplitude - Second coupling between 5hz phase with a 100hz amplitude The final signal is the concatenation of both """ sf = 1024. s_1 = pac_signals_wavelet(sf=sf, fpha=10., famp=80., ntrials=1, npts=5000)[0] s_2 = pac_signals_wavelet(sf=sf, fpha=5., famp=100., ntrials=1, npts=5000)[0] sig = np.c_[s_1, s_2] sc = SceneObj(size=(1200, 600)) print(""" # ============================================================================= # Comodulogram # ============================================================================= """) pac_obj_como = PacmapObj('como', sig, sf=sf, f_pha=(2, 30, 1, .5), f_amp=(60, 150, 10, 1), interpolation='bicubic') sc.add_to_subplot(pac_obj_como, row=0, col=0, zoom=.9, title='Comodulogram') print(""" # ============================================================================= # Optimal phase frequency # ============================================================================= """)
""" Load the xyz coordinates and corresponding subject name """ mat = np.load(download_file('xyz_sample.npz')) xyz = mat['xyz'] n_sources = xyz.shape[0] text = ['S' + str(k) for k in range(n_sources)] """Create a scene. By default, we fix the top view of the camera """ CAM_STATE = dict(azimuth=0, # azimuth angle elevation=90, # elevation angle scale_factor=180 # ~distance to the camera ) CBAR_STATE = dict(cbtxtsz=12, txtsz=10., width=.5, rect=(1., -2., 1., 4.)) sc = SceneObj(camera_state=CAM_STATE, size=(1200, 1000)) """Create the most basic source object """ s_obj_basic = SourceObj('Basic', xyz, text=text, text_bold=True, text_color='yellow') sc.add_to_subplot(s_obj_basic, row=0, col=0, title='Default configuration with text') """Control the color and the symbol """ s_obj_col = SourceObj('S2', xyz, color='slategray', symbol='square') sc.add_to_subplot(s_obj_col, row=0, col=1, title='Change color and symbol') """Mask sources that have a x coordinate between [-20, 20] and color it into orange
def generate_img(l_file, r_file, activated_areas, brain_name, out_file, views, add_hemispheres, is_estimate=False, cmap='copper', vmin=0., vmax=0.01, save_gif=False): """Generate .png and .gif animation of rotating brains """ sc = SceneObj(size=(1000 * (len(views) // 2 + (1 if add_hemispheres else 0)), 1000 * (len(views) > 1)), bgcolor='black') KW = dict(title_size=14., zoom=2.) # zoom not working CBAR_STATE = dict(cbtxtsz=12, txtsz=10., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.)) # PLOT OBJECTS for i, rot in enumerate(views): # cannot use the same object b_obj = create_brain_obj(l_file, r_file, activated_areas, brain_name, cmap=cmap, vmin=vmin, vmax=vmax) sc.add_to_subplot(b_obj, row=i // 2, col=i % 2, rotate=rot, title=rot, **KW) # Get the colorbar of the brain object and add it to the scene # Identical brain ==> same colorbar if add_hemispheres: # add left brain b_obj = create_brain_obj(l_file, r_file, activated_areas, brain_name, hemisphere='right', cmap=cmap, vmin=vmin, vmax=vmax) sc.add_to_subplot(b_obj, row=i // 2 + 1, col=0, rotate='left', title='right half', **KW) b_obj = create_brain_obj(l_file, r_file, activated_areas, brain_name, hemisphere='left', cmap=cmap, vmin=vmin, vmax=vmax) sc.add_to_subplot(b_obj, row=i // 2 + 1, col=1, rotate='right', title='left half', **KW) if is_estimate: # cmap needs to be set for all objects cb_parr = ColorbarObj(b_obj, cblabel='Data to parcellates', **CBAR_STATE) # not working properly and can't find a way to rotate that bar # sc.add_to_subplot(cb_parr, row=0, col=2, row_span=i//2+1, width_max=200) # gif and png # sc.preview() if save_gif: sc.record_animation(out_file + ('_est' if is_estimate else '') + "_areas.gif") sc.screenshot(saveas=out_file + ('_est' if is_estimate else '') + "_areas.png") return sc.render()
""" Plot x3d files ============== This example illustrate how to plot .x3d files. 6 brain templates are going to be downloaded (total of 26.3Mo). Additional templates can be downloaded from : https://scalablebrainatlas.incf.org """ from visbrain.objects import BrainObj, SceneObj from visbrain.io import download_file sc = SceneObj(size=(1500, 800)) ############################################################################### # Ferret brain ############################################################################### # Hutchinson EB, Schwerin SC, Radomski KL, Sadeghi N, Jenkins J, Komlosh ME, # Irfanoglu MO, Juliano SL, Pierpaoli C (2017) "Population based MRI and DTI # templates of the adult ferret brain and tools for voxelwise analysis" # Neuroimage 152:575–589. [doi 10.1016/j.neuroimage.2017.03.009] ferret_file = download_file('ferret.x3d', astype='example_data') b_ferret_obj = BrainObj(ferret_file, translucent=False) sc.add_to_subplot(b_ferret_obj, title='Ferret brain (Hutchinson et al. 2017)') ############################################################################### # Macaque brain (1) ###############################################################################
import numpy as np from visbrain.objects import ConnectObj, SceneObj, SourceObj, BrainObj from visbrain.io import download_file ############################################################################### # Download data and define the scene ############################################################################### # First, we download a connectivity dataset consisting of the location of each # node (104) and the connectivity strength between every node (104, 104) # Download data arch = np.load(download_file('phase_sync_delta.npz', astype='example_data')) nodes, edges = arch['nodes'], arch['edges'] # Create the scene with a black background sc = SceneObj(size=(1500, 600)) ############################################################################### # Color by connectivity strength ############################################################################### # First, we download a connectivity dataset consisting of the location of each # node (iEEG site) and the connectivity strength between those nodes. The first # coloring method illustrated bellow consist in coloring connections based on # a colormap # Coloring method color_by = 'strength' # Because we don't want to plot every connections, we only keep connections # above .7 select = edges > .7 # Define the connectivity object
data = np.random.uniform(low=-1., high=1., size=(xyz.shape[0], )) ############################################################################### # Scene creation ############################################################################### CAM_STATE = dict( azimuth=0, # azimuth angle elevation=90, # elevation angle ) CBAR_STATE = dict(cbtxtsz=12, txtsz=10., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.)) sc = SceneObj(camera_state=CAM_STATE, size=(1400, 1000)) ############################################################################### # 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,
import numpy as np from visbrain.objects import ConnectObj, SceneObj, SourceObj, BrainObj from visbrain.io import download_file ############################################################################### # Download data and define the scene ############################################################################### # First, we download a connectivity dataset consisting of the location of each # node (104) and the connectivity strength between every node (104, 104) # Download data arch = np.load(download_file('phase_sync_delta.npz', astype='example_data')) nodes, edges = arch['nodes'], arch['edges'] # Create the scene with a black background sc = SceneObj(size=(1500, 600)) ############################################################################### # Color by connectivity strength ############################################################################### # First, we download a connectivity dataset consisting of the location of each # node (iEEG site) and the connectivity strength between those nodes. The first # coloring method illustrated bellow consist in coloring connections based on # a colormap # Coloring method color_by = 'strength' # Because we don't want to plot every connections, we only keep connections # above .7 select = edges > .7 # Define the connectivity object
from itertools import product import mne from visbrain.objects import GridSignalsObj, SceneObj from visbrain.utils import generate_eeg ############################################################################### # Scene creation ############################################################################### # The SceneObj is Matplotlib subplot like in which, you can add visbrain's # objects. We first create the scene with a black background, a fixed size # Scene creation sc = SceneObj(bgcolor='black', size=(1400, 1000)) ############################################################################### # Generate random data ############################################################################### # Here we generate a random 3D dataset with 5 channels and 4 trials per channel # Note that here we geneate a 3D dataset but you can also pass a 1D or 2D # dataset sf = 512. # sampling frequency n_pts = 1000 # number of time points n_channels = 5 # number of channels n_trials = 4 # number of trials data_3d = generate_eeg(n_pts=n_pts, n_channels=n_channels, n_trials=n_trials, f_max=20., smooth=200, noise=1000)[0] channels = ['Channel %i' % (k + 1) for k in range(n_channels)]
print(""" # ============================================================================= # Default scene # ============================================================================= """) CAM_STATE = dict( azimuth=0, # azimuth angle elevation=90, # elevation angle ) 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)) print(""" # ============================================================================= # Translucent inflated brain template # ============================================================================= """) b_obj_fs = BrainObj('inflated', translucent=True) b_obj_fs.alpha = 0.03 sc.add_to_subplot(b_obj_fs, row=0, col=0, row_span=2, title='Translucent inflated brain template') print("""
""" Volume object (VolumeObj) : complete tutorial ============================================= Illustration of the main functionalities and inputs of the volume object : * Volume rendering methods (MIP, translucent, additive, Iso) * Colormap choice * Select volume levels * Load an MRI (nii.gz) file """ from visbrain.objects import VolumeObj, SceneObj from visbrain.io import download_file # Define the scene sc = SceneObj(size=(1000, 600)) ############################################################################### # MIP rendering ############################################################################### # MIP rendering with an opaque fire colormap v_obj_mip = VolumeObj('brodmann', method='mip', cmap='OpaqueFire') sc.add_to_subplot(v_obj_mip, row=0, col=0, title='MIP rendering', zoom=.7) ############################################################################### # Translucent rendering ############################################################################### # Translucent rendering with a translucent fire colormap v_obj_trans = VolumeObj('aal', method='translucent', cmap='TransFire')
# Plotting properties shared across topoplots and colorbar : kw_top = dict(margin=15 / 100, chan_offset=(0., 0.1, 0.), chan_size=10) kw_cbar = dict(cbtxtsz=12, txtsz=10., width=.3, txtcolor='black', cbtxtsh=1.8, rect=(0., -2., 1., 4.), border=False) ############################################################################### # Creation of the scene ############################################################################### # Create a scene with a white background sc = SceneObj(bgcolor='white', size=(1600, 900)) ############################################################################### # Topoplot based on channel names ############################################################################### # First definition using channel names only # Define some EEG channels and set one data value per channel ch_names = ['C3', 'C4', 'Cz', 'Fz', 'Pz'] data_names = [10, 20, 30, 10, 10] # Create the topoplot and the associated colorbar t_obj = TopoObj('topo', data_names, channels=ch_names, **kw_top) cb_obj = ColorbarObj(t_obj, cblabel='Colorbar label', **kw_cbar) # Add both objects to the scene # Add the topoplot and the colorbar to the scene : sc.add_to_subplot(t_obj,
""" Cross-section object ==================== Illustration and main functionalities and inputs of the cross-section object. .. image:: ../../picture/picobjects/ex_cs_obj.png """ from visbrain.objects import CrossSecObj, SceneObj from visbrain.io import download_file sc = SceneObj() print(""" # ============================================================================= # Brodmann area # ============================================================================= """) cs_brod = CrossSecObj('brodmann', interpolation='nearest', coords=(70., 80., 90.)) cs_brod.localize_source((-10., -15., 20.)) sc.add_to_subplot(cs_brod, row=0, col=0, title='Brodmann area') print(""" # ============================================================================= # Nii.gz file # ============================================================================= """) path = download_file('GG-853-GM-0.7mm.nii.gz') cs_cust = CrossSecObj(path, coords=(0., 0., 0.), cmap='gist_stern')
def create_scene (): sc = SceneObj (size=(1400, 1000)) brain_objs = [] # CREATE 4 BRAIN OBJECTS EACH WITH SPECOFOC ROTATION brain_objs = [] for rot in ["left", "right", 'side-fl', 'side-fr', 'front', 'back']: brain_objs. append (BrainObj(name = 'inflated', hemisphere='both', translucent=False, cbtxtsz = 10., verbose = None)) sc.add_to_subplot(brain_objs[0], row=0, col=0, rotate='right', title='Right', zoom = 3.5) sc.add_to_subplot(brain_objs[1], row=0, col=1, rotate='left', title='Left') sc.add_to_subplot(brain_objs[2], row=1, col=0, rotate='top', title='Top') sc.add_to_subplot(brain_objs[3], row=1, col=1, rotate='bottom', title='Bottom') sc.add_to_subplot(brain_objs[4], row=2, col=0, rotate='front', title='Front') sc.add_to_subplot(brain_objs[5], row=2, col=1, rotate='back', title='Back') return sc, brain_objs
CBAR_STATE = dict(cbtxtsz=12, clim=[0, 7], txtsz=10., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.)) KW = dict(title_size=14., zoom=1) nii_bo_dir = '../../../data/niis/supplemental_3/networks' fig_dir = '../../../paper/figs/source/supplemental_3/networks' freqs = ['delta', 'theta', 'alpha', 'beta', 'lgamma', 'hgamma'] sc = SceneObj(bgcolor='white', size=(1000, 1000)) b_yeo = se.load(os.path.join(nii_bo_dir, 'yeo_bo_6mm.bo')) data1 = b_yeo.get_data().values.ravel() xyz1 = b_yeo.locs.values s_obj_1 = SourceObj('iEEG', xyz1, data=data1, cmap=cmap) s_obj_1.color_sources(data=data1) b_obj_proj_left = BrainObj(template_brain, hemisphere='left', translucent=False) b_obj_proj_left.project_sources(s_obj_1, clim=(1, 7), cmap=cmap) sc.add_to_subplot(b_obj_proj_left, row=0,
def add_objs_to_scene (sc, brain_objs): sc = SceneObj (size=(1400, 1000)) sc.add_to_subplot(brain_objs[0], row=0, col=0, rotate='right', title='Right') sc.add_to_subplot(brain_objs[1], row=0, col=1, rotate='left', title='Left') sc.add_to_subplot(brain_objs[2], row=1, col=0, rotate='top', title='Top') sc.add_to_subplot(brain_objs[3], row=1, col=1, rotate='bottom', title='Bottom') sc.add_to_subplot(brain_objs[4], row=2, col=0, rotate='front', title='Front') sc.add_to_subplot(brain_objs[5], row=2, col=1, rotate='back', title='Back') return sc
import numpy as np from visbrain.objects import BrainObj, ColorbarObj, SceneObj, SourceObj from visbrain.utils import generate_eeg, convert_meshdata, vispy_array from visbrain.config import CONFIG from vispy.app import Timer scene = SceneObj(bgcolor='white', size=(1400, 1000)) # Colorbar default arguments. See `visbrain.objects.ColorbarObj` CBAR_STATE = dict(cbtxtsz=12, txtsz=10., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.)) KW = dict(title_size=14., zoom=2) colormap = 'inferno' # load brain model verts = np.load('bnd4_pos1.npy') faces = np.load('bnd4_tri1.npy') verts *= 1000 verts, faces, normals = convert_meshdata(verts, faces, invert_normals=True) # generate random toy data
Volume object (VolumeObj) : complete tutorial ============================================= Illustration of the main functionalities and inputs of the volume object : * Volume rendering methods (MIP, translucent, additive, Iso) * Colormap choice * Select volume levels * Load an MRI (nii.gz) file """ from visbrain.objects import VolumeObj, SceneObj from visbrain.io import download_file # Define the scene sc = SceneObj(size=(1000, 600)) ############################################################################### # MIP rendering ############################################################################### # MIP rendering with an opaque fire colormap v_obj_mip = VolumeObj('brodmann', method='mip', cmap='OpaqueFire') sc.add_to_subplot(v_obj_mip, row=0, col=0, title='MIP rendering', zoom=.7) ############################################################################### # Translucent rendering ############################################################################### # Translucent rendering with a translucent fire colormap v_obj_trans = VolumeObj('aal', method='translucent', cmap='TransFire')
############################################################################### # Run workflow locally on 2 CPUs in parrallel #main_workflow.run(plugin='MultiProc', plugin_args={'n_procs': 2}) ############################################################################### # plotting modules from graphpype.utils_visbrain import visu_graph_modules # noqa labels_file = op.join(data_path, "label_names.txt") coords_file = op.join(data_path, "label_centroid.txt") from visbrain.objects import SceneObj, BrainObj # noqa sc = SceneObj(size=(1000, 1000), bgcolor=(1,1,1)) views = ["left",'top'] for i_v,view in enumerate(views): for nf, freq_band_name in enumerate(freq_band_names): res_path = op.join( data_path, graph_analysis_name, "graph_den_pipe_den_"+str(con_den).replace(".", "_"), "_freq_band_name_"+freq_band_name+"_subject_id_sub-0003") lol_file = op.join(res_path, "community_rada", "Z_List.lol") net_file = op.join(res_path, "prep_rada", "Z_List.net") b_obj = BrainObj("B1", translucent=True) sc.add_to_subplot(b_obj, row=nf, col = i_v, use_this_cam=True,
from tensorpac.utils import pac_signals_wavelet from visbrain.objects import PacmapObj, SceneObj """Generate artificillly coupled signals : - First coupling between 10hz phase with a 80hz amplitude - Second coupling between 5hz phase with a 100hz amplitude The final signal is the concatenation of both """ sf = 1024. s_1 = pac_signals_wavelet(sf=sf, fpha=10., famp=80., ntrials=1, npts=5000)[0] s_2 = pac_signals_wavelet(sf=sf, fpha=5., famp=100., ntrials=1, npts=5000)[0] sig = np.c_[s_1, s_2] sc = SceneObj() print(""" # ============================================================================= # Comodulogram # ============================================================================= """) pac_obj_como = PacmapObj('como', sig, sf=sf, f_pha=(2, 30, 1, .5), f_amp=(60, 150, 10, 1), interpolation='bicubic') sc.add_to_subplot(pac_obj_como, row=0, col=0, title='Comodulogram') print("""
############################################################################### # Finally, we are now ready to execute our workflow. main_workflow.config['execution'] = {'remove_unnecessary_outputs': 'false'} main_workflow.run() # Run workflow locally on 2 CPUs #main_workflow.run(plugin='MultiProc', plugin_args={'n_procs': 2}) ################################################################################ ## plotting from graphpype.utils_visbrain import visu_graph_modules, visu_graph_modules_roles from visbrain.objects import SceneObj, BrainObj # noqa sc = SceneObj(size=(1000, 1000), bgcolor=(1, 1, 1)) res_path = op.join(data_path, conmat_analysis_name, "graph_den_pipe_den_" + str(con_den).replace(".", "_"), "_session_rest_subject_id_01") lol_file = op.join(res_path, "community_rada", "Z_List.lol") net_file = op.join(res_path, "prep_rada", "Z_List.net") roles_file = op.join(res_path, "node_roles", "node_roles.txt") views = ["left", 'top'] for i_v, view in enumerate(views): b_obj = BrainObj("B1", translucent=True) sc.add_to_subplot(b_obj,
# space. # Define 5 sources xyz = np.array([[0, .5, 0], [1, -4, 3], [10, 2, 8], [1, 7, 12], [-4, 5, 6]]) n_sources = xyz.shape[0] # Define the time-series of those 5 sources ts_data = generate_eeg(sf=512., n_channels=n_sources, noise=5., smooth=5)[0] # Compute the spectrogram of the 5 time-series pic_data = [] for k in range(n_sources): pic_data += [spectrogram(ts_data[k, :], 512., nperseg=128, noverlap=10)[2]] pic_data = np.asarray(pic_data) clim = (.01 * pic_data.min(), .01 * pic_data.max()) # Scene definition sc = SceneObj() ############################################################################### # Basic plot ############################################################################### # Basic plot without further customizations # Define time-series and picture objects ts_0 = TimeSeries3DObj('t0', ts_data, xyz, antialias=True) pic_0 = Picture3DObj('p0', pic_data, xyz, clim=clim) # Add those objects to the scene sc.add_to_subplot(ts_0, row=0, col=0, zoom=.2, title='Basic 3D TS plot') sc.add_to_subplot(pic_0, row=0, col=1, zoom=.5, title='Basic 3D pictures plot') ############################################################################### # Subset selection
# space. # Define 5 sources xyz = np.array([[0, .5, 0], [1, -4, 3], [10, 2, 8], [1, 7, 12], [-4, 5, 6]]) n_sources = xyz.shape[0] # Define the time-series of those 5 sources ts_data = generate_eeg(sf=512., n_channels=n_sources, noise=5., smooth=5)[0] # Compute the spectrogram of the 5 time-series pic_data = [] for k in range(n_sources): pic_data += [spectrogram(ts_data[k, :], 512., nperseg=128, noverlap=10)[2]] pic_data = np.asarray(pic_data) clim = (.01 * pic_data.min(), .01 * pic_data.max()) # Scene definition sc = SceneObj() ############################################################################### # Basic plot ############################################################################### # Basic plot without further customizations # Define time-series and picture objects ts_0 = TimeSeries3DObj('t0', ts_data, xyz, antialias=True) pic_0 = Picture3DObj('p0', pic_data, xyz, clim=clim) # Add those objects to the scene sc.add_to_subplot(ts_0, row=0, col=0, zoom=.2, title='Basic 3D TS plot') sc.add_to_subplot(pic_0, row=0, col=1, zoom=.5, title='Basic 3D pictures plot') ############################################################################### # Subset selection
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()
def plot_meg_connectome(): ''' Plot the MEG brain connectome for the master figure in MEG paper ''' megdata = sio.loadmat('MEG_data_info/total_connecivtiy_coord_label.mat') total_con = megdata['connectivity'] xyz = megdata['ROI_coords'] normal_con = total_con[:53] smci_con = total_con[53:-28] pmci_con = total_con[-28:] edges = smci_con[8, :, :] sc = SceneObj(bgcolor='black') c_obj = ConnectObj('default', xyz, edges, select=edges > .026, line_width=3., dynamic=(0., 1.), dynamic_orientation='center', cmap='bwr', color_by='strength') s_obj = SourceObj('sources', xyz, color='red', radius_min=15.) cb_obj = ColorbarObj(c_obj, cblabel='Edge strength') sc.add_to_subplot(c_obj, title='MEG brain network') sc.add_to_subplot(s_obj) sc.add_to_subplot(BrainObj('B3'), use_this_cam=True) sc.add_to_subplot(cb_obj, col=1, width_max=200) sc.preview()
def vis_sources_by_pval(padj, all_coord, short_label): ''' 1. visualize the sources (brain regions) based on the FDR-adjusted p values display both the source objects and the brain object ''' # Define the default camera state used for each subplot CAM_STATE = dict( azimuth=0, # azimuth angle elevation=90, # elevation angle scale_factor=180 # distance to the camera ) S_KW = dict(camera_state=CAM_STATE) # Create the scene CBAR_STATE = dict(cbtxtsz=12, txtsz=13., width=.5, cbtxtsh=2., rect=(1., -2., 1., 4.)) sc = SceneObj(bgcolor='black', size=(1600, 1000)) # mask = padj<=0.05 # significant regions with true label data0, max_p, min_p = get_log_pval(padj) b_obj = BrainObj('white', hemisphere='both', translucent=True) b_obj.animate(iterations=10, step=30, interval=1) s_obj = SourceObj( 's1', all_coord, #all_coord, # mask = mask, # mask_color='white', # mask_radius = 15, color=padj * 100, data=data0, text=short_label, text_size=10, text_bold=True, text_color='yellow', symbol='disc', visible=True, radius_min=10, radius_max=40, alpha=0.65) s_obj_1.set_visible_sources('left') s_obj.color_sources(data=data0, cmap='jet', clim=(min_p, max_p)) cb_data = ColorbarObj(s_obj, cblabel='Log FDR-adjusted p value', border=False, **CBAR_STATE) sc.add_to_subplot(b_obj, row=0, col=0, rotate='front') sc.add_to_subplot(s_obj, row=0, col=0) sc.add_to_subplot(cb_data, row=0, col=1, width_max=90) # recording animation and save it sc.record_animation('output/animate_pvalue_projection.gif', n_pic=10) sc.preview()
text = ['S' + str(k) for k in range(n_sources)] ############################################################################### # Scene creation ############################################################################### # As said in other tutorials, the scene is equivalent with Matplotlib subplots. # So here, we define a scene that is going to centralize objects in subplots # 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 sc = SceneObj(size=(1600, 1000)) CBAR_STATE = dict(cbtxtsz=12, txtsz=10., width=.5, cbtxtsh=3., rect=(1., -2., 1., 4.)) ############################################################################### # Basic source object ############################################################################### # The first example consist of only plotting the source, without any # modifications of the inputs # Create the source objects and add this object to the scene s_obj_basic = SourceObj('Basic', xyz) sc.add_to_subplot(s_obj_basic, row=0, col=0, title='Default configuration', **S_KW) ###############################################################################
from ephypype.gather.gather_results import get_results # noqa from ephypype.gather.gather_results import get_channel_files # noqa from ephypype.aux_tools import _parse_string # noqa from visbrain.objects import ConnectObj, SourceObj, SceneObj, ColorbarObj # noqa thresh = .75 with_text = False channel_coo_files, channel_name_files = get_channel_files( main_workflow.base_dir, main_workflow.name) connectivity_matrices, _ = get_results(main_workflow.base_dir, main_workflow.name, pipeline='connectivity') sc = SceneObj(size=(1000, 1000), bgcolor=(.1, .1, .1)) for nf, (connect_file, channel_coo_file, channel_name_file) in \ enumerate(zip(connectivity_matrices, channel_coo_files, channel_name_files)): # Load files : xyz = np.genfromtxt(channel_coo_file, dtype=float) names = np.genfromtxt(channel_name_file, dtype=str) connect = np.load(connect_file) connect += connect.T connect = np.ma.masked_array(connect, mask=connect < thresh) names = names if with_text else None radius = connect.sum(1) clim = (thresh, connect.max()) # With text :
# Get the path to the ~/visbrain_data/example_data folder vb_path = path_to_visbrain_data(folder='example_data') # Download (x, y, z) coordinates of intracranial sources mat = np.load(download_file('xyz_sample.npz', astype='example_data')) xyz, subjects = mat['xyz'], mat['subjects'] data = np.random.uniform(low=-1., high=1., size=(xyz.shape[0],)) # Download the MIST parcellates download_file('MIST_ROI.zip', unzip=True, astype='example_data') ############################################################################### # Scene creation ############################################################################### # First, we need to create the scene that will host objects # Scene creation with a dark background and a custom size sc = SceneObj(size=(1400, 1000)) # In this example, we also illustrate the use of the colorbar object. Hence, we # centralize colorbar properties inside a dictionary CBAR_STATE = dict(cbtxtsz=12, txtsz=10., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.)) ############################################################################### # Find the index of a region of interest ############################################################################### # 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 #####################################
path = download_file('topoplot_data.npz', astype='example_data') mat = np.load(path) xy, data = mat['xyz'], mat['data'] channels = [str(k) for k in range(len(data))] # Plotting properties shared across topoplots and colorbar : kw_top = dict(margin=15 / 100, chan_offset=(0., 0.1, 0.), chan_size=10) kw_cbar = dict(cbtxtsz=12, txtsz=10., width=.3, txtcolor='black', cbtxtsh=1.8, rect=(0., -2., 1., 4.), border=False) ############################################################################### # Creation of the scene ############################################################################### # Create a scene with a white background sc = SceneObj(bgcolor='white', size=(1600, 900)) ############################################################################### # Topoplot based on channel names ############################################################################### # First definition using channel names only # Define some EEG channels and set one data value per channel ch_names = ['C3', 'C4', 'Cz', 'Fz', 'Pz'] data_names = [10, 20, 30, 10, 10] # Create the topoplot and the associated colorbar t_obj = TopoObj('topo', data_names, channels=ch_names, **kw_top) cb_obj = ColorbarObj(t_obj, cblabel='Colorbar label', **kw_cbar) # Add both objects to the scene # Add the topoplot and the colorbar to the scene : sc.add_to_subplot(t_obj, row=0, col=0, title='Definition using channel names',