def drawROI(): for hemi in ["lh"]: # load data roivol = io.project_volume_data(roifile, hemi, subject_id=surfsubj, smooth_fwhm=4.0, projmeth="dist", projsum="avg", projarg=[0,6,0.1], surf="white") # create label roivol = abs(roivol) roivol[roivol < 0.33] = 0 #if max(roivol) < 1: # brain.close() # continue #else: write_label(np.asarray(np.nonzero(roivol)),"/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.label") # load brain my_fig = mlab.figure(figure="new_fig1", size=(800,800)) brain = Brain("fsaverage",hemi,"inflated",curv=True,size=[800,800],background="white",cortex=(("gist_yarg",-1.5,3.5,False)),figure=my_fig) set_mylights(my_fig,lights[hemi]) #add label brain.add_label("/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.label",borders=False,color="#ffff00",alpha=1) brain.add_label("/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.label",borders=1,color="black",alpha=0.5) brain.show_view('lat') brain.save_image("/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.tiff") brain.close()
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_movie(): """Test saving a movie of an MEG inverse solution """ # create and setup the Brain instance mlab.options.backend = 'auto' 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') brain.save_movie(dst) brain.save_movie(dst, tmin=0.081, tmax=0.102) # test the number of frames in the movie sp = subprocess.Popen(('ffmpeg', '-i', 'test.mov', '-vcodec', 'copy', '-f', 'null', '/dev/null'), cwd=tempdir, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = sp.communicate() m = re.search('frame=\s*(\d+)\s', stderr) if not m: raise RuntimeError(stderr) n_frames = int(m.group(1)) assert_equal(n_frames, 3) finally: # clean up shutil.rmtree(tempdir) brain.close()
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 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_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 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 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()
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_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_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', 'white', 'white', 'white', 'white', 'white'] hemis = ['lh', 'rh', 'both', 'both', 'rh', 'both', 'both'] titles = [None, 'Hello', 'Good bye!', 'lut test', 'dict test', 'None test', 'RGB test'] cortices = ["low_contrast", ("Reds", 0, 1, False), 'hotpink', ['yellow', 'blue'], dict(colormap='Greys'), None, (0.5, 0.5, 0.5)] sizes = [500, (400, 300), (300, 300), (300, 400), 500, 400, 300] backgrounds = ["white", "blue", "black", "0.75", (0.2, 0.2, 0.2), "black", "0.75"] foregrounds = ["black", "white", "0.75", "red", (0.2, 0.2, 0.2), "blue", "black"] figs = [None, mlab.figure(), None, None, mlab.figure(), None, None] subj_dirs = [None, subj_dir, subj_dir, subj_dir, subj_dir, subj_dir, subj_dir] alphas = [1.0, 0.5, 0.25, 0.7, 0.5, 0.25, 0.7] for surf, hemi, title, cort, s, bg, fg, fig, sd, alpha \ in zip(surfs, hemis, titles, cortices, sizes, backgrounds, foregrounds, figs, subj_dirs, alphas): brain = Brain(subject_id, hemi, surf, title=title, cortex=cort, alpha=alpha, size=s, background=bg, foreground=fg, figure=fig, subjects_dir=sd) brain.close() assert_raises(ValueError, Brain, subject_id, 'lh', 'inflated', subjects_dir='')
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_equal(brain.data_dict['lh']['time_idx'], 0) brain.set_time(.1) assert_equal(brain.data_dict['lh']['time_idx'], 2) # viewer = TimeViewer(brain) # multiple data layers assert_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_equal(brain.data_dict['lh']['time_idx'], 1) data_dicts = brain._data_dicts['lh'] assert_equal(len(data_dicts), 3) assert_equal(data_dicts[0]['time_idx'], 1) assert_equal(data_dicts[1]['time_idx'], 1) # shift time in both layers brain.set_data_time_index(0) assert_equal(data_dicts[0]['time_idx'], 0) assert_equal(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_equal(len(data_dicts), 4) # change surface brain.set_surf('white') # remove all layers brain.remove_data() assert_equal(brain._data_dicts['lh'], []) brain.close()
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_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_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_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 curvature_normalization(data_dir, subj, close=True): """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") for hemi in ["lh", "rh"]: cmd = ["mri_surf2surf", "--srcsubject", subj, "--trgsubject", "fsaverage", "--hemi", hemi, "--sval", op.join(surf_dir, "%s.curv" % hemi), "--tval", op.join(surf_dir, "%s.curv.fsaverage.mgz" % hemi)] sub.check_output(cmd) b = Brain("fsaverage", hemi, "inflated", config_opts=dict(background="white", width=700, height=500)) curv = nib.load(op.join(surf_dir, "%s.curv.fsaverage.mgz" % hemi)) curv = (curv.get_data() > 0).squeeze() b.add_contour_overlay(curv, min=0, max=1.5, n_contours=2, line_width=4) b.contour["colorbar"].visible = False for view in ["lat", "med"]: b.show_view(view) mlab.view(distance=330) png = op.join(snap_dir, "%s.surf_warp_%s.png" % (hemi, view)) b.save_image(png) if close: b.close()
def vizify(self): for hemi in self.hemis: print "visualize %s" % hemi # Bring up the beauty (the underlay) brain = Brain(self.subject_id, hemi, self.surf, \ config_opts=self.config_opts, \ subjects_dir=self.subjects_dir) surf_data = io.read_scalar_data(self.overlay_surf[hemi]) if (sum(abs(surf_data)) > 0): # Overlay another hopeful beauty (functional overlay) brain.add_overlay(self.overlay_surf[hemi], name=self.overlay_name, min=self.min, max=self.max, sign=self.sign) # Update colorbar #brain.overlays[self.overlay_name].pos_bar.lut_mode = self.colorbar tmp = brain.overlays[self.overlay_name] lut = tmp.pos_bar.lut.table.to_array() lut[:,0:3] = self.colorbar tmp.pos_bar.lut.table = lut # Refresh brain.show_view("lat") brain.hide_colorbar() # Save the beauts brain.save_imageset("%s_%s" % (self.outprefix, hemi), self.views, 'jpg', colorbar=None) # End a great journey, till another life brain.close() return
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 test_meg_inverse(): """Test plotting of MEG inverse solution """ mlab.options.backend = 'test' 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'] vertices = stc['vertices'] time = np.linspace(stc['tmin'], stc['tmin'] + data.shape[1] * stc['tstep'], data.shape[1], endpoint=False) colormap = 'hot' def time_label(t): return 'time=%0.2f ms' % (1e3 * t) brain.add_data(data, colormap=colormap, vertices=vertices, smoothing_steps=10, time=time, time_label=time_label) brain.scale_data_colormap(fmin=13, fmid=18, fmax=22, transparent=True) assert_equal(brain.data_dict['lh']['time_idx'], 0) brain.set_time(.1) assert_equal(brain.data_dict['lh']['time_idx'], 2) # viewer = TimeViewer(brain) brain.add_data(data, colormap=colormap, vertices=vertices, smoothing_steps=10, time=time, time_label=time_label, initial_time=.09, remove_existing=True) assert_equal(brain.data_dict['lh']['time_idx'], 1) 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 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 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 test_offscreen(): """Test offscreen rendering """ mlab.options.backend = 'auto' brain = Brain(*std_args, offscreen=True) shot = brain.screenshot() assert_array_equal(shot.shape, (800, 800, 3)) brain.close()
def test_offscreen(): """Test offscreen rendering.""" _set_backend() brain = Brain(*std_args, offscreen=True) shot = brain.screenshot() assert_array_less((400, 400, 2), shot.shape) assert_array_less(shot.shape, (801, 801, 4)) brain.close()
def test_morphometry(): """Test plotting of morphometry.""" mlab.options.backend = 'test' brain = Brain(*std_args) brain.add_morphometry("curv") brain.add_morphometry("sulc", grayscale=True) brain.add_morphometry("thickness") brain.close()
def test_data_limits(): """Test handling of data limits.""" _set_backend() brain = Brain(*std_args) surf_data = np.zeros(163842) pytest.raises(ValueError, brain.add_data, surf_data, 0, 0) brain.add_data(surf_data, 0, 1) brain.close()
def test_morphometry(): """Test plotting of morphometry.""" _set_backend() brain = Brain(*std_args) brain.add_morphometry("curv") brain.add_morphometry("sulc", grayscale=True) brain.add_morphometry("thickness") brain.close()
def plot_parcel(num_nodes=600,numbers=[1],hemi='lh'): from surfer import Brain, io for n in numbers: brain = Brain("fsaverage", "%s" %(hemi), "pial",config_opts=dict(background="white")) image = io.project_volume_data('/home/despo/mb3152/random_nodes/%s/parcel_%s.nii'%(num_nodes,n),hemi, subject_id="fsaverage", projsum = 'max', smooth_fwhm = 0) brain.add_data(image,thresh=1,colormap = "spectral") brain.save_imageset('/home/despo/mb3152/random_nodes/%s/parcel_%s' %(num_nodes,n),['med','lat'],'jpg',colorbar= None) brain.close()
def corr_image(resting_image,fwhm): """This function makes correlation image on brain surface""" import numpy as np import nibabel as nb import matplotlib.pyplot as plt from surfer import Brain, Surface import os img = nb.load(resting_image) corrmat = np.corrcoef(np.squeeze(img.get_data())) corrmat[np.isnan(corrmat)] = 0 corrmat_npz = os.path.abspath('corrmat.npz') np.savez(corrmat_npz,corrmat=corrmat) br = Brain('fsaverage5', 'lh', 'smoothwm') #br.add_overlay(corrmat[0,:], min=0.2, name=0, visible=True) lh_aparc_annot_file = os.path.join(os.environ["FREESURFER_HOME"],'/subjects/label/lh.aparc.annot') values = nb.freesurfer.read_annot(lh_aparc_annot_file) #br.add_overlay(np.mean(corrmat[values[0]==5,:], axis=0), min=0.8, name='mean', visible=True) data = img.get_data() data = np.squeeze(img.get_data()) # precuneus_signal = np.mean(data[values[0]==np.nonzero(np.array(values[2])=='precuneus')[0][0],:], axis=0) precuneus = np.corrcoef(precuneus_signal, data) #precuneus.shape #br.add_overlay(precuneus[0,1:], min=0.3, sign='pos', name='mean', visible=True) br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True) #br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True) plt.hist(precuneus[0,1:], 128) plt.savefig(os.path.abspath("histogram.png")) plt.close() corr_image = os.path.abspath("corr_image%s.png"%fwhm) br.save_montage(corr_image) ims = br.save_imageset(prefix=os.path.abspath('fwhm_%s'%str(fwhm)),views=['medial','lateral','caudal','rostral','dorsal','ventral']) br.close() print ims #precuneus[np.isnan(precuneus)] = 0 #plt.hist(precuneus[0,1:]) roitable = [['Region','Mean Correlation']] for i, roi in enumerate(np.unique(values[2])): roitable.append([roi,np.mean(precuneus[values[0]==np.nonzero(np.array(values[2])==roi)[0][0]])]) #images = [corr_fimage]+ims+[os.path.abspath("histogram.png"), roitable] roitable=[roitable] histogram = os.path.abspath("histogram.png") return corr_image, ims, roitable, histogram, corrmat_npz
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_data(): """Test plotting of data """ mlab.options.backend = 'test' brain = Brain(*std_args) mri_file = pjoin(data_dir, 'resting_corr.nii.gz') reg_file = pjoin(data_dir, 'register.dat') surf_data = io.project_volume_data(mri_file, "lh", reg_file) brain.add_data(surf_data, -.7, .7, colormap="jet", alpha=.7) brain.close()
def test_offscreen(): """Test offscreen rendering.""" mlab.options.backend = 'auto' brain = Brain(*std_args, offscreen=True) # Sometimes the first screenshot is rendered with a different # resolution on OS X brain.screenshot() shot = brain.screenshot() assert_array_equal(shot.shape, (800, 800, 3)) brain.close()
def test_contour(): """Test plotting of contour overlay.""" _set_backend() brain = Brain(*std_args) overlay_file = pjoin(data_dir, "lh.sig.nii.gz") brain.add_contour_overlay(overlay_file) brain.add_contour_overlay(overlay_file, max=20, n_contours=9, line_width=2) brain.contour['surface'].actor.property.line_width = 1 brain.contour['surface'].contour.number_of_contours = 10 brain.close()
def make_brain_figures(srcdf, measure, cinfo, filepat_base, top=5): views = {'rh': ['medial', 'lateral'], 'lh': ['lateral', 'medial']} toplabels = {} for hemi in ['lh', 'rh']: brain = Brain('fsaverage', hemi, 'inflated', cortex='low_contrast', subjects_dir=sv.subjects_dir, background='w', foreground='k') sv.show_labels_as_data(srcdf, measure, brain, time_label=None, parc=parc, **cinfo) if top: ind = srcdf.index.get_level_values('label').map( lambda x: x.startswith(hemi[0].upper())) topl = srcdf[ind].abs().sort_values( measure, ascending=False).head(top) topl = ( topl[(topl[measure] != 0) & topl[measure].notna()] .index.droplevel('time')) toplabels[hemi] = topl alllabels = mne.read_labels_from_annot( 'fsaverage', parc=parc, hemi=hemi) brain.remove_labels() for label in alllabels: if label.name in topl: brain.add_label(label, borders=1, hemi=hemi, alpha=0.8, color='k') # increase font size of colorbar - this only works by increasing the # colorbar itself and setting the ratio of colorbar to text brain.data['colorbar'].scalar_bar.bar_ratio = 0.35 brain.data['colorbar'].scalar_bar_representation.position = [0.075, 0.01] brain.data['colorbar'].scalar_bar_representation.position2 = [0.85, 0.12] filepat = os.path.join(figdir, filepat_base + '_{}.png'.format(hemi)) brain.save_montage(filepat, views[hemi], colorbar=0) brain.close() infiles = [ os.path.join(figdir, filepat_base + '_{}.png'.format(hemi)) for hemi in ['lh', 'rh']] outfile = os.path.join(figdir, filepat_base + '.png') os.system("montage -tile 2x1 -geometry +0+0 {} {}".format( ' '.join(infiles), outfile)) return toplabels
def test_annot(): """Test plotting of annot.""" mlab.options.backend = 'test' annots = ['aparc', 'aparc.a2005s'] borders = [True, False, 2] alphas = [1, 0.5] brain = Brain(*std_args) for a, b, p in zip(annots, borders, alphas): brain.add_annotation(a, b, p) assert_raises(ValueError, brain.add_annotation, 'aparc', borders=-1) brain.close()
def test_annot(): """Test plotting of annot """ mlab.options.backend = 'test' annots = ['aparc', 'aparc.a2005s'] borders = [True, False] alphas = [1, 0.5] brain = Brain(*std_args) for a, b, p in zip(annots, borders, alphas): brain.add_annotation(a, b, p) brain.close()
def pysurfer_plot_perm_ttest_results(vertices, vertives_values, max_vals, fol): T = max(vertices.keys()) for t in range(T+1): print(t) brain = Brain('fsaverage', 'split', 'pial', curv=False, offscreen=False, views=['lat', 'med'], title='{} ms'.format(t)) for hemi in ['rh', 'lh']: if t in vertices: brain.add_data(np.array(vertives_values[t][hemi]), hemi=hemi, min=1, max=max_vals, remove_existing=True, colormap="YlOrRd", alpha=1, vertices=np.array(vertices[t][hemi])) brain.save_image(os.path.join(fol, '{}.jpg'.format(t))) brain.close()
def test_animate(): """Test animation.""" _set_backend('auto') brain = Brain(*std_args, size=100) brain.add_morphometry('curv') tmp_name = mktemp() + '.avi' brain.animate(["m"] * 3, n_steps=2) brain.animate(['l', 'l'], n_steps=2, fname=tmp_name) # can't rotate in axial plane assert_raises(ValueError, brain.animate, ['l', 'd']) brain.close()
def test_data(): """Test plotting of data.""" _set_backend() brain = Brain(*std_args) mri_file = pjoin(data_dir, 'resting_corr.nii.gz') reg_file = pjoin(data_dir, 'register.dat') surf_data = io.project_volume_data(mri_file, "lh", reg_file) brain.add_data(surf_data, -.7, .7, colormap="jet", alpha=.7) brain.set_surf('white') brain.add_data([], vertices=np.array([], int)) brain.close()
def test_image(): """Test image saving """ mlab.options.backend = 'auto' brain = Brain(*std_args, config_opts=small_brain) tmp_name = mktemp() + '.png' brain.save_image(tmp_name) brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg') brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v') brain.screenshot() brain.close()