def test_int64_in_dataviewrgb(): data = np.arange(np.product(volshape)).reshape(volshape, order='C') view = cortex.VolumeRGB(data, data + 1, data + 2, subject=subj, xfmname=xfmname) cortex.quickshow(view) data = np.arange(nverts) view = cortex.VertexRGB(data, data + 1, data + 2, subject=subj) cortex.quickshow(view)
def test_dataset_save(): tf = tempfile.NamedTemporaryFile(suffix=".hdf") mrand = np.random.randn(2, *volshape) rand = np.random.randn(*volshape) ds = cortex.Dataset(test=(mrand, subj, xfmname)) ds.append(twod=cortex.Volume2D(rand, rand, subj, xfmname)) ds.append(rgb=cortex.VolumeRGB(rand, rand, rand, subj, xfmname)) ds.append(vert=cortex.Vertex.random(subj)) ds.save(tf.name) ds = cortex.load(tf.name) assert isinstance(ds.test, cortex.Volume) assert ds.test.data.shape == mrand.shape assert isinstance(ds.twod, cortex.Volume2D) assert ds.twod.dim1.data.shape == rand.shape assert ds.twod.dim2.data.shape == rand.shape assert ds.rgb.volume.shape == tuple([1] + list(volshape) + [4]) assert isinstance(ds.vert, cortex.Vertex)
# np.sqrt(rsq) #np.ones_like(rsq) # np.sqrt(rsq) hsv[..., 1] = np.ones_like(rsq) hsv[..., 2] = np.ones_like(rsq) # np.sqrt(rsq)# np.ones_like(rsq) alpha_mask = (rsq <= settings['rsq_threshold']).T alpha = rsq.T # np.sqrt(rsq).T * 3 # for graded rsq viz # alpha[alpha_mask] = 0 # alpha = np.ones(alpha.shape) alpha[alpha_mask] = 0 rgb = colors.hsv_to_rgb(hsv) # use the above calculations to create pycortex representations vrgba = cortex.VolumeRGB(red=rgb[..., 0].T, green=rgb[..., 1].T, blue=rgb[..., 2].T, subject='sub-{subject}'.format(subject=subject), alpha=alpha, xfmname='fmriprep_T1') vecc = cortex.Volume2D(eccentricity.T, rsq.T, 'sub-{subject}'.format(subject=subject), 'fmriprep_T1', vmin=0, vmax=10, vmin2=settings['rsq_threshold'], vmax2=1.0, cmap='BROYG_2D') vsize = cortex.Volume2D(size.T, rsq.T, 'sub-{subject}'.format(subject=subject), 'fmriprep_T1',
def draw_cortex_vertex(subject,xfmname,data,vmin,vmax,description,cmap='Viridis',cbar = 'discrete',cmap_steps = 255,\ alpha = None,depth = 1,thick = 1,height = 1024,sampler = 'nearest',\ with_curvature = True,with_labels = False,with_colorbar = False,\ with_borders = False,curv_brightness = 0.95,curv_contrast = 0.05,add_roi = False,\ roi_name = 'empty',col_offset = 0, zoom_roi = None, zoom_hem = None, zoom_margin = 0.0,): """ Plot brain data onto a previously saved flatmap. Parameters ---------- subject : subject id (e.g. 'sub-001') xfmname : xfm transform data : the data you would like to plot on a flatmap cmap : colormap that shoudl be used for plotting vmins : minimal values of 1D 2D colormap [0] = 1D, [1] = 2D vmaxs : minimal values of 1D/2D colormap [0] = 1D, [1] = 2D description : plot title cbar : color bar layout cmap_steps : number of colormap bins alpha : alpha map depth : Value between 0 and 1 for how deep to sample the surface for the flatmap (0 = gray/white matter boundary, 1 = pial surface) thick : Number of layers through the cortical sheet to sample. Only applies for pixelwise = True height : Height of the image to render. Automatically scales the width for the aspect of the subject's flatmap sampler : Name of sampling function used to sample underlying volume data. Options include 'trilinear', 'nearest', 'lanczos' with_curvature : Display the rois, labels, colorbar, annotated flatmap borders, or cross-hatch dropout? with_labels : Display labels? with_colorbar : Display pycortex' colorbar? with_borders : Display borders? curv_brightness : Mean brightness of background. 0 = black, 1 = white, intermediate values are corresponding grayscale values. curv_contrast : Contrast of curvature. 1 = maximal contrast (black/white), 0 = no contrast (solid color for curvature equal to curvature_brightness). add_roi : add roi -image- to overlay.svg roi_name : roi name col_offset : colormap offset between 0 and 1 zoom_roi : name of the roi on which to zoom on zoom_hem : hemifield fo the roi zoom zoom_margin : margin in mm around the zoom Returns ------- vertex_rgb - pycortex vertex file """ import cortex import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors from matplotlib import cm import matplotlib as mpl # import ipdb # deb = ipdb.set_trace # define colormap base = cortex.utils.get_cmap(cmap) val = np.linspace(0, 1,cmap_steps+1,endpoint=False) colmap = colors.LinearSegmentedColormap.from_list('my_colmap',base(val), N = cmap_steps) # convert data to RGB vrange = float(vmax) - float(vmin) norm_data = ((data-float(vmin))/vrange)*cmap_steps mat = colmap(norm_data.astype(int))*255.0 alpha = alpha*255.0 # define volume RGB volume = cortex.VolumeRGB( channel1 = mat[...,0].T.astype(np.uint8), channel2 = mat[...,1].T.astype(np.uint8), channel3 = mat[...,2].T.astype(np.uint8), alpha = alpha.T.astype(np.uint8), subject = subject, xfmname = xfmname) volume_fig = cortex.quickshow( braindata = volume, depth = depth, thick = thick, height = height, sampler = sampler, with_curvature = with_curvature, with_labels = with_labels, with_colorbar = with_colorbar, with_borders = with_borders, curvature_brightness = curv_brightness, curvature_contrast = curv_contrast) if cbar == 'polar': base = cortex.utils.get_cmap(cmap) val = np.arange(1,cmap_steps+1)/cmap_steps - (1/(cmap_steps*2)) val = np.fmod(val+col_offset,1) colmap = colors.LinearSegmentedColormap.from_list('my_colmap',base(val),N = cmap_steps) cbar_axis = volume_fig.add_axes([0.5, 0.07, 0.8, 0.2], projection='polar') norm = colors.Normalize(0, 2*np.pi) t = np.linspace(0,2*np.pi,200,endpoint=True) r = [0,1] rg, tg = np.meshgrid(r,t) im = cbar_axis.pcolormesh(t, r, tg.T,norm= norm, cmap = colmap) cbar_axis.set_yticklabels([]) cbar_axis.set_xticklabels([]) cbar_axis.set_theta_zero_location("W") cbar_axis.spines['polar'].set_visible(False) elif cbar == 'ecc': # Ecc color bar colorbar_location = [0.5, 0.07, 0.8, 0.2] n = 200 cbar_axis = volume_fig.add_axes(colorbar_location, projection='polar') t = np.linspace(0,2*np.pi, n) r = np.linspace(0,1, n) rg, tg = np.meshgrid(r,t) c = tg im = cbar_axis.pcolormesh(t, r, c, norm = mpl.colors.Normalize(0, 2*np.pi), cmap = colmap) cbar_axis.tick_params(pad = 1,labelsize = 15) cbar_axis.spines['polar'].set_visible(False) # superimpose new axis for dva labeling box = cbar_axis.get_position() cbar_axis.set_yticklabels([]) cbar_axis.set_xticklabels([]) axl = volume_fig.add_axes( [1.8*box.xmin, 0.5*(box.ymin+box.ymax), box.width/600, box.height*0.5]) axl.spines['top'].set_visible(False) axl.spines['right'].set_visible(False) axl.spines['bottom'].set_visible(False) axl.yaxis.set_ticks_position('right') axl.xaxis.set_ticks_position('none') axl.set_xticklabels([]) axl.set_yticklabels(np.linspace(vmin,vmax,3),size = 'x-large') axl.set_ylabel('$dva$\t\t', rotation = 0, size = 'x-large') axl.yaxis.set_label_coords(box.xmax+30,0.4) axl.patch.set_alpha(0.5) elif cbar == 'discrete': # Discrete color bars # ------------------- colorbar_location= [0.9, 0.05, 0.03, 0.25] cmaplist = [colmap(i) for i in range(colmap.N)] # define the bins and normalize bounds = np.linspace(vmin, vmax, cmap_steps + 1) bounds_label = np.linspace(vmin, vmax, 3) norm = mpl.colors.BoundaryNorm(bounds, colmap.N) cbar_axis = volume_fig.add_axes(colorbar_location) cb = mpl.colorbar.ColorbarBase(cbar_axis,cmap = colmap,norm = norm,ticks = bounds_label,boundaries = bounds) # add to overalt if add_roi == True: cortex.utils.add_roi( data = volume, name = roi_name, open_inkscape = False, add_path = False, depth = depth, thick = thick, sampler = sampler, with_curvature = with_curvature, with_colorbar = with_colorbar, with_borders = with_borders, curvature_brightness = curv_brightness, curvature_contrast = curv_contrast) return volume
subject = "S1" xfm = "fullhead" # Creating three test datasets that are the same shape as this transform with # one entry for this voxel # The first two are gradients going in different directions across the brain # and the third is stripes across certain slices of the brain test1 = np.arange(31. * 100 * 100).reshape((31, 100, 100), order='C') test2 = np.arange(31. * 100 * 100).reshape((31, 100, 100), order='F') test3 = np.zeros((31, 100, 100)) test3[::3, :, :] = 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.Volume(test1_scaled.astype(np.uint8), 'S1', 'fullhead') green = cortex.Volume(test2_scaled.astype(np.uint8), 'S1', 'fullhead') blue = cortex.Volume(test3_scaled.astype(np.uint8), 'S1', 'fullhead') # This creates an RGB Volume from the three different color channels for # this subject # Note that you do not need to specify the transform when creating this as it # is already specified in the red, green, and blue channels vol_data = cortex.VolumeRGB(red, green, blue, subject) cortex.quickshow(vol_data, with_colorbar=False) 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
rgb = colors.hsv_to_rgb(hsv) # define alpha channel - which specifies the opacity for a color # 0 = transparent = values with rsq below thresh and 1 = opaque = values above thresh alpha_mask = (rsq <= rsq_threshold ).T #why transpose? because of orientation of pycortex volume? alpha = np.ones(alpha_mask.shape) alpha[alpha_mask] = 0 #create volumes #contains RGBA colors for each voxel in a volumetric dataset # volume for polar angles vrgba = cortex.VolumeRGB(red=rgb[..., 0].T, green=rgb[..., 1].T, blue=rgb[..., 2].T, subject='sub-' + sub_num, alpha=alpha, xfmname='fmriprep_T1') # volume for ecc vecc = cortex.Volume2D(eccentricity.T, rsq.T, 'sub-' + sub_num, 'fmriprep_T1', vmin=0, vmax=10, vmin2=rsq_threshold, vmax2=1.0, cmap='BROYG_2D') # volume for size
# 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.Volume(test1_scaled.astype(np.uint8), 'S1', 'fullhead') green = cortex.Volume(test2_scaled.astype(np.uint8), 'S1', 'fullhead') blue = cortex.Volume(test3_scaled.astype(np.uint8), 'S1', 'fullhead') # This creates an RGB Volume from the three different color channels for # this subject using the default RGB mappings # Note that you do not need to specify the transform when creating this as it # is already specified in the red, green, and blue channels vol_data = cortex.VolumeRGB(red, green, blue, subject) cortex.quickshow(vol_data, with_colorbar=False) plt.show() # This creates an RGB Volume from the three different color channels for # this subject using custom colors. # Note that you do not need to specify the transform when creating this as it # is already specified in the red, green, and blue channels vol_data = cortex.VolumeRGB(red, green, blue, subject, channel1color=cortex.Colors.RoseRed, channel2color=cortex.Colors.LimeGreen, channel3color=cortex.Colors.DodgerBlue) cortex.quickshow(vol_data, with_colorbar=False)