def surface_images(out_dir, subj): """Plot the white, pial, and inflated surfaces to look for defects.""" for surf in ["white", "pial", "inflated"]: panels = [] for hemi in ["lh", "rh"]: try: b = Brain(subj, hemi, surf, curv=False, background="white") except TypeError: # PySurfer <= 0.5 b = Brain(subj, hemi, surf, curv=False, config_opts=dict(background="white")) for view in ["lat", "med", "ven"]: b.show_view(view, distance="auto") panels.append(crop(b.screenshot())) b.close() # Make and save a figure f = multi_panel_brain_figure(panels) fname = op.join(out_dir, "{}_surface.png".format(surf)) f.savefig(fname, bbox_inches="tight") plt.close(f)
def contrast_loop(subj, contrasts, stat_temp, mask_temp, png_temp, args, z_thresh, sign): """Iterate over contrasts and make surface images.""" for contrast in contrasts: # Calculate where the overlay should saturate z_max = calculate_sat_point(stat_temp, contrast, sign, subj) panels = [] for hemi in ["lh", "rh"]: # Initialize the brain object b_subj = subj if args.regspace == "epi" else "fsaverage" try: b = Brain(b_subj, hemi, args.geometry, background="white") except TypeError: # PySurfer <= v0.5 b = Brain(b_subj, hemi, args.geometry, config_opts={"background": "white"}) # Plot the mask mask_file = mask_temp.format(contrast=contrast, hemi=hemi, subj=subj) add_mask_overlay(b, mask_file) # Plot the overlay stat_file = stat_temp.format(contrast=contrast, hemi=hemi, subj=subj) add_stat_overlay(b, stat_file, z_thresh, z_max, sign, sig_to_z=args.regspace == "fsaverage") # Take screenshots for view in ["lat", "med", "ven"]: b.show_view(view, distance="auto") sleep(.1) panels.append(crop(b.screenshot())) b.close() # Make a single figure with all the panels f = multi_panel_brain_figure(panels) kwargs = {} if sign in ["pos", "abs"]: kwargs["pos_cmap"] = "Reds_r" if sign in ["neg", "abs"]: kwargs["neg_cmap"] = "Blues" add_colorbars(f, z_thresh, z_max, **kwargs) # Save the figure in both hemisphere outputs for hemi in ["lh", "rh"]: png_file = png_temp.format(hemi=hemi, contrast=contrast, subj=subj) f.savefig(png_file, bbox_inches="tight") plt.close(f)
def curvature_normalization(data_dir, subj): """Normalize the curvature map and plot contour over fsaverage.""" surf_dir = op.join(data_dir, subj, "surf") snap_dir = op.join(data_dir, subj, "snapshots") panels = [] for hemi in ["lh", "rh"]: # Load the curv values and apply registration to fsaverage curv_fname = op.join(surf_dir, "{}.curv".format(hemi)) curv_vals = nib.freesurfer.read_morph_data(curv_fname) subj_curv_vals = apply_surface_warp(data_dir, subj, hemi, curv_vals) subj_curv_binary = (subj_curv_vals > 0) # Load the template curvature norm_fname = op.join(data_dir, "fsaverage", "surf", "{}.curv".format(hemi)) norm_curv_vals = nib.freesurfer.read_morph_data(norm_fname) norm_curv_binary = (norm_curv_vals > 0) # Compute the curvature overlap image curv_overlap = np.zeros_like(norm_curv_binary, np.int) curv_overlap[norm_curv_binary & subj_curv_binary] = 1 curv_overlap[norm_curv_binary ^ subj_curv_binary] = 2 # Mask out the medial wall cortex_fname = op.join(data_dir, "fsaverage", "label", "{}.cortex.label".format(hemi)) cortex = nib.freesurfer.read_label(cortex_fname) medial_wall = ~np.in1d(np.arange(curv_overlap.size), cortex) curv_overlap[medial_wall] = 1 # Plot the curvature overlap image try: b = Brain("fsaverage", hemi, "inflated", background="white") except TypeError: # PySurfer <= 0.5 b = Brain("fsaverage", hemi, "inflated", config_opts=dict(background="white")) b.add_data(curv_overlap, min=0, max=2, colormap=[".9", ".45", "indianred"], colorbar=False) for view in ["lat", "med", "ven"]: b.show_view(view, distance="auto") panels.append(crop(b.screenshot())) b.close() # Make and save a figure f = multi_panel_brain_figure(panels) fname = op.join(snap_dir, "surface_registration.png") f.savefig(fname, bbox_inches="tight") plt.close(f)
def test_brain_separate(): """Test that Brain does not reuse existing figures by default.""" _set_backend('auto') brain = Brain(*std_args) assert brain.brain_matrix.size == 1 brain_2 = Brain(*std_args) assert brain_2.brain_matrix.size == 1 assert brain._figures[0][0] is not brain_2._figures[0][0] brain_3 = Brain(*std_args, figure=brain._figures[0][0]) assert brain._figures[0][0] is brain_3._figures[0][0]
def plot_vertices(vertices_lh, vertices_rh, alpha=0.5, save=False, fname=None, simulated=False, col='green'): from surfer import Brain # Read labels subjects_dir = sample.data_path() + '/subjects' lh_vertex = 114573 # Auditory label rh_vertex = 53641 # Medial occipital label brain = Brain('sample', hemi='lh', surf='inflated', subjects_dir=subjects_dir, title='lh', background='white') if simulated: brain.add_foci(lh_vertex, coords_as_verts=True, color='red', hemi='lh') brain.add_foci(vertices_lh, coords_as_verts=True, color=col, alpha=alpha, hemi='lh') if save: brain.save_montage('paper_figures/images/' + fname + '_lat_lh.png', order=['lat'], border_size=1) brain = Brain('sample', hemi='rh', surf='inflated', subjects_dir=subjects_dir, title='rh', views=['lat'], background='white') if simulated: brain.add_foci(rh_vertex, coords_as_verts=True, color='red', hemi='rh') brain.add_foci(vertices_rh, coords_as_verts=True, color=col, alpha=alpha, hemi='rh') if save: brain.save_montage('paper_figures/images/' + fname + '_lat_rh.png', order=['lat'], border_size=1) return brain
def display_matrices(filenames, target, hemi, surface): from mayavi import mlab from surfer import Brain print '\n'.join(filenames) for name in filenames: try: corrmat = sio.loadmat(name)['corrmat'] except: try: corrmat = np.load(name)['corrmat'] except: try: corrmat = np.load(name)['arr_0'] except: try: corrmat = np.load(name)['avgcorr'] except: h5file = openFile(name, 'r') corrmat = h5file.root.corrmat corrmats.append(corrmat) for idx, name in enumerate(filenames): path, name = os.path.split(name) br = Brain(target, hemi, surface, title=name + '-%d' % idx) brains.append(br) for brain in brains[:-1]: mlab.sync_camera(br._f, brain._f) mlab.sync_camera(brain._f, br._f) br._f.on_mouse_pick(picker_callback) mlab.show()
def test_label(): """Test plotting of label.""" _set_backend() subject_id = "fsaverage" hemi = "lh" surf = "inflated" brain = Brain(subject_id, hemi, surf) brain.add_label("BA1") brain.add_label("BA1", color="blue", scalar_thresh=.5) subj_dir = utils._get_subjects_dir() label_file = pjoin(subj_dir, subject_id, "label", "%s.MT.label" % hemi) brain.add_label(label_file) brain.add_label("BA44", borders=True) brain.add_label("BA6", alpha=.7) brain.show_view("medial") brain.add_label("V1", color="steelblue", alpha=.6) brain.add_label("V2", color="#FF6347", alpha=.6) brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6) brain.set_surf('white') # remove labels brain.remove_labels('V1') assert_in('V2', brain.labels_dict) assert_not_in('V1', brain.labels_dict) brain.remove_labels() assert_not_in('V2', brain.labels_dict) brain.close()
def test_movie(tmpdir): """Test saving a movie of an MEG inverse solution.""" import imageio if sys.version_info < (3, ): raise SkipTest('imageio ffmpeg requires Python 3') # create and setup the Brain instance _set_backend() brain = Brain(*std_args) stc_fname = os.path.join(data_dir, 'meg_source_estimate-lh.stc') stc = io.read_stc(stc_fname) data = stc['data'] time = np.arange(data.shape[1]) * stc['tstep'] + stc['tmin'] brain.add_data(data, colormap='hot', vertices=stc['vertices'], smoothing_steps=10, time=time, time_label='time=%0.2f ms') brain.scale_data_colormap(fmin=13, fmid=18, fmax=22, transparent=True) # save movies with different options dst = str(tmpdir.join('test.mov')) # test the number of frames in the movie brain.save_movie(dst) frames = imageio.mimread(dst) assert len(frames) == 2 brain.save_movie(dst, time_dilation=10) frames = imageio.mimread(dst) assert len(frames) == 7 brain.save_movie(dst, tmin=0.081, tmax=0.102) frames = imageio.mimread(dst) assert len(frames) == 2 brain.close()
def test_probabilistic_labels(): """Test plotting of probabilistic labels.""" _set_backend() brain = Brain("fsaverage", "lh", "inflated", cortex="low_contrast") extra, subj_dir = _get_extra() brain.add_label("BA1" + extra, color="darkblue") brain.add_label("BA1" + extra, color="dodgerblue", scalar_thresh=.5) brain.add_label("BA45" + extra, color="firebrick", borders=True) brain.add_label("BA45" + extra, color="salmon", borders=True, scalar_thresh=.5) label_file = pjoin(subj_dir, "fsaverage", "label", "lh.BA6%s.label" % (extra, )) prob_field = np.zeros_like(brain.geo['lh'].x) ids, probs = nib.freesurfer.read_label(label_file, read_scalars=True) prob_field[ids] = probs brain.add_data(prob_field, thresh=1e-5) with warnings.catch_warnings(record=True): brain.data["colorbar"].number_of_colors = 10 brain.data["colorbar"].number_of_labels = 11 brain.close()
def main(subid, overlay): _, fname = os.path.split(overlay) hemi = fname[:2] brain = Brain(subid, hemi, "pial", config_opts=dict(cortex="low_contrast")) brain.add_overlay(overlay, min=0.4, max=4, sign="pos") brain.show_view('m')
def visMontage(pathToSurface, overlay, outputPath, hemi, type='white'): brain = Brain(pathToSurface, hemi, type) brain.add_overlay(overlay, -5, 3) brain.save_montage(outputPath, ['l', 'm'], orientation='v') brain.close() return outputPath
def test_overlay(): """Test plotting of overlay """ mlab.options.backend = 'test' # basic overlay support overlay_file = pjoin(data_dir, "lh.sig.nii.gz") brain = Brain(*std_args) brain.add_overlay(overlay_file) brain.overlays["sig"].remove() brain.add_overlay(overlay_file, min=5, max=20, sign="pos") sig1 = io.read_scalar_data(pjoin(data_dir, "lh.sig.nii.gz")) sig2 = io.read_scalar_data(pjoin(data_dir, "lh.alt_sig.nii.gz")) thresh = 4 sig1[sig1 < thresh] = 0 sig2[sig2 < thresh] = 0 conjunct = np.min(np.vstack((sig1, sig2)), axis=0) brain.add_overlay(sig1, 4, 30, name="sig1") brain.overlays["sig1"].pos_bar.lut_mode = "Reds" brain.overlays["sig1"].pos_bar.visible = False brain.add_overlay(sig2, 4, 30, name="sig2") brain.overlays["sig2"].pos_bar.lut_mode = "Blues" brain.overlays["sig2"].pos_bar.visible = False brain.add_overlay(conjunct, 4, 30, name="conjunct") brain.overlays["conjunct"].pos_bar.lut_mode = "Purples" brain.overlays["conjunct"].pos_bar.visible = False brain.close()
def plot_y_pred_true_parcels(subject_name, labels_pred, labels_true, colors={ 'pred': 'y', 'true': 'b', 'overlap': 'g' }): # fig_name = (subject_name + '_' + str(len(parcels_subject)) + '_' + # str(n_parcels_max)) # TODO: make the switch automatic depending on who/where it runs data_path = 'mne_data/MNE-sample-data' # Maja # mne_dir = mne.get_config('MNE_DATASETS_SAMPLE_PATH') # Alex # data_path = mne_dir + '/MNE-sample-data' subjects_dir = os.path.join(data_path, 'subjects') hemi = 'both' brain = Brain(subject_name, hemi, 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white') for parcel in labels_pred: brain.add_label(parcel, alpha=1, color=colors['pred']) for parcel in labels_true: brain.add_label(parcel, alpha=1, color=colors['true']) for parcel in set(labels_pred) & set(labels_true): brain.add_label(parcel, alpha=1, color=colors['overlap']) import pdb pdb.set_trace()
def test_meg_inverse(): """Test plotting of MEG inverse solution.""" _set_backend() brain = Brain(*std_args) stc_fname = os.path.join(data_dir, 'meg_source_estimate-lh.stc') stc = io.read_stc(stc_fname) vertices = stc['vertices'] colormap = 'hot' data = stc['data'] data_full = (brain.geo['lh'].nn[vertices][..., np.newaxis] * data[:, np.newaxis]) time = np.linspace(stc['tmin'], stc['tmin'] + data.shape[1] * stc['tstep'], data.shape[1], endpoint=False) def time_label(t): return 'time=%0.2f ms' % (1e3 * t) for use_data in (data, data_full): brain.add_data(use_data, colormap=colormap, vertices=vertices, smoothing_steps=1, time=time, time_label=time_label) brain.scale_data_colormap(fmin=13, fmid=18, fmax=22, transparent=True) assert brain.data_dict['lh']['time_idx'] == 0 brain.set_time(.1) assert brain.data_dict['lh']['time_idx'] == 2 # viewer = TimeViewer(brain) # multiple data layers pytest.raises(ValueError, brain.add_data, data, vertices=vertices, time=time[:-1]) brain.add_data(data, colormap=colormap, vertices=vertices, smoothing_steps=1, time=time, time_label=time_label, initial_time=.09) assert brain.data_dict['lh']['time_idx'] == 1 data_dicts = brain._data_dicts['lh'] assert len(data_dicts) == 3 assert data_dicts[0]['time_idx'] == 1 assert data_dicts[1]['time_idx'] == 1 # shift time in both layers brain.set_data_time_index(0) assert data_dicts[0]['time_idx'] == 0 assert data_dicts[1]['time_idx'] == 0 brain.set_data_smoothing_steps(2) # add second data-layer without time axis brain.add_data(data[:, 1], colormap=colormap, vertices=vertices, smoothing_steps=2) brain.set_data_time_index(2) assert len(data_dicts) == 4 # change surface brain.set_surf('white') # remove all layers brain.remove_data() assert brain._data_dicts['lh'] == [] brain.close()
def plot_stc(stc): ''' Plot average stc within freq range. ''' brain = Brain(subj_id, 'split', 'inflated', size=(800, 400), views=['lat','med']) freqs = stc_av.times f_mask = [(freqs > low) & (freqs < high)] f_idx = np.nonzero(f_mask)[1] freqs_mask = freqs[f_mask] l_data = stc_av.lh_data l_data_mask = l_data[:,f_idx] l_data_mean = np.mean(l_data_mask, axis = 1) l_vertices = stc_av.lh_vertno r_data = stc_av.rh_data r_data_mask = r_data[:,f_idx] r_data_mean = np.mean(r_data_mask, axis = 1) r_vertices = stc_av.rh_vertno cmap = 'nipy_spectral' smooth = 10 time = np.mean(freqs_mask) brain.add_data(l_data_mean, colormap = cmap, vertices = l_vertices, smoothing_steps = smooth, time = time, colorbar = True, hemi = 'lh') brain.add_data(r_data_mean, colormap = cmap, vertices = r_vertices, smoothing_steps = smooth, time = time, colorbar = True, hemi = 'rh') return(brain)
def panel_mesh_axial(foci, foci_colors, color_scales): if not withsurfer: print "Cannot do 3D without PySurder. Exiting" exit() foci_colors = np.array(foci_colors) brain = Brain(subject_id, "both", "pial", cortex='ivory', alpha=0.1, background='white'); for color in np.unique(foci_colors): brain.add_foci(foci[foci_colors==color, :], hemi='rh', scale_factor=color_scales[color], color=color); brain.show_view(view=dict(azimuth=0.0, elevation=0), roll=90); pic = brain.screenshot() plt.imshow(pic); # small axis #plt.xlabel('MNI Y', size=24); #plt.xticks(np.arange(0, 800, 40), np.asarray(np.arange(-75, 106, 9.0), dtype='int'), size=18, rotation=90); #plt.ylabel('MNI X', size=24); #plt.yticks(np.arange(0, 800, 40), np.asarray(np.arange(-94.5, 93.5, 9.4), dtype='int'), size=18); # big axis plt.xlabel('MNI Y', size=24); plt.xticks(np.arange(0, 800, 50), np.asarray(np.arange(-75, 106, 11.3125), dtype='int'), size=24, rotation=90); plt.ylabel('MNI Z', size=24); plt.yticks(np.arange(0, 800, 50), np.asarray(np.arange(-94.5, 93.5, 11.75), dtype='int'), size=24); plt.xlim(0, 800); plt.ylim(800, 0);
def plot_V1V2(measure, hemi, clim): data, vert = extract_hemi_data(src_df, measure, time, hemi) brain = Brain('fsaverage', hemi, 'inflated', cortex='low_contrast', subjects_dir='mne_subjects', background='w', foreground='k') brain.add_data(data, vertices=vert, min=-clim[2], max=clim[2], time=[time], time_label=lambda t: '%d ms' % (t * 1000), colormap=morph_divergent_cmap(cmap, clim), hemi=hemi, smoothing_steps=5) labels = mne.read_labels_from_annot('fsaverage', parc='HCPMMP1', hemi=hemi, regexp='[LR]_((V1)|(V2)).*') for label in labels: brain.add_label(label, borders=True) mlab.view(*views[hemi]) return brain
def translate_electrodes_onto_the_brain_surface(subject_name, subjects_dir, elec_sorted): #find brain surface points brain = Brain(subject_id=subject_name, subjects_dir=subjects_dir, surf='pial', hemi='lh', offscreen=True) surf = brain.geo['lh'] src = np.array([surf.x, surf.y, surf.z]).T #use ConvexHull to chek if a point is inside the brain or not elec_up = np.zeros([64, 3]) hull = ConvexHull(src) for i, e in enumerate(elec_sorted): a = 1 n = deepcopy(e) while a == 1: new_hull = ConvexHull(np.concatenate((hull.points, [e]))) if np.array_equal(new_hull.vertices, hull.vertices): a = 1 e += n * 0.01 else: a = 0 elec_up[i] = e return elec_up
def test_movie(): """Test saving a movie of an MEG inverse solution.""" import imageio # create and setup the Brain instance _set_backend() brain = Brain(*std_args) stc_fname = os.path.join(data_dir, 'meg_source_estimate-lh.stc') stc = io.read_stc(stc_fname) data = stc['data'] time = np.arange(data.shape[1]) * stc['tstep'] + stc['tmin'] brain.add_data(data, colormap='hot', vertices=stc['vertices'], smoothing_steps=10, time=time, time_label='time=%0.2f ms') brain.scale_data_colormap(fmin=13, fmid=18, fmax=22, transparent=True) # save movies with different options tempdir = mkdtemp() try: dst = os.path.join(tempdir, 'test.mov') # test the number of frames in the movie brain.save_movie(dst) frames = imageio.mimread(dst) assert_equal(len(frames), 2) brain.save_movie(dst, time_dilation=10) frames = imageio.mimread(dst) assert_equal(len(frames), 7) brain.save_movie(dst, tmin=0.081, tmax=0.102) frames = imageio.mimread(dst) assert_equal(len(frames), 2) finally: # clean up if not (sys.platform == 'win32' and os.getenv('APPVEYOR', 'False') == 'True'): # cleanup problems shutil.rmtree(tempdir) brain.close()
def test_text(): """Test plotting of text """ mlab.options.backend = 'test' brain = Brain(*std_args) brain.add_text(0.1, 0.1, 'Hello', 'blah') brain.close()
def plot_overlays_diff_group_window(condition,method,modality,hemi,window,azimuth,elevation): subject_id, surface = 'fsaverage', 'inflated' hemi = hemi brain = Brain(subject_id, hemi, surface, size=(600, 600)) stc_fname = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/BrainMaps/IcaCorr_Normalized' + modality + '_' + condition[0] + '-' + condition[1] + '_pick_oriNone_' + method + '_ico-5-fwd-fsaverage.stc-'+ hemi +'.stc') stcl_fname = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/BrainMaps/IcaCorr_Normalized' + modality + '_' + condition[0] + '-' + condition[1] + '_pick_oriNone_' + method + '_ico-5-fwd-fsaverage.stc-lh.stc') stcr_fname = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/BrainMaps/IcaCorr_Normalized' + modality + '_' + condition[0] + '-' + condition[1] + '_pick_oriNone_' + method + '_ico-5-fwd-fsaverage.stc-rh.stc') stcl = read_stc(stcl_fname) stcr = read_stc(stcr_fname) datal = stcl['data'] datar = stcr['data'] stc = read_stc(stc_fname) data = stc['data'] vertices = stc['vertices'] time = np.linspace(stc['tmin'], stc['tmin'] + data.shape[1] * stc['tstep'], data.shape[1]) winstart = np.where(time < window[0])[0][-1] winend = np.where(time >= window[1])[0][0] meanval = np.mean(data[:,winstart:winend],1) meanvalr = np.mean(datar[:,winstart:winend],1) meanvall = np.mean(datal[:,winstart:winend],1) maxval = np.max([np.max(meanvalr),np.max(meanvall)]) minval = np.min([np.min(meanvalr),np.min(meanvall)]) fmin = -np.max(np.abs([maxval,minval]))*0.8 fmax = np.max(np.abs([maxval,minval]))*0.8 colormap = mne.viz.mne_analyze_colormap(limits=[fmin, fmin/3, fmin/3.1, fmax/3.1, fmax/3, fmax], format='mayavi') #colormap = 'jet' time_label = lambda t: 'time=%0.2f ms' % (0) brain.add_data(meanval, colormap=colormap, vertices=vertices, smoothing_steps=15, time=time, time_label=time_label, hemi=hemi) brain.scale_data_colormap(fmin=fmin, fmid=0, fmax=fmax, transparent=False) brain.show_view(dict(azimuth=azimuth,elevation=elevation, distance=None)) # mayavi.mlab.view(azimuth=0, elevation=None, distance=None, focalpoint=None, # roll=None, reset_roll=True, figure=None) PlotDir = [] PlotDir = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/Plots/IcaCorr_Window_' + condition[0] + '-' + condition[1] + str(window[0]) + '-' + str(window[1])) if not os.path.exists(PlotDir): os.makedirs(PlotDir) brain.save_image(PlotDir + '/IcaCorr_' + modality + '_' + method + '_' + '_Normalized' + condition[0] + '-' + condition[1] + '_' + str(window[0]) + '-' + str(window[1]) + hemi + '_'+ str(azimuth)+ '_ico-5-fwd-fsaverage-'+'.png')
def plot_single_roi(roi): fsaverage = "fsaverage" hemi = "lh" surf = "inflated" t, p, str_names, labels = get_data() df = pd.DataFrame({'labs': str_names, 't': 0}) df.loc[df.labs == roi, 't'] = -4 data = df.t.values data = data[labels] brain = Brain(fsaverage, hemi, surf, background="white", views=['lateral', 'ventral', 'medial', 'frontal']) brain.add_data(data, -10, 11, thresh=None, colormap="RdBu_r", alpha=1) f = brain.save_montage(None, [['lateral', 'parietal'], ['medial', 'frontal']], border_size=0, colorbar=None) fig, a = plt.subplots() im = plt.imshow(f, cmap='RdBu_r') a.set(xticks=[], yticks=[]) sns.despine(bottom=True, left=True) cbar = fig.colorbar(im, ticks=[f.min(), (f.min() + 255) / 2, 255], orientation='horizontal', drawedges=False) cbar.ax.set_xticklabels(['-10', '0', '10']) a.set_title(roi) return f, data
def plot_distance(subject, data_dir, parcels, parcel_name='1-lh'): print('displaying brain of subject {}, distances from label {}'.format( subject, parcel_name)) data_path = 'mne_data/MNE-sample-data' # Maja subjects_dir = os.path.join(data_path, 'subjects') hemi = 'both' brain = Brain(subject, hemi, 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white') dist_path_lh = os.path.join(data_dir, subject + '_dist_matrix_lh.csv') dist_matrix_lh = pd.read_csv(dist_path_lh, index_col=0) dist_matrix_lh_norm = dist_matrix_lh.divide(dist_matrix_lh.max().max()) if 'lh' in parcel_name: hemi = 'lh' elif 'rh' in parcel_name: hemi = 'rh' for parcel in parcels: if parcel_name == parcel.name: brain.add_label(parcel, alpha=1, color='blue') elif hemi in parcel.name: dist = dist_matrix_lh_norm.loc[parcel_name][parcel.name] brain.add_label(parcel, alpha=1, color=str(1 - dist)) import pdb pdb.set_trace() cm = parcel.center_of_mass(subject, subjects_dir=subjects_dir) brain.add_foci(cm, coords_as_verts=True, hemi='lh', color='blue')
def test_brains(): """Test plotting of Brain with different arguments """ # testing backend breaks when passing in a figure, so we use 'auto' here # (shouldn't affect usability, but it makes testing more annoying) mlab.options.backend = 'auto' surfs = ['inflated', 'white'] hemis = ['lh', 'rh'] curvs = [True, False] titles = [None, 'Hello'] cortices = ["low_contrast", ("Reds", 0, 1, False)] sizes = [500, (400, 300)] backgrounds = ["white", "blue"] foregrounds = ["black", "white"] figs = [None, mlab.figure()] subj_dirs = [None, subj_dir] for surf, hemi, curv, title, cort, s, bg, fg, fig, sd \ in zip(surfs, hemis, curvs, titles, cortices, sizes, backgrounds, foregrounds, figs, subj_dirs): brain = Brain(subject_id, hemi, surf, curv, title, cort, s, bg, fg, fig, sd) brain.close() assert_raises(ValueError, Brain, subject_id, 'lh', 'inflated', subjects_dir='')
def test_probabilistic_labels(): """Test plotting of probabilistic labels """ mlab.options.backend = 'test' brain = Brain("fsaverage", "lh", "inflated", config_opts=dict(cortex="low_contrast")) brain.add_label("BA1", color="darkblue") brain.add_label("BA1", color="dodgerblue", scalar_thresh=.5) brain.add_label("BA45", color="firebrick", borders=True) brain.add_label("BA45", color="salmon", borders=True, scalar_thresh=.5) label_file = pjoin(subj_dir, "fsaverage", "label", "lh.BA6.label") prob_field = np.zeros_like(brain._geo.x) ids, probs = nib.freesurfer.read_label(label_file, read_scalars=True) prob_field[ids] = probs brain.add_data(prob_field, thresh=1e-5) brain.data["colorbar"].number_of_colors = 10 brain.data["colorbar"].number_of_labels = 11 brain.close()
def test_annot(): """Test plotting of annot.""" _set_backend() annots = ['aparc', 'aparc.a2005s'] borders = [True, False, 2] alphas = [1, 0.5] brain = Brain(*std_args) view = get_view(brain) for a, b, p in zip(annots, borders, alphas): brain.add_annotation(a, b, p, opacity=0.8) check_view(brain, view) brain.set_surf('white') with pytest.raises(ValueError): brain.add_annotation('aparc', borders=-1) subj_dir = utils._get_subjects_dir() annot_path = pjoin(subj_dir, subject_id, 'label', 'lh.aparc.a2009s.annot') labels, ctab, names = nib.freesurfer.read_annot(annot_path) brain.add_annotation((labels, ctab)) brain.add_annotation('aparc', color="red", remove_existing=True) surf = brain.annot["surface"] ctab = surf.module_manager.scalar_lut_manager.lut.table for color in ctab: assert color[:3] == (255, 0, 0) brain.close()
def montage_plot(parameter, in_dir, task, fdr_correct=True, hemi='lh', input_hemisphere='', annot=None): ''' Make plots for parameter on the cortical surface using pysurf module - Arguments: a) parameter b) output directory c) task (inference or instructed) d) FDR correction (boolean) ''' out_dir = join(in_dir, 'pysurf_plots') slu.mkdir_p(out_dir) fsaverage = "fsaverage" surf = "inflated" t_data, p_data, str_names, labels = get_data(task, in_dir, input_hemisphere, hemi) if fdr_correct is True: data = fdr_filter(t_data, p_data, parameter) else: data = t_data[parameter].values data = data[labels] brain = Brain(fsaverage, hemi, surf, background="white", title=parameter + task) brain.add_data(data, -10, 10, thresh=None, colormap="RdBu_r", alpha=.8) if annot is not None: brain.add_annotation(annot, color='white', alpha=1) brain.save_imageset(join(out_dir, parameter + '_' + task + input_hemisphere), ['lateral', 'medial', 'par'], colorbar=None)
def test_foci(): """Test plotting of foci.""" _set_backend('test') brain = Brain(*std_args) coords = [[-36, 18, -3], [-43, 25, 24], [-48, 26, -2]] brain.add_foci(coords, map_surface="white", color="gold", name='test1', resolution=25) subj_dir = utils._get_subjects_dir() annot_path = pjoin(subj_dir, subject_id, 'label', 'lh.aparc.a2009s.annot') ids, ctab, names = nib.freesurfer.read_annot(annot_path) verts = np.arange(0, len(ids)) coords = np.random.permutation(verts[ids == 74])[:10] scale_factor = 0.7 brain.add_foci(coords, coords_as_verts=True, scale_factor=scale_factor, color="#A52A2A", name='test2') with pytest.raises(ValueError): brain.remove_foci(['test4']) brain.remove_foci('test1') brain.remove_foci() assert len(brain.foci_dict) == 0 brain.close()
def brain_plot(r_name, viewtimes, brain): views = {'rh': ['medial', 'parietal'], 'lh': ['parietal', 'medial']} if type(brain) is str: hemi = brain brain = Brain('fsaverage', hemi, 'inflated', cortex='low_contrast', subjects_dir=sv.subjects_dir, background='w', foreground='k') else: hemi = brain.geo.keys()[0] sv.show_labels_as_data(src_df_masked.loc[r_name], show_measure, brain, **colorinfo) filepat = os.path.join( figdir, filepat_base + '_{}_{}_%02d.png'.format(hemi, r_name)) brain.save_image_sequence([times.get_loc(t) for t in viewtimes], filepat, montage=views[hemi]) return brain
def test_label(): """Test plotting of label.""" _set_backend() subject_id = "fsaverage" hemi = "lh" surf = "inflated" brain = Brain(subject_id, hemi, surf) view = get_view(brain) extra, subj_dir = _get_extra() brain.add_label("BA1" + extra) check_view(brain, view) brain.add_label("BA1" + extra, color="blue", scalar_thresh=.5) label_file = pjoin(subj_dir, subject_id, "label", "%s.MT%s.label" % (hemi, extra)) brain.add_label(label_file) brain.add_label("BA44" + extra, borders=True) brain.add_label("BA6" + extra, alpha=.7) brain.show_view("medial") brain.add_label("V1" + extra, color="steelblue", alpha=.6) brain.add_label("V2" + extra, color="#FF6347", alpha=.6) brain.add_label("entorhinal" + extra, color=(.2, 1, .5), alpha=.6) brain.set_surf('white') brain.show_view(dict(elevation=40, distance=430), distance=430) with pytest.raises(ValueError, match='!='): brain.show_view(dict(elevation=40, distance=430), distance=431) # remove labels brain.remove_labels('V1' + extra) assert 'V2' + extra in brain.labels_dict assert 'V1' + extra not in brain.labels_dict brain.remove_labels() assert 'V2' + extra not in brain.labels_dict brain.close()