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 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 loadScalar(pathToScalar): ''' Method to read scalar vectors for example in mgh format ''' outVec = io.read_scalar_data(pathToScalar) return outVec
def vol_to_surf(infile, outprefix=None, interp="trilinear", hemis=["lh", "rh"]): """ Transforms a volume from MNI to FSaverage space using mri_vol2surf. Parameters ---------- infile : str outprefix : str or None (default: None) When outfile is None, the path will be autogenerated using tmpfile. The suffix of the file will be the hemi and .nii.gz. interp : str (default: trilinear) Can be 'nearest' or 'trilinear'. hemis : list (default: ['lh', 'rh']) Returns -------- outfiles : dict For instance: `{'lh': 'file1', 'rh': 'file2'}`. outsurfs : dict For instance: `{'lh': surf_lh, 'rh': surf_rh}` where surf_* is an `ndarray`. """ if not op.exists(infile): raise Exception("Input for vol_to_surf '%s' doesn't exist" % infile) if outprefix is None: to_clean = True _,outprefix = tempfile.mkstemp() else: to_clean = False outfiles = {} outsurfs = {} templ_vars = dict(input=infile, interp=interp) for hemi in hemis: outfile = "%s_%s.nii.gz" % (outprefix, hemi) outfiles[hemi] = outfile templ_vars["hemi"] = hemi templ_vars["output"] = outfile cmd = "mri_vol2surf --mov %(input)s \ --mni152reg --projfrac-max 0 1 0.1 \ --interp %(interp)s --hemi %(hemi)s \ --out %(output)s --reshape" % templ_vars print cmd p = Process(cmd) print p.stdout print p.stderr if p.retcode != 0: raise Exception("mri_vol2surf failed") outsurfs[hemi] = io.read_scalar_data(outfile) if to_clean: os.remove(outprefix) return (outfiles, outsurfs)
def test_overlay(): """Test plotting of overlay.""" _set_backend() # 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")) # two-sided overlay brain.add_overlay(sig1, 4, 30, name="two-sided") overlay = brain.overlays_dict.pop('two-sided')[0] assert_array_equal(overlay.pos_bar.data_range, [4, 30]) assert_array_equal(overlay.neg_bar.data_range, [-30, -4]) assert_equal(overlay.pos_bar.reverse_lut, True) assert_equal(overlay.neg_bar.reverse_lut, False) overlay.remove() 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.set_surf('white') brain.close()
def mask_vtx_data(overlay_fname, cortex_fname, thresh): vtx_data = io.read_scalar_data(overlay_fname) cortex_data = io.read_label(cortex_fname) # Create a mask of 1s where there is cortex and 0s on the medial wall mask = np.zeros_like(vtx_data) mask[cortex_data] = 1 # Set all values that are not in cortex to thresh-1 vtx_data[mask == 0] = thresh-1 return vtx_data
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 run(cmd): print(cmd) os.system(cmd) prefix = op.join(odir, "surf_neurosynth") ns_combined_dir = op.join(base, "neurosynth/neurosynth/intelligence_reasoning_wm") cmd = "./x_vol2surf.py %s/_pAgF_z.nii.gz %s/_pAgF_z_FDR_0.05.nii.gz %s" % ( ns_combined_dir, ns_combined_dir, prefix) #run(cmd) ns_combined = { hemi: io.read_scalar_data("%s_%s.nii.gz" % (prefix, hemi)) for hemi in ["lh", "rh"] } all_ns = ns_combined.values() print 'getting range' dmin2 = np.array([ns[ns.nonzero()].min() for ns in all_ns]).min() dmax2 = np.array([ns[ns.nonzero()].max() for ns in all_ns]).max() print 'min=%.4f; max=%.4f' % (dmin2, dmax2) ### # Overlap ### scans_and_ns = {} for hemi in ["lh", "rh"]:
print 'min=%.4f; max=%.4f' % (dmin,dmax) ### # Neurosynth ### def run(cmd): print(cmd) os.system(cmd) prefix = op.join(odir, "surf_neurosynth") ns_combined_dir = op.join(base, "neurosynth/neurosynth/intelligence_reasoning_wm") cmd = "./x_vol2surf.py %s/_pAgF_z.nii.gz %s/_pAgF_z_FDR_0.05.nii.gz %s" % (ns_combined_dir, ns_combined_dir, prefix) #run(cmd) ns_combined = { hemi : io.read_scalar_data("%s_%s.nii.gz" % (prefix, hemi)) for hemi in ["lh", "rh"] } all_ns = ns_combined.values() print 'getting range' dmin2 = np.array([ ns[ns.nonzero()].min() for ns in all_ns ]).min() dmax2 = np.array([ ns[ns.nonzero()].max() for ns in all_ns ]).max() print 'min=%.4f; max=%.4f' % (dmin2,dmax2) ### # Overlap ### scans_and_ns = {} for hemi in ["lh", "rh"]: # 1. Combine IQ CWAS Scan 1 and 2
dmin = ranges.min() dmax = ranges.max() print 'min=%.4f; max=%.4f' % (dmin,dmax) ### # Read surfaces ### print "...reading surfaces" surfs = {} for measure in measures: surfs[measure] = {} for hemi in ["lh", "rh"]: tmp = io.read_scalar_data(all_surf_files[measure][hemi]) surfs[measure][hemi] = tmp ### # Plot ### print "...plotting" cbarfile = "/home2/data/Projects/CWAS/share/lib/surfwrap/colorbars/red-yellow.txt" cbar = load_colorbar(cbarfile) # Overlap for measure in measures: oprefix = op.join(odir, "surf_%s" % measure)
ipython #%gui qt %gui wx from surfer import Brain import mayavi from numpy import array import os.path as op import numpy as np from surfer import io ########################## TJ - SJ #########################" brain = Brain("fsaverage", "lh", "pial", config_opts={"cortex":"low_contrast","background":"black"}) sig1 = np.nan_to_num(io.read_scalar_data("/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/fMRI/GROUPlvl_TJ-SJ_lh.mgz")) sig2 = np.nan_to_num(io.read_scalar_data('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/fMRI/GROUPlvl_SJ-TJ_lh.mgz')) thresh = 1 sig1[sig1 < thresh] = 0 sig2[sig2 < thresh] = 0 conjunct = np.min(np.vstack((sig1, sig2)), axis=0) brain.add_overlay(sig1, 1, 8, name="sig1") brain.overlays["sig1"].pos_bar.lut_mode = "Reds" brain.overlays["sig1"].pos_bar.visible = False brain.add_overlay(sig2, 1, 8, name="sig2") brain.overlays["sig2"].pos_bar.lut_mode = "Blues" brain.overlays["sig2"].pos_bar.visible = False ################### CONJ[TJ-CTRL SJ- CTRL] ##################### ################## WHITE #######################################
brain.add_overlay(overlay_file, min=3.11, max=10, sign="pos") mayavi.mlab.view(azimuth=225, elevation=None, distance=None, focalpoint=None, roll=None, reset_roll=True, figure=None) mayavi.mlab.savefig("/neurospin/unicog/protocols/IRMf/BENOIT_MT/BAPTISTE_FOLDER/PICTURES/MOD30-2/GROUPlvl_TJ_CTRL_tT_extT_lh_projfrac05_face1.png", size=None, figure=None, magnification='auto') mayavi.mlab.view(azimuth=45, elevation=None, distance=None, focalpoint=None, roll=None, reset_roll=True, figure=None) mayavi.mlab.savefig("/neurospin/unicog/protocols/IRMf/BENOIT_MT/BAPTISTE_FOLDER/PICTURES/MOD30-2/GROUPlvl_TJ_CTRL_tT_extT_rh_projfrac05_face2.png", size=None, figure=None, magnification='auto') mayavi.mlab.view(azimuth=315, elevation=None, distance=None, focalpoint=None, roll=None, reset_roll=True, figure=None) mayavi.mlab.savefig("/neurospin/unicog/protocols/IRMf/BENOIT_MT/BAPTISTE_FOLDER/PICTURES/MOD30-2/GROUPlvl_TJ_CTRL_tT_extT_rh_projfrac05_face3.png", size=None, figure=None, magnification='auto') ################### SJ-CTRL ##################### ###################### LH ####################### brain = Brain("fsaverage", "lh", "inflated", config_opts={"cortex":"low_contrast","background":"black"}) overlay_file = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/fMRI/GROUPlvl_SJ_CTRL_tT_extT_lh_projfrac05.mgz" brain.add_overlay(overlay_file, min=3.11, max=10, sign="pos") sig1 = io.read_scalar_data(overlay_file) brain.add_overlay(sig1, 3.11, 10, name="sig1") brain.overlays['sig1'].pos_bar.lut_mode = "Blues" mayavi.mlab.view(azimuth=315, elevation=None, distance=None, focalpoint=None, roll=None, reset_roll=True, figure=None) mayavi.mlab.savefig("/neurospin/unicog/protocols/IRMf/BENOIT_MT/BAPTISTE_FOLDER/PICTURES/MOD30-2/GROUPlvl_SJ_CTRL_tT_extT_lh_projfrac05_face1.png", size=None, figure=None, magnification='auto') mayavi.mlab.view(azimuth=135, elevation=None, distance=None, focalpoint=None, roll=None, reset_roll=True, figure=None) mayavi.mlab.savefig("/neurospin/unicog/protocols/IRMf/BENOIT_MT/BAPTISTE_FOLDER/PICTURES/MOD30-2/GROUPlvl_SJ_CTRL_tT_extT_lh_projfrac05_face2.png", size=None, figure=None, magnification='auto') mayavi.mlab.view(azimuth=225, elevation=None, distance=None, focalpoint=None, roll=None, reset_roll=True, figure=None) mayavi.mlab.savefig("/neurospin/unicog/protocols/IRMf/BENOIT_MT/BAPTISTE_FOLDER/PICTURES/MOD30-2/GROUPlvl_SJ_CTRL_tT_extT_lh_projfrac05_face3.png", size=None, figure=None, magnification='auto') ###################### RH ####################### brain = Brain("fsaverage", "rh", "inflated", config_opts={"cortex":"low_contrast","background":"black"}) overlay_file = "/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/fMRI/GROUPlvl_SJ_CTRL_tT_extT_rh_projfrac05.mgz" brain.add_overlay(overlay_file, min=3.11, max=10, sign="pos")
import numpy as np from surfer import io from surfer import Brain print(__doc__) """ Initialize the visualization. """ brain = Brain("fsaverage", "lh", "inflated", background="white") """ Read both of the activation maps in using surfer's io functions. """ sig1 = io.read_scalar_data(op.join('example_data', "lh.sig.nii.gz")) sig2 = io.read_scalar_data(op.join('example_data', "lh.alt_sig.nii.gz")) """ Zero out the vertices that do not meet a threshold. """ thresh = 4 sig1[sig1 < thresh] = 0 sig2[sig2 < thresh] = 0 """ A conjunction is defined as the minimum significance value between the two maps at each vertex. """ conjunct = np.min(np.vstack((sig1, sig2)), axis=0)
ranges = np.array([ get_range(sfile) for sfile in all_sfiles ]) dmin = ranges.min() dmax = ranges.max() print 'min=%.4f; max=%.4f' % (dmin,dmax) ### # Overlap ### no = {} yes = {} combined = {} for hemi in ["lh", "rh"]: no[hemi] = io.read_scalar_data(all_surf_files["no"][hemi]) yes[hemi] = io.read_scalar_data(all_surf_files["yes"][hemi]) combined[hemi] = np.min(np.vstack((no[hemi], yes[hemi])), axis=0) ### # Plot ### # Overlap oprefix = op.join(odir, "surface_compare_transformation") for hemi in ["lh","rh"]: brain = fsaverage(hemi) surfov = no[hemi]
def vol_to_surf(infile, outprefix=None, interp="trilinear", hemis=["lh", "rh"]): """ Transforms a volume from MNI to FSaverage space using mri_vol2surf. Parameters ---------- infile : str outprefix : str or None (default: None) When outfile is None, the path will be autogenerated using tmpfile. The suffix of the file will be the hemi and .nii.gz. interp : str (default: trilinear) Can be 'nearest' or 'trilinear'. hemis : list (default: ['lh', 'rh']) Returns -------- outfiles : dict For instance: `{'lh': 'file1', 'rh': 'file2'}`. outsurfs : dict For instance: `{'lh': surf_lh, 'rh': surf_rh}` where surf_* is an `ndarray`. """ if not op.exists(infile): raise Exception("Input for vol_to_surf '%s' doesn't exist" % infile) if outprefix is None: to_clean = True _, outprefix = tempfile.mkstemp() else: to_clean = False outfiles = {} outsurfs = {} templ_vars = dict(input=infile, interp=interp) for hemi in hemis: outfile = "%s_%s.nii.gz" % (outprefix, hemi) outfiles[hemi] = outfile templ_vars["hemi"] = hemi templ_vars["output"] = outfile cmd = "mri_vol2surf --mov %(input)s \ --mni152reg --projfrac-max 0 1 0.1 \ --interp %(interp)s --hemi %(hemi)s \ --out %(output)s --reshape" % templ_vars print cmd p = Process(cmd) print p.stdout print p.stderr if p.retcode != 0: raise Exception("mri_vol2surf failed") outsurfs[hemi] = io.read_scalar_data(outfile) if to_clean: os.remove(outprefix) return (outfiles, outsurfs)
easydir = easydirs[scan] surf_files = { "lh": op.join(easydir, "surf_lh_thresh_zstat_FSIQ.nii.gz"), "rh": op.join(easydir, "surf_rh_thresh_zstat_FSIQ.nii.gz") } ba_files = { "lh": "/home2/data/PublicProgram/freesurfer/fsaverage_copy/label/lh.PALS_B12_Brodmann.annot", "rh": "/home2/data/PublicProgram/freesurfer/fsaverage_copy/label/rh.PALS_B12_Brodmann.annot", } hemi = "lh" ba = io.read_annot(ba_files[hemi]) cwas = io.read_scalar_data(surf_files[hemi]) rois = ba[0] urois = np.unique(rois); urois.sort() labels = np.array(ba[2])[urois] cols = ["index", "roi", "ba", "summary_wt", "summary_uwt", "meta_analysis"] dict_df = { k : [] for k in cols } for i,label in enumerate(labels): if label.find("Brodmann") == -1: continue ba = int(label[9:]) roi = urois[i] summary_wt = cwas[rois==roi].mean()
dmax = ranges.max() print 'min=%.4f; max=%.4f' % (dmin,dmax) ### ### # Neurosynth ### def run(cmd): print(cmd) os.system(cmd) prefix = "/home2/data/Projects/CWAS/results/20_cwas_iq/12_iq_surface/30_neurosynth_iq_surf_thresh" neurosynth = { hemi : io.read_scalar_data("%s_%s.nii.gz" % (prefix, hemi)) for hemi in ["lh", "rh"] } all_ns = neurosynth.values() prefix = op.join(odir, "surfs", "surf_ns_intelligence_all") ns_orig_dir = op.join(base, "neurosynth/neurosynth/intelligence_001") cmd = "./x_vol2surf.py %s/_pAgF_z.nii.gz %s/_pAgF_z_FDR_0.05.nii.gz %s" % (ns_orig_dir, ns_orig_dir, prefix) run(cmd) ns_orig = { hemi : io.read_scalar_data("%s_%s.nii.gz" % (prefix, hemi)) for hemi in ["lh", "rh"] } all_ns = ns_orig.values() prefix = "surf_ns_intelligence_fmri" ns_fmri_dir = op.join(base, "neurosynth/neurosynth/intelligence_very_relevant_fmri") cmd = "./x_vol2surf.py %s/_pAgF_z.nii.gz %s/_pAgF_z_FDR_0.05.nii.gz %s" % (ns_fmri_dir, ns_fmri_dir, prefix) run(cmd) ns_fmri = { hemi : io.read_scalar_data("%s_%s.nii.gz" % (prefix, hemi)) for hemi in ["lh", "rh"] } all_ns = ns_fmri.values()
import numpy as np from surfer import io from surfer import Brain """ Initialize the visualization. """ brain = Brain("fsaverage", "lh", "inflated", config_opts=dict(background="white")) """ Read both of the activation maps in using surfer's io functions. """ data_dir = op.join("example_data") sig1 = io.read_scalar_data(op.join(data_dir, "lh.sig.nii.gz")) sig2 = io.read_scalar_data(op.join(data_dir, "lh.alt_sig.nii.gz")) """ Zero out the vertices that do not meet a threshold. """ thresh = 4 sig1[sig1 < thresh] = 0 sig2[sig2 < thresh] = 0 """ A conjunction is defined as the minimum significance value between the two maps at each vertex. """ conjunct = np.min(np.vstack((sig1, sig2)), axis=0)
print 'getting range' ranges = np.array([get_range(sfile) for sfile in all_sfiles]) dmin = ranges.min() dmax = ranges.max() print 'min=%.4f; max=%.4f' % (dmin, dmax) ### # Read surfaces ### print "...reading surfaces" surfs = {} for measure in measures: surfs[measure] = {} for hemi in ["lh", "rh"]: tmp = io.read_scalar_data(all_surf_files[measure][hemi]) surfs[measure][hemi] = tmp ### # Plot ### print "...plotting" cbarfile = "/home2/data/Projects/CWAS/share/lib/surfwrap/colorbars/red-yellow.txt" cbar = load_colorbar(cbarfile) # Overlap for measure in measures: oprefix = op.join(odir, "surf_%s" % measure) for hemi in ["lh", "rh"]: