def main(derivatives, subject, session): all_depth_zmap_l = op.join( derivatives, 'sampled_giis', f'sub-{subject}', f'ses-{session}', 'func', f'sub-{subject}_ses-{session}_left_over_right_desc-zmap-depth-all_hemi-lh.gii' ) all_depth_zmap_r = op.join( derivatives, 'sampled_giis', f'sub-{subject}', f'ses-{session}', 'func', f'sub-{subject}_ses-{session}_left_over_right_desc-zmap-depth-all_hemi-rh.gii' ) all_depth_zmap = np.hstack((surface.load_surf_data(all_depth_zmap_l), surface.load_surf_data(all_depth_zmap_r))) abs_zmap_l = op.join( derivatives, 'sampled_giis', f'sub-{subject}', f'ses-{session}', 'func', f'sub-{subject}_ses-{session}_left_over_right_desc-abszmap-depth-all_hemi-lh_smoothed.gii' ) abs_zmap_r = op.join( derivatives, 'sampled_giis', f'sub-{subject}', f'ses-{session}', 'func', f'sub-{subject}_ses-{session}_left_over_right_desc-abszmap-depth-all_hemi-rh_smoothed.gii' ) abs_zmap = np.hstack((surface.load_surf_data(abs_zmap_l), surface.load_surf_data(abs_zmap_r))) images = {} images['all_depth_zmap'] = cortex.Vertex(all_depth_zmap, f'odc.{subject}') images['abs_zmap_smooth'] = cortex.Vertex(abs_zmap, f'odc.{subject}') ds = cortex.Dataset(**images) cortex.webshow(ds)
def minimal_plot(sub, dat, zeronan, fig, savefig, fname): if zeronan == True: dat[dat == 0] = np.nan light = cortex.Vertex(dat, subject=sub, vmin=np.nanmin(dat), vmax=np.nanmax(dat), cmap='plasma') mfig = cortex.quickshow(light, with_curvature=True, fig=fig, with_colorbar=True, with_rois=False) if savefig == True: mfig.savefig(fname, dpi=300, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format='png', transparent=False)
def get_wang2015(subject, sourcedata, probabilistic=False): if subject == 'fsaverage': fs_subject = 'fsaverage' w2015_l = surface.load_surf_data( op.join(sourcedata, 'derivatives', 'freesurfer', fs_subject, 'surf', 'lh.wang2015_atlas.mgz')) w2015_r = surface.load_surf_data( op.join(sourcedata, 'derivatives', 'freesurfer', fs_subject, 'surf', 'rh.wang2015_atlas.mgz')) else: fs_subject = f'sub-{subject}' if probabilistic: w2015_l = surface.load_surf_data( op.join(sourcedata, 'derivatives', 'freesurfer', fs_subject, 'surf', 'lh.wang15_fplbl.mgz')) w2015_r = surface.load_surf_data( op.join(sourcedata, 'derivatives', 'freesurfer', fs_subject, 'surf', 'rh.wang15_fplbl.mgz')) else: w2015_l = surface.load_surf_data( op.join(sourcedata, 'derivatives', 'freesurfer', fs_subject, 'surf', 'lh.wang15_mplbl.mgz')) w2015_r = surface.load_surf_data( op.join(sourcedata, 'derivatives', 'freesurfer', fs_subject, 'surf', 'rh.wang15_mplbl.mgz')) if probabilistic: w2015 = np.concatenate((w2015_l, w2015_r), 1) else: w2015 = np.concatenate((w2015_l, w2015_r), 0) return cortex.Vertex(w2015, fs_subject)
def main(subject, derivatives, desc='test2', pc_subject=None): if pc_subject is None: pc_subject = 'odc.{}'.format(subject) pars_grid = np.load( op.join(derivatives, 'prf', 'vertices', 'sub-{subject}_desc-{desc}_prf_grid.npz').format(**locals())) pars_optim = np.load( op.join(derivatives, 'prf', 'vertices', 'sub-{subject}_desc-{desc}_prf_optim.npz').format(**locals())) images = {} r2_grid = pars_grid['r2'] r2_optim = pars_optim['r2'] angle_grid = pars_grid['angle'] angle_optim = pars_optim['angle'] ecc_grid = pars_grid['ecc'] ecc_optim = pars_optim['ecc'] size_grid = pars_grid['size'] size_optim = pars_optim['size'] images['r2_grid'] = cortex.Vertex(r2_grid, pc_subject, vmin=0, vmax=0.65) images['r2_optim'] = cortex.Vertex(r2_optim, pc_subject, vmin=0, vmax=0.65) images['angle_grid'] = cortex.Vertex(angle_grid, pc_subject, cmap='hsv', vmin=-3.14, vmax=3.14) images['angle_optim'] = cortex.Vertex(angle_optim, pc_subject, cmap='hsv', vmin=-3.14, vmax=3.14) images['ecc_grid'] = cortex.Vertex(ecc_grid, pc_subject, vmin=0, vmax=12) images['ecc_optim'] = cortex.Vertex(ecc_optim, pc_subject, vmin=0, vmax=12) images['size_grid'] = cortex.Vertex(size_grid, pc_subject, vmin=0, vmax=12) images['size_optim'] = cortex.Vertex(size_optim, pc_subject, vmin=0, vmax=12) ds = cortex.Dataset(**images) cortex.webshow(ds)
def get_wang15_ips(subject, sourcedata): if subject == 'fsaverage': fs_subject = subject else: fs_subject = f'sub-{subject}' fn = op.join(sourcedata, 'derivatives', 'freesurfer', fs_subject, 'surf', '{hemi}.wang15_ips.mgz') surfs = [ surface.load_surf_data(fn.format(hemi=hemi)) for hemi in ['lh', 'rh'] ] surfs = np.concatenate(surfs) return cortex.Vertex(surfs, fs_subject)
with_sulci=True) # plot different body areas # but first threshold them (only show positive z-scores) data_threshed_face = zthresh(face_contrast, threshold=z_threshold, side='above') data_threshed_hand = zthresh(hand_contrast, threshold=z_threshold, side='above') data_threshed_leg = zthresh(leg_contrast, threshold=z_threshold, side='above') # vertex for face vs all others images['v_face'] = cortex.Vertex(data_threshed_face.T, 'fsaverage', vmin=0, vmax=7, cmap='Blues') #cortex.quickshow(images['v_face'],with_curvature=True,with_sulci=True,with_colorbar=True) filename = os.path.join( figure_out, 'flatmap_space-fsaverage_rsq-%0.2f_zscore-%.2f_type-face-vs-all.svg' % (rsq_threshold, z_threshold)) print('saving %s' % filename) _ = cortex.quickflat.make_png(filename, images['v_face'], recache=False, with_colorbar=True, with_curvature=True, with_sulci=True)
np.random.seed(1234) import matplotlib.pyplot as plt subject = 'S1' # In order to get the number of vertices in this subject's cortical surface # we have to load in their surfaces and get the number of points in each surfs = [cortex.polyutils.Surface(*d) for d in cortex.db.get_surf(subject, "fiducial")] # This is the total number of vertices in both hemispheres combined num_verts = surfs[0].pts.shape[0] + surfs[1].pts.shape[0] # Creating a random dataset with one entry for each vertex test_data = np.random.randn(num_verts) # This creates a Vertex object for our subject and test dataset vertex_data = cortex.Vertex(test_data, subject) # And now we can display it on a flatmap cortex.quickshow(vertex_data) plt.show() # We can also plot just the left hemisphere data numl = surfs[0].pts.shape[0] # This creates a Vertex object with an array only as long as the number of # vertices in the left hemisphere, and the right hemisphere will be filled # in with zeros vertex_data_left = cortex.Vertex(test_data[:numl], subject) cortex.quickshow(vertex_data_left) plt.show()
def _load_parameters(subject, session, par, space='fsnative', smoothed=False, concatenated=False, pca_confounds=False, alpha=None, split_certainty=False, volume=False, sourcedata='/data/ds-risk', cmap='nipy_spectral', vmin=None, vmax=None, threshold=None, stimulus=None, **kwargs): d_name = 'encoding_model' if smoothed: d_name += '.smoothed' if pca_confounds: d_name += '.pca_confounds' if concatenated: d_name += '.concatenated' if split_certainty: d_name += '.split_certainty' dir_ = op.join(sourcedata, 'derivatives', d_name, f'sub-{subject}', f'ses-{session}', 'func') print(dir_) if volume: if stimulus is None: par = op.join( sourcedata, 'derivatives', 'encoding_model', f'sub-{subject}', f'ses-{session}', 'func', f'sub-{subject}_ses-{session}_desc-{par}.optim_space-T1w_pars.nii.gz' ) else: par = op.join( sourcedata, 'derivatives', 'encoding_model', f'sub-{subject}', f'ses-{session}', 'func', f'sub-{subject}_ses-{session}_stim-{stimulus}_desc-{par}.optim_space-T1w_pars.nii.gz' ) if op.exists(par): par = image.load_img(par) transform = cortex.xfm.Transform(np.identity(4), par) transform.save(f'sub-{subject}', f'bold.{session}') # vmin, vmax = 1, 4. data = par.get_data() if vmin is None: vmin = np.quantile(data, .05) if vmax is None: vmax = np.quantile(data, .95) if threshold is not None: alpha = (data > threshold).T.astype(np.float32) data = np.clip((data - vmin) / (vmax - vmin), 0., .99) rgb = getattr(cm, cmap)(data.T, )[..., :3] red, green, blue = rgb[..., 0], rgb[..., 1], rgb[..., 2] return cortex.VolumeRGB(red, green, blue, f'sub-{subject}', f'bold.{session}', alpha=alpha) else: print(f'{par} does not exist') return None else: par_l = op.join( dir_, f'sub-{subject}_ses-{session}_desc-{par}.optim_space-{space}_hemi-L.func.gii' ) par_r = op.join( dir_, f'sub-{subject}_ses-{session}_desc-{par}.optim_space-{space}_hemi-R.func.gii' ) if op.exists(par_l): par_l = surface.load_surf_data(par_l).T par_r = surface.load_surf_data(par_r).T par = np.concatenate((par_l, par_r)) if space == 'fsnative': fs_subject = f'sub-{subject}' else: fs_subject = space if alpha is None: return cortex.Vertex(par, fs_subject, **kwargs) else: get_alpha_vertex(par, alpha, subject=fs_subject, cmap=cmap, **kwargs) else: return None
alpha, cmap='hot', subject=subject, vmin=0.0, vmax=0.4, standard_space=True) d[f'mu_{subject}.{session}_volsurf'] = get_alpha_vertex( mu.data, alpha, cmap='nipy_spectral', subject=subject, vmin=np.log(5), vmax=np.log(28), standard_space=True) com = surface.load_surf_data( op.join(bids_folder, 'derivatives', 'npc_com', f'sub-{subject}_space-fsaverage_desc-npcr_com.gii')) com = np.concatenate((np.zeros_like(com), com)) d[f'com_npcr_{subject}.{session}_volsurf'] = cortex.Vertex(com, 'fsaverage', vmin=.5, vmax=1.0) ds = cortex.Dataset(**d) cortex.webshow(ds)
# hemisphere based on vertex number test1 = np.hstack((np.arange(num_verts[0]), np.arange(num_verts[1]))) # Picking a different vertex in each hemisphere to create another fake # gradient away from that vertex second_verts = [n / 4 for n in num_verts] test2 = np.hstack((np.abs(np.arange(num_verts[0]) - second_verts[0]), np.abs(np.arange(num_verts[1]) - second_verts[1]))) # Creating a third dataset that is random stripes third_verts = np.random.randint(num_verts[0] + num_verts[1], size=(20, )) test3 = np.zeros(num_verts[0] + num_verts[1]) for v in third_verts: test3[v - 1000:v + 1000] = 1 # Scaling the three datasets to be between 0-255 test1_scaled = test1 / np.max(test1) * 255 test2_scaled = test2 / np.max(test2) * 255 test3_scaled = test3 / np.max(test3) * 255 # Creating three cortex.Volume objects with the test data as np.uint8 red = cortex.Vertex(test1_scaled, subject) green = cortex.Vertex(test2_scaled, subject) blue = cortex.Vertex(test3_scaled, subject) # This creates a 2D Vertex object with both of our test datasets for the # given subject vertex_data = cortex.VertexRGB(red, green, blue, subject) cortex.quickshow(vertex_data, with_colorbar=False) plt.show()
from bids import BIDSLayout from nilearn import image derivatives = '/data/odc/derivatives' subject = '06' pc_subject = 'odc.{}'.format(subject) session = 'odc' left, right = cortex.db.get_surf('odc.{}'.format(subject), 'fiducial') left_surface = cortex.polyutils.Surface(left[0], left[1]) right_surface = cortex.polyutils.Surface(right[0], right[1]) example_gabors = op.join( derivatives, 'zmap_spatfreq', 'sub-{subject}', 'ses-{session}', 'func', 'sub-{subject}_ses-{session}_dynamicbw_example_gabors.pkl').format( subject=subject, session=session) example_gabors = pd.read_pickle(example_gabors) mask = np.zeros(len(left_surface.pts)) mask[example_gabors.columns] = True ss = left_surface.create_subsurface(mask.astype(bool)) example_gabors = ss.lift_subsurface_data(example_gabors.values) v_example_gabors = cortex.Vertex(example_gabors, pc_subject, vmin=-0.1, vmax=0.1, cmap='BuBkRd') cortex.webshow(v_example_gabors)
median_tsnr_right = sorted(glob('../../outputs/datapaper/tsnr/sub-*/*median*hemi-R*npy')) assert len(median_tsnr_left) == 25 assert len(median_tsnr_right) == 25 median_tsnr_both = [] for left, right in zip(median_tsnr_left, median_tsnr_right): median_tsnr_both.append(np.hstack((np.load(left), np.load(right)))) median_tsnr_across_subjects = np.median(median_tsnr_both, 0) # set medial wall values to nan median_wall = median_tsnr_across_subjects == 0. median_tsnr_across_subjects[median_wall] = np.nan surface = cortex.Vertex(median_tsnr_across_subjects, 'fsaverage', vmin=0, vmax=180, cmap='hot'); params = cortex.export.params_inflated_lateral_medial_ventral windowsize = (1600*2, 900*2) viewer_params = dict( labels_visible=[], overlays_visible=[] ) fig = cortex.export.plot_panels(surface, windowsize=windowsize, viewer_params=viewer_params, **params) fig.savefig('../../outputs/datapaper/tsnr/figures/group_inflated_median-tsnr-fsaverage-hotcmap.png', dpi=300) fig = cortex.quickflat.make_figure(surface, with_rois=False, with_curvature=True, colorbar_location='right', height=2048) fig.savefig('../../outputs/datapaper/tsnr/figures/group_flatmap_median-tsnr-fsaverage-hotcmap.png', dpi=300)
def main(pars, make_svg, derivatives, old=False, recache=False, pc_subject=None): if pc_subject is None: reg = re.compile('.*/sub-(?P<subject>[a-z0-9]+)_.*') subject = reg.match(pars).group(1) pc_subject = 'odc.{}'.format(subject) if old: pc_subject += '.old' #mean_epi = '{derivatives}/spynoza/ses-prffunc/sub-subject/.nii.gz'.format(**locals()) prf_pars = np.load(pars) images = {} r2 = prf_pars['r2'] mask = r2 < 0.05 angle = prf_pars['angle'] #angle[mask] = np.nan ecc = prf_pars['ecc'] ecc[mask] = np.nan size = prf_pars['size'] size[mask] = np.nan images['ecc'] = cortex.Vertex(ecc, pc_subject, vmin=0, vmax=15) r2_max = np.max(r2) r2_max = 0.3 r2_min = 0.15 hsv_angle = np.ones((len(r2), 3)) hsv_angle[:, 0] = angle hsv_angle[:, 1] = np.clip(r2 / r2_max * 2, 0, 1) hsv_angle[:, 2] = r2 > r2_min left_index = cortex.db.get_surfinfo(pc_subject).left.shape[0] angle_ = hsv_angle[:left_index, 0] hsv_angle[:left_index, 0] = np.clip( ((angle_ + np.pi) - 0.25 * np.pi) / (1.5 * np.pi), 0, 1) angle_ = -hsv_angle[left_index:, 0].copy() angle_[hsv_angle[left_index:, 0] > 0] += 2 * np.pi angle_ = np.clip((angle_ - 0.25 * np.pi) / 1.5 / np.pi, 0, 1) hsv_angle[left_index:, 0] = angle_ rgb_angle = colors.hsv_to_rgb(hsv_angle) #alpha_angle = np.clip(r2 / r2_max * 2, r2_min/r2_max, 1) #alpha_angle[alpha_angle < r2_min/r2_max] = 0 alpha_angle = hsv_angle[:, 2] images['angle'] = cortex.VertexRGB( rgb_angle[:, 0], rgb_angle[:, 1], rgb_angle[:, 2], #alpha=np.ones(len(rgb_angle)), alpha=alpha_angle, subject=pc_subject) images['angle_1d'] = cortex.Vertex(angle, pc_subject, vmin=-3.14, vmax=3.14, cmap='hsv') images['r2'] = cortex.Vertex(r2, pc_subject, vmin=0, vmax=r2_max) #images['ecc'] = cortex.Vertex2D(ecc/15, r2/r2_max, cmap='BuBkRd_alpha_2D', subject=pc_subject, vmin=.15, vmax=1) v1_ix, v1_values = cortex.freesurfer.get_label(pc_subject, 'V1_exvivo', 'sub-{}'.format(subject), fs_dir=op.join( derivatives, 'freesurfer')) vt_v1 = np.zeros_like(r2) vt_v1[v1_ix] = v1_values images['fs_v1'] = cortex.Vertex(vt_v1, pc_subject) v2_ix, v2_values = cortex.freesurfer.get_label(pc_subject, 'V2_exvivo', 'sub-{}'.format(subject), fs_dir=op.join( derivatives, 'freesurfer')) vt_v2 = np.zeros_like(r2) vt_v2[v2_ix] = v2_values images['fs_v2'] = cortex.Vertex(vt_v2, pc_subject) layout = BIDSLayout(op.join(derivatives, 'tsnr'), validate=False) veins = layout.get(subject=subject, session='prf', suffix='invtsnr', return_type='file') if len(veins) > 0: veins = image.mean_img(veins) t1w = cortex.db.get_anat(pc_subject, 'raw') veins = image.resample_to_img(veins, t1w) images['veins'] = cortex.Volume(veins.get_data().T, subject=pc_subject, xfmname='identity', vmin=0, vmax=2) if make_svg: cortex.utils.add_roi(data=images['angle'], name='prf_angle', open_inkscape=False) cortex.utils.add_roi(data=images['angle_1d'], name='prf_angle_1d', open_inkscape=False) cortex.utils.add_roi(data=images['ecc'], name='prf_ecc', open_inkscape=False) cortex.utils.add_roi(data=images['fs_v1'], name='Freesurfer V1', open_inkscape=False) cortex.utils.add_roi(data=images['fs_v2'], name='Freesurfer V2', open_inkscape=False) else: ds = cortex.Dataset(**images) cortex.webshow(ds, recache=recache)
import numpy as np import os.path as op import cortex from nilearn import surface folder = 'encoding_model' sourcedata = '/data/ds-risk' par = 'r2' session = '3t2' r2_l = surface.load_surf_data( op.join(sourcedata, 'derivatives', folder, f'group_ses-{session}_desc-{par}.volume_hemi-L_mean.gii')) r2_r = surface.load_surf_data( op.join(sourcedata, 'derivatives', folder, f'group_ses-{session}_desc-{par}.volume_hemi-R_mean.gii')) r2 = np.concatenate((r2_l, r2_r)) r2[r2 < 0.025] = np.nan r2 = cortex.Vertex(r2, 'fsaverage', cmap='hot', vmin=0.0, vmax=.05) cortex.utils.add_roi(r2, 'r2_3t2_group', open_inkscape=True)
def main(derivatives, subject, session): pc_subject = 'odc.{}'.format(subject) left, right = cortex.db.get_surf('odc.{}'.format(subject), 'fiducial') left_surface = cortex.polyutils.Surface(left[0], left[1]) right_surface = cortex.polyutils.Surface(right[0], right[1]) max_wavelengths = {} max_orientations = {} zmaps = {} for hemi, surf in zip(['lh', 'rh'], [left_surface, right_surface]): energies = op.join( derivatives, 'zmap_spatfreq', 'sub-{subject}', 'ses-{session}', 'func', 'sub-{subject}_ses-{session}_hemi-{hemi}_energies.pkl').format( subject=subject, session=session, hemi=hemi) xy = pd.read_pickle( op.join(derivatives, 'coordinate_patches', 'sub-{subject}', 'anat', 'sub-{subject}_hemi-{hemi}_coordinatepatch.pkl').format( **locals())) energies = pd.read_pickle(energies) energies = energies.loc[:, ~energies.isnull().any(0)] max_frequency = energies.groupby(['depth', 'frequency']).sum().groupby( 'depth', as_index=True).apply( lambda d: d.reset_index('depth', drop=True).idxmax()) max_wavelengths[hemi] = 1. / max_frequency max_orientations[hemi] = [] zmaps[hemi] = [] for depth, d in energies.groupby('depth'): tmp = d.loc[(depth, max_frequency.loc[depth]), :].idxmax() tmp = tmp.apply(lambda x: x[2] if not x is np.nan else None) tmp = pd.DataFrame(tmp, columns=pd.Index([depth], name='depth')).T tmp.columns = energies.columns max_orientations[hemi].append(tmp) zmap = op.join(derivatives, 'sampled_giis', 'sub-{subject}', 'ses-{session}', 'func', 'sub-{subject}_ses-{session}_left_over_right_desc-zmap-depth-{depth}_hemi-{hemi}.gii'). \ format(**locals()) zmaps[hemi].append(surface.load_surf_data(zmap)) zmaps[hemi] = np.array(zmaps[hemi]) max_orientations[hemi] = pd.concat(max_orientations[hemi]) ss = pd.DataFrame([], columns=np.arange(surf.pts.shape[0])) max_wavelengths[hemi] = pd.concat((ss, max_wavelengths[hemi])).values max_orientations[hemi] = pd.concat((ss, max_orientations[hemi])).values print(max_wavelengths['lh'].shape, max_wavelengths['rh'].shape) max_wavelengths = np.concatenate( [max_wavelengths['lh'], max_wavelengths['rh']], axis=-1) max_orientations = np.concatenate( [max_orientations['lh'], max_orientations['rh']], axis=-1) print(zmaps['lh'].shape, zmaps['rh'].shape) zmaps = np.concatenate([zmaps['lh'], zmaps['rh']], axis=-1) images = {} images['wavelength'] = cortex.Vertex(max_wavelengths, 'odc.{}'.format(subject), vmin=0, vmax=10) images['orientation'] = cortex.Vertex(max_orientations, 'odc.{}'.format(subject), vmin=0, vmax=np.pi, cmap='hsv') images['zmap'] = cortex.Vertex(zmaps, 'odc.{}'.format(subject), vmin=-3, vmax=3) layout = BIDSLayout(op.join(derivatives, 'tsnr'), validate=False) veins = layout.get(subject=subject, session=session, suffix='invtsnr', extension='nii.gz', return_type='file') veins = image.mean_img(veins) t1w = cortex.db.get_anat(pc_subject, 'raw') veins = image.resample_to_img(veins, t1w) images['veins'] = cortex.Volume(veins.get_data().T, subject=pc_subject, xfmname='identity', vmin=0, vmax=2) zmap = '{derivatives}/modelfitting/glm7/sub-{subject}/ses-{session}/func/sub-{subject}_ses-{session}_left_over_right_zmap.nii.gz'.format( **locals()) t1w = get_bids_file(derivatives, 'averaged_mp2rages', 'anat', subject, 'T1w', 'anat', 'average') zmap = image.resample_to_img(zmap, t1w) transform = cortex.xfm.Transform(np.identity(4), t1w) if not np.in1d(subject, ['01', '06']): transform.save(pc_subject, 'identity.t1w', 'magnet') mask = image.math_img('np.abs(zmap)', zmap=zmap) zmap = zmap.get_data().T zmap[zmap == 0] = np.nan mask = mask.get_data().T images['zmap'] = cortex.Volume2D(zmap, mask, pc_subject, 'identity.t1w', vmin=-3, vmax=3, vmin2=0, vmax2=3, cmap='BuBkRd_alpha_2D') ds = cortex.Dataset(**images) cortex.webshow(ds)
lsurf, rsurf = [Surface(*d) for d in cortex.db.get_surf(subject, "fiducial")] # Let's choose a few points and generate data for them selected_pts = np.arange(len(lsurf.pts), step=5000) num_selected_pts = len(selected_pts) sparse_data = np.random.randn(num_selected_pts) # Then interpolate interp_data = lsurf.interp(selected_pts, sparse_data) # Plot the result # interp_data is only for the left hemisphere, but the Vertex constructor # infers that and fills the right hemisphere with zeros interp_vertex = cortex.Vertex(interp_data[:, 0], subject, vmin=-2, vmax=2, cmap='RdBu_r') cortex.quickshow(interp_vertex, with_labels=False, with_rois=False) # plot the locations of the points we selected originally # nudge=True puts both left and right hemispheres in the same space, moving them # so that they don't overlap. These are the coordinates used in quickflat (lflatpts, lpolys), (rflatpts, rpolys) = cortex.db.get_surf(subject, "flat", nudge=True) ax = plt.gca() # zorder is set to 10 to make sure points go on top of other quickflat layers ax.scatter(lflatpts[selected_pts, 0],
import glob subject = 4 sourcedata = '/data/risk_precision/ds-numrisk' derivatives = op.join(sourcedata, 'derivatives') log_r2_l = glob.glob( op.join(derivatives, 'modelfit_surf_smoothed', f'sub-*', 'func', f'sub-*_space-fsaverage_desc-r2_hemi-L.func.gii')) log_r2_l = np.mean([surface.load_surf_data(fn) for fn in log_r2_l], 0) log_r2_r = glob.glob( op.join(derivatives, 'modelfit_surf_smoothed', f'sub-*', 'func', f'sub-*_space-fsaverage_desc-r2_hemi-R.func.gii')) log_r2_r = np.mean([surface.load_surf_data(fn) for fn in log_r2_r], 0) log_r2 = cortex.Vertex(np.hstack((log_r2_l, log_r2_r)), 'fsaverage') nat_r2_l = glob.glob( op.join(derivatives, 'modelfit_surf_smoothed_natural_space', f'sub-*', 'func', f'sub-*_space-fsaverage_desc-r2_hemi-L.func.gii')) nat_r2_l = np.mean([surface.load_surf_data(fn) for fn in nat_r2_l], 0) nat_r2_r = glob.glob( op.join(derivatives, 'modelfit_surf_smoothed_natural_space', f'sub-*', 'func', f'sub-*_space-fsaverage_desc-r2_hemi-R.func.gii')) nat_r2_r = np.mean([surface.load_surf_data(fn) for fn in nat_r2_r], 0) nat_r2 = cortex.Vertex(np.hstack((nat_r2_l, nat_r2_r)), 'fsaverage') diff_r2 = cortex.Vertex(log_r2.data - nat_r2.data, 'fsaverage') ds = cortex.Dataset(log_r2=log_r2, nat_r2=nat_r2, diff_r2=diff_r2)
import os.path as op from nilearn import surface import numpy as np import glob from matplotlib import colors, cm derivatives = '/data/risk_precision/ds-numrisk/derivatives' r2s_l = op.join(derivatives, 'modelfit_surf_smoothed', f'sub-*', 'func', f'sub-*_space-fsaverage_desc-r2_hemi-L.func.gii') r2s_r = r2s_l.replace('hemi-L', 'hemi-R') r2s_l = [surface.load_surf_data(fn) for fn in sorted(glob.glob(r2s_l))] r2s_r = [surface.load_surf_data(fn) for fn in sorted(glob.glob(r2s_r))] r2s = np.hstack((r2s_l, r2s_r)) r2s_v = cortex.Vertex(r2s, 'fsaverage') r2s_mean_v = cortex.Vertex(np.nanmean(r2s, 0), 'fsaverage') pars_l = op.join(derivatives, 'modelfit_surf_smoothed', f'sub-*', 'func', f'sub-*_space-fsaverage_desc-pars_hemi-L.func.gii') print(glob.glob(pars_l)) pars_r = pars_l.replace('hemi-L', 'hemi-R') pars_r = pars_l.replace('hemi-L', 'hemi-R') pars_l = [surface.load_surf_data(fn) for fn in sorted(glob.glob(pars_l))] pars_r = [surface.load_surf_data(fn) for fn in sorted(glob.glob(pars_r))] pars = np.hstack((pars_l, pars_r)) weighted_pars = (r2s[..., np.newaxis] * pars).sum(0) / \ r2s.sum(0)[:, np.newaxis]
plt.figure(figsize=(6, 20)) for i, subject_session in enumerate(subjects_sessions): subject, session = subject_session.split('_') write_dir = pjoin(DERIVATIVES, subject, session, 'res_fsaverage7_retinotopy_ffx', 'stat_maps') for j, stat in enumerate(['phase_wedge', 'phase_ring']): lh = os.path.join(write_dir, '%s_lh.gii' % stat) rh = os.path.join(write_dir, '%s_rh.gii' % stat) output_file = os.path.join(write_dir, '%s.png' % stat) x1 = np.ravel([darrays.data for darrays in load(lh).darrays]) x2 = np.ravel([darrays.data for darrays in load(rh).darrays]) x = np.hstack((x1, x2)) x[x == 0] = np.nan vertex_data = cortex.Vertex(x, 'fsaverage') ax = plt.subplot(12, 2, i * 2 + j + 1) fig = cortex.quickshow(vertex_data, with_colorbar=False, with_rois=False, with_labels=False, with_curvature=True, curvature_contrast=0.5, curvature_brightness=0.5, curvature_threshold=True, fig=ax) #fig.set_size_inches((8, 4.5)) #fig.savefig(output_file) # ax = plt.axes([.46, .96 - i * 1. * .0815, .08, .04]) ax.text(.01, .2, subject)
zmap = image.resample_img(zmap, zmap.affine, new_shape, fill_value=np.nan) zmap.to_filename('/tmp/zmap.nii.gz') transform = cortex.xfm.Transform(np.identity(4), zmap.get_filename()) transform.save(pc_subject, 'identity.zmap.extended') mask = image.math_img('np.abs(zmap)', zmap=zmap) mask = mask.get_data().T zmap_vox = cortex.Volume2D(zmap.get_data().T, mask, pc_subject, 'identity.zmap.extended', vmin=-3.5, vmax=3.5, vmin2=0, vmax2=3, cmap='BuBkRd_alpha_2D') cds_vox = cortex.Volume(coordinates, pc_subject, 'identity.zmap.extended') curvature_v = cortex.db.get_surfinfo(pc_subject) random_data = np.random.rand(*curvature_v.data.shape) random_data_v = cortex.Vertex(random_data, pc_subject) ds = cortex.Dataset(zmap=zmap_vox, voxels=cds_vox, curvature=curvature_v, random_data=random_data_v) cortex.webshow(ds)
'flatmap_space-fsaverage_rsq-%0.2f_type-rsquared.svg' % rsq_threshold) print('saving %s' % filename) _ = cortex.quickflat.make_png(filename, images['rsq'], recache=True, with_colorbar=True, with_curvature=True, with_sulci=True) # vertex for ecc ecc4plot = masked_eccentricity.copy() ecc4plot[alpha_mask] = np.nan images['ecc'] = cortex.Vertex(ecc4plot.T, 'fsaverage_gross', vmin=0, vmax=analysis_params['max_eccen'], cmap='J4') #cortex.quickshow(images['ecc'],with_curvature=True,with_sulci=True) # Save this flatmap filename = os.path.join( figure_out, 'flatmap_space-fsaverage_rsq-%0.2f_type-eccentricity.svg' % rsq_threshold) print('saving %s' % filename) _ = cortex.quickflat.make_png(filename, images['ecc'], recache=True, with_colorbar=True, with_curvature=True, with_sulci=True)
import numpy as np import matplotlib.pyplot as plt subject = "S1" # First we need to import the surfaces for this subject surfs = [cortex.polyutils.Surface(*d) for d in cortex.db.get_surf(subject, "fiducial")] # Then we will pick one vertex in each hemisphere to find distances to vert = 10000 dists = [s.geodesic_distance(vert) for s in surfs] # Now we can plot these distances onto a flatmap all_dists = np.hstack((dists[0], dists[1])) dist_map = cortex.Vertex(all_dists, subject, cmap="hot") cortex.quickshow(dist_map) plt.show() # Alternatively, you can find the minimum distance from a set of points to the # surface # Here, we use an example of an ROI all_eba = cortex.utils.get_roi_verts(subject, "EBA")["EBA"] # We have to then separate these vertices by hemisphere numl = surfs[0].pts.shape[0] eba_verts = [all_eba[all_eba < numl], all_eba[all_eba >= numl] - numl] # Now look at geodesic distances for each hemisphere separately dists = [s.geodesic_distance(verts) for s, verts in zip(surfs, eba_verts)] all_dists = np.hstack((dists[0], dists[1]))
import matplotlib matplotlib.use('Agg') import cortex import cortex.rois import nibabel as nib import os # load glasser atlas lh_aparc_file = os.path.join('atlases', 'lh.HCP-MMP1.annot') rh_aparc_file = os.path.join('atlases', 'rh.HCP-MMP1.annot') lpinds, lpstats, lpnames = nib.freesurfer.read_annot(lh_aparc_file) lpinds_orig, lpstats, lpnames = nib.freesurfer.read_annot(lh_aparc_file, True) lpinds[lpinds_orig == 0] = -1 rpinds, rpstats, rpnames = nib.freesurfer.read_annot(rh_aparc_file) rpinds_orig, rpstats, rpnames = nib.freesurfer.read_annot(rh_aparc_file, True) rpinds[rpinds_orig == 0] = -1 # create roipack object roipack = cortex.rois.ROIpack('fsaverage_pycortex', 'blah') # create vertexdata for an roi vd = cortex.Vertex(lpinds == 12, 'fsaverage_pycortex') # jam it into the roipack roipack.rois['test'] = vd # save the dang thing out as an svg file roipack.to_svg(filename='test.svg')
def test_vertexdata_copy(): vd = cortex.Vertex(np.random.randn(nverts), subj) vdcopy = vd.copy(vd.data) assert np.allclose(vd.data, vdcopy.data)
axis[1].set_xlabel('R',fontsize=14) axis[0].set_xlim(0,) axis[1].axvline(x=mot_quant,c='k',linestyle='--') axis[1].set_title('Histogram of normalized R values from soma fit') fig.savefig(os.path.join(figure_out,'histogram_combined_R_normalized_%.2f-quantile.svg'%quantile), dpi=100,bbox_inches = 'tight') # make flatmaps of the above distributions ########## print('making flatmaps') images = {} # make and save rsq flatmaps for each task images['rsq_visual_norm'] = cortex.Vertex(rsq_visual_norm,'fsaverage_gross', vmin=0, vmax=1, cmap='Reds') cortex.quickshow(images['rsq_visual_norm'],with_curvature=True,with_sulci=True) filename = os.path.join(figure_out,'flatmap_space-fsaverage_type-rsquared-normalized_visual.svg') print('saving %s' %filename) _ = cortex.quickflat.make_png(filename, images['rsq_visual_norm'], recache=False,with_colorbar=True,with_curvature=True,with_sulci=True) images['rsq_motor_norm'] = cortex.Vertex(rsq_motor_norm,'fsaverage_gross', vmin=0, vmax=1, cmap='Blues') cortex.quickshow(images['rsq_motor_norm'],with_curvature=True,with_sulci=True) filename = os.path.join(figure_out,'flatmap_space-fsaverage_type-rsquared-normalized_motor.svg') print('saving %s' %filename) _ = cortex.quickflat.make_png(filename, images['rsq_motor_norm'], recache=False,with_colorbar=True,with_curvature=True,with_sulci=True)
def test_vertexdata_index(): vd = cortex.Vertex(np.random.randn(10, nverts), subj) assert np.allclose(vd[0].data, vd.data[0])
def test_vertexdata_set(): vd = cortex.Vertex(np.random.randn(nverts), subj) newdata = np.random.randn(nverts) vd.data = newdata assert np.allclose(newdata, vd.data)
data_dir = os.path.abspath('../../outputs/fmriprep') def get_subjects(): fns = sorted(glob(os.path.join(data_dir, 'sub-*/'))) fns = [fn.split('/')[-2] for fn in fns] return fns subjects = get_subjects() data = np.load( '../../outputs/datapaper/isc/isc-correlations-all-subjects-fsaverage.npy') data_median = np.median(data, 0) # surfaces = dict() surface = cortex.Vertex(data_median, 'fsaverage', cmap='hot', vmin=0, vmax=0.5) # for subject, dt in zip(subjects, data): # surfaces[subject] = cortex.Vertex(dt, 'fsaverage', cmap='inferno', vmin=0, vmax=0.5) params = cortex.export.params_inflated_lateral_medial_ventral windowsize = (1600 * 2, 900 * 2) viewer_params = dict(labels_visible=[], overlays_visible=[]) fig = cortex.export.plot_panels(surface, windowsize=windowsize, viewer_params=viewer_params, **params) fig.savefig('../../outputs/datapaper/isc/median-isc-fsaverage-hotcmap.png', dpi=300) fig = cortex.quickflat.make_figure(surface, with_rois=False,
# First let's load the surface and compute the distortion directly using the # Distortion class # load fiducial (mid-cortical) surfaces # we're ignoring the right hemisphere surface here # the polys (triangles) are the same for the fiducial and flat surfaces _, (rfidpts, rpolys) = cortex.db.get_surf(subject, "fiducial") # load flattened surfaces _, (rflatpts, rpolys) = cortex.db.get_surf(subject, "flat") # Create the Distortion object dist = Distortion(rflatpts, rfidpts, rpolys) # Compute areal distortion # this returns an array of values for each vertex, which we will put into # a Vertex object for plotting areal_dist = cortex.Vertex(dist.areal, subject, vmin=-2, vmax=2) # areal distortion is in log_2 units (e.g. -1 is half the area, 1 is double) # Next compute metric distortion metric_dist = cortex.Vertex(dist.metric, subject, vmin=-2, vmax=2) # metric distortion is in mm (e.g. -1 means flatmap edge is 1 mm shorter) cortex.quickshow(areal_dist, with_rois=False, with_labels=False) cortex.quickshow(metric_dist, with_rois=False, with_labels=False) # these also return Vertex objects like those we created above plt.show()
def main(sourcedata, derivatives, subject, session, cache=True, dataset='odc'): if subject in []: trans_str = '_trans' else: trans_str = '' pc_subject = '{}.{}'.format(dataset, subject) zmap = '{derivatives}/modelfitting/glm7/sub-{subject}/ses-{session}/func/sub-{subject}_ses-{session}_left_over_right_zmap{trans_str}.nii.gz'.format( **locals()) #zmap2 = '{derivatives}/modelfitting/glm8/sub-{subject}/ses-{session}/func/sub-{subject}_ses-{session}_left_over_right_zmap{trans_str}.nii.gz'.format(**locals()) #zmap_task = '{derivatives}/modelfitting/glm7/sub-{subject}/ses-{session}/sub-{subject}_ses-{session}_left_over_right_task_zmap.nii.gz'.format(**locals()) if subject == '01': mean_epi = '{derivatives}/spynoza/sub-{subject}/ses-{session}/func/sub-{subject}_ses-{session}_task-checkerboard_acq-07_run-03_reference{trans_str}.nii.gz'.format( **locals()) else: mean_epi = '{derivatives}/spynoza/sub-{subject}/ses-{session}/func/sub-{subject}_ses-{session}_task-fixation_acq-07_run-03_reference{trans_str}.nii.gz'.format( **locals()) #psc = '{derivatives}/modelfitting/glm7/sub-{subject}/ses-{session}/sub-{subject}_ses-{session}_left_over_right_effect_size.nii.gz'.format(**locals()) abs_zmap_l = op.join( derivatives, 'sampled_giis', f'sub-{subject}', f'ses-{session}', 'func', f'sub-{subject}_ses-{session}_left_over_right_desc-abszmap-depth-all_hemi-lh_smoothed.gii' ) abs_zmap_r = op.join( derivatives, 'sampled_giis', f'sub-{subject}', f'ses-{session}', 'func', f'sub-{subject}_ses-{session}_left_over_right_desc-abszmap-depth-all_hemi-rh_smoothed.gii' ) images = {} if op.exists(abs_zmap_l): abs_zmap = np.hstack((surface.load_surf_data(abs_zmap_l), surface.load_surf_data(abs_zmap_r))) images['abs_zmap'] = cortex.Vertex(abs_zmap, pc_subject, vmin=.5, vmax=2.3) t1w = cortex.db.get_anat(pc_subject) zmap = image.resample_to_img(zmap, t1w) transform = cortex.xfm.Transform(np.identity(4), t1w) mask = image.math_img('np.abs(zmap)', zmap=zmap) zmap = zmap.get_data().T zmap[zmap == 0] = np.nan #zmap2 = zmap2.get_data().T #zmap2[zmap2 == 0] = np.nan mask = mask.get_data().T images['zmap'] = cortex.Volume2D(zmap, mask, pc_subject, 'identity', vmin=-3.5, vmax=3.5, vmin2=0, vmax2=3, cmap='BuBkRd_alpha_2D') #images['zmap2'] = cortex.Volume2D(zmap2, #mask, #pc_subject, #'identity.t1w', vmin=-3, vmax=3, vmin2=0, vmax2=3, #cmap='BuBkRd_alpha_2D') #images['abs_zmap'] = cortex.Volume(np.abs(zmap), #pc_subject, #'identity.t1w', vmin=-3, vmax=3, vmin2=0, vmax2=3) ##cmap='BuBkRd_alpha_2D') #zmap_task = zmap_task.get_data().T #zmap_task[zmap_task == 0] = np.nan #images['zmap_task'] = cortex.Volume2D(zmap_task, #mask, #pc_subject, #'identity.t1w', vmin=-3, vmax=3, vmin2=0, vmax2=3, #cmap='BuBkRd_alpha_2D') #images['mean_epi'] = cortex.Volume(mean_epi.get_data().T, #pc_subject, #'identity.t1w') # PRFs prf_pars = np.load( op.join(derivatives, 'prf/vertices/sub-{subject}_desc-test2_prf_optim.npz').format( **locals())) r2 = prf_pars['r2'] mask = r2 < 0.1 angle = prf_pars['angle'] #angle[mask] = np.nan ecc = prf_pars['ecc'] ecc[mask] = np.nan size = prf_pars['size'] size[mask] = np.nan r2_max = np.max(r2) r2_max = 0.3 r2_min = 0.15 hsv_angle = np.ones((len(r2), 3)) hsv_angle[:, 0] = angle hsv_angle[:, 1] = np.clip(r2 / r2_max * 2, 0, 1) hsv_angle[:, 2] = r2 > r2_min left_index = cortex.db.get_surfinfo(pc_subject).left.shape[0] angle_ = hsv_angle[:left_index, 0] hsv_angle[:left_index, 0] = np.clip( ((angle_ + np.pi) - 0.25 * np.pi) / (1.5 * np.pi), 0, 1) angle_ = -hsv_angle[left_index:, 0].copy() angle_[hsv_angle[left_index:, 0] > 0] += 2 * np.pi angle_ = np.clip((angle_ - 0.25 * np.pi) / 1.5 / np.pi, 0, 1) hsv_angle[left_index:, 0] = angle_ rgb_angle = colors.hsv_to_rgb(hsv_angle) #alpha_angle = np.clip(r2 / r2_max * 2, r2_min/r2_max, 1) #alpha_angle[alpha_angle < r2_min/r2_max] = 0 alpha_angle = hsv_angle[:, 2] images['angle'] = cortex.VertexRGB( rgb_angle[:, 0], rgb_angle[:, 1], rgb_angle[:, 2], #alpha=np.ones(len(rgb_angle)), alpha=alpha_angle, subject=pc_subject) #images['r2'] = cortex.Vertex(prf_pars['r2'], pc_subject, cmap='inferno') images['ecc'] = cortex.Vertex(ecc, pc_subject, vmin=0, vmax=15, cmap='inferno') #images['angle_1d'] = cortex.Vertex(angle, pc_subject, vmin=-3.14, vmax=3.14, cmap='hsv') #images['size'] = cortex.Vertex(size, pc_subject, vmin=0, vmax=10) # VEIN MASK layout = BIDSLayout(op.join(derivatives, 'veins_mask'), validate=False) veins = layout.get(subject=subject, session=session, suffix='veins', return_type='file') if len(veins) == 1: veins = veins[0] t1w = cortex.db.get_anat(pc_subject, 'raw') veins = image.resample_to_img(veins, t1w) veins = veins.get_data().T veins[veins == 0] = np.nan images['veins'] = cortex.Volume(veins, subject=pc_subject, xfmname='identity', vmin=0, vmax=2) veins_surf_l = op.join( derivatives, 'tsnr', f'sub-{subject}', f'ses-{session}', 'func', f'sub-{subject}_ses-{session}_desc-depth.all_hemi-lh_invtsnr.gii') veins_surf_r = op.join( derivatives, 'tsnr', f'sub-{subject}', f'ses-{session}', 'func', f'sub-{subject}_ses-{session}_desc-depth.all_hemi-rh_invtsnr.gii') veins_d = np.hstack((surface.load_surf_data(veins_surf_l), surface.load_surf_data(veins_surf_r))) veins_d[np.isinf(veins_d)] = np.nan images['veins_surf'] = cortex.Vertex(veins_d, pc_subject) ds = cortex.Dataset(**images) # cortex.webgl.make_static(outpath=op.join(derivatives, 'pycortex', subject), # data=ds) cortex.webgl.make_static(outpath=op.join(derivatives, 'pycortex', f'{subject}.{session}', 'light'), data={ 'ODCs': images['zmap'], 'PRF polar angle': images['angle'] }, anonymize=False, sampler='trilinear')