예제 #1
0
def test_vmin_none_in_dataview2d():
    data = np.arange(np.product(volshape)).reshape(volshape, order='C')
    view = cortex.Volume2D(data, data + 1, subject=subj, xfmname=xfmname)
    cortex.quickshow(view)

    data = np.arange(nverts)
    view = cortex.Vertex2D(data, data + 1, subject=subj)
    cortex.quickshow(view)
예제 #2
0
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)
예제 #3
0
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)
예제 #4
0
def alphaplot(sub, dat, R2, thresh, fig, save, fname):
    light = cortex.Vertex2D(dat,
                            R2,
                            subject=sub,
                            vmin=np.nanmin(dat),
                            vmax=np.nanmax(dat),
                            vmin2=thresh,
                            vmax2=1,
                            cmap='plasma_alpha')
    mfig = cortex.quickshow(light, with_curvature=True, fig=fig)
    sp.savefig(fname,
               dpi=300,
               facecolor='w',
               edgecolor='w',
               orientation='portrait',
               papertype=None,
               format='png',
               transparent=False,
               bbox_inches=None,
               pad_inches=0.1,
               frameon=None)
예제 #5
0
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], lflatpts[selected_pts,1], s=50, 
           c=sparse_data, vmin=-2, vmax=2, cmap=plt.cm.RdBu_r, zorder=10)

예제 #6
0
"""
=======================
Get Vertices for an ROI
=======================

In this example we show how to get the vertices that are inside an ROI that was
defined in the SVG ROI file (see :doc:`/rois.rst`).

"""
import cortex

# get vertices for fusiform face area FFA in subject S1
roi_verts = cortex.get_roi_verts('S1', 'FFA')

# roi_verts is a dictionary (in this case with only one entry)
ffa_verts = roi_verts['FFA']

# this includes indices from both hemispheres
# let's create an empty Vertex object and fill FFA

ffa_map = cortex.Vertex.empty('S1', cmap='plasma')
ffa_map.data[ffa_verts] = 1.0

cortex.quickshow(ffa_map)
예제 #7
0
"""
import cortex
import cortex.polyutils
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")]
numl = surfs[0].pts.shape[0]

# Now we need to pick the start and end points of the line we will draw
pt_a = 100
pt_b = 50000

# Then we find the geodesic path between these points
path = surfs[0].geodesic_path(pt_a, pt_b)

# In order to plot this on the cortical surface, we need an array that is the
# same size as the number of vertices in the left hemisphere
path_data = np.zeros(numl)
for v in path:
    path_data[v] = 1

# And now plot these distances onto the cortical surface
path_verts = cortex.Vertex(path_data, subject, cmap="Blues_r")
cortex.quickshow(path_verts, with_colorbar=False)
plt.show()
and you will also need a flatmap for them.
"""
import six
import cortex
import matplotlib.pyplot as plt
if six.PY2:
    from urllib import urlretrieve
elif six.PY3:
    from urllib.request import urlretrieve


# Download the dataset and load it
_ = urlretrieve("http://gallantlab.org/pycortex/S1_retinotopy.hdf",
                "S1_retinotopy.hdf")
ret_data = cortex.load("S1_retinotopy.hdf")

# The retinotopy data has to be divided into left and right hemispheres
left_data = ret_data.angle_left
cortex.quickshow(left_data, with_curvature=True, 
							curvature_contrast=0.5, 
							curvature_brightness=0.5, 
							curvature_threshold=True)
plt.show()

right_data = ret_data.angle_right
cortex.quickshow(right_data, with_curvature=True, 
							 curvature_contrast=0.5, 
							 curvature_brightness=0.5, 
							 curvature_threshold=True)
plt.show()
예제 #9
0
pixel will only have the value NaN if every voxel between pia and white matter 
has the value NaN.
"""

import cortex
import numpy as np
from matplotlib import pyplot as plt

# create dataset with volume of all 1's
vol = cortex.Volume.empty('S1', 'fullhead', vmin=0, vmax=2) + 1

# set 20% of the values in the dataset to NaN
vol.data[np.random.rand(*vol.data.shape) > 0.8] = np.nan

# plot the volume with nanmean=False
# here a nan in ANY layer of the thickness mapping will result in a nan
# in the final image
# so this image should have many, many holes that show curvature
# and all the non-hole points should have value of 1
_ = cortex.quickshow(vol, nanmean=False, with_curvature=True)

plt.show()

# plot the volume with nanmean=True
# here there should only be a nan in the final image if EVERY layer of the
# thickness mapping has a nan for the given pixel
# so this image should have many fewer holes that show curvature
# and, again, all the non-hole points should have value of 1
_ = cortex.quickshow(vol, nanmean=True, with_curvature=True)

plt.show()
예제 #10
0
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()
예제 #11
0
import matplotlib.pyplot as plt

subject = "S1"
xfm = "fullhead"

# Creating two different test datasets that are both the same shape as this
# transform with one entry for each voxel
# The matrices have just been reordered in different ways so that they make
# gradients across the brain in different directions
test_data1 = np.arange(31 * 100 * 100).reshape((31, 100, 100), order='C')
test_data2 = np.arange(31 * 100 * 100).reshape((31, 100, 100), order='F')

# This creates a 2D Volume object for both of our test datasets for the given
# subject and transform
vol_data = cortex.Volume2D(test_data1, test_data2, subject, xfm)
cortex.quickshow(vol_data, with_colorbar=False)
plt.show()

# You can alter the minimum and maximum values shown on the colorbar and this
# can be done separately for the two different datasets
vol_data = cortex.Volume2D(test_data1,
                           test_data2,
                           subject,
                           xfm,
                           vmin=np.mean(test_data1),
                           vmax=np.max(test_data1),
                           vmin2=np.min(test_data2),
                           vmax2=np.mean(test_data2))
cortex.quickshow(vol_data, with_colorbar=False)
plt.show()
예제 #12
0
def cv_report(results,
              model_name=None,
              subject=None,
              transform=None,
              ridges=None,
              cmap='viridis',
              save_dir=None,
              performance_histogram=True,
              global_vs_local=False,
              ridge_histogram=True,
              performance_flatmap=True,
              ridge_flatmap=True,
              file_label=''):
    """create diagnostic plots for results of cv_ridge()

    - specify subject and transform parameters to create flatmaps
    - specify save_dir to save figures to a directory

    Parameters
    ----------
    - results: dict of results from cv_ridge()
    - model_name: str of model name, added to titles of plots
    - subject: str subject surface name
    - transform: str transform name
    - performance_histogram: bool of whether to plot histogram of voxel performance
    - global_vs_local: bool of whether to plot 2d histogram of global vs local
    - ridge_histogram: bool of whether to plot histogram
    """
    if model_name is None:
        model_name = ''
    else:
        model_name += ' '

    if save_dir is not None:
        outputs = {
            'performance_histogram': '{file_label}performance_histogram.png',
            'global_vs_local': '{file_label}global_vs_local.png',
            'ridge_histogram': '{file_label}ridge_histogram.png',
            'performance_flatmap': '{file_label}performance_flatmap.png',
            'ridge_flatmap': '{file_label}ridge_flatmap.png',
        }
        outputs = {
            name: os.path.join(save_dir, path)
            for name, path in outputs.items()
        }
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)

    # test set performance plots
    if performance_histogram:
        histograms = {}
        if 'global_performance' in results:
            histograms['global'] = results['global_performance']
        if 'local_performance' in results:
            histograms['local'] = results['local_performance']
        plot_utils.hists1d(
            histograms,
            title=(model_name + 'test set performance'),
        )
        if save_dir is not None:
            plt.savefig(outputs['performance_histogram'])
        plt.show()

    if global_vs_local:
        plot_utils.hist2d(
            results['global_performance'],
            results['local_performance'],
            xlabel='global',
            ylabel='local',
            clabel='# regressands',
            title=(model_name + 'global vs local test set performance'),
        )
        if save_dir is not None:
            plt.savefig(outputs['global_vs_local'])
        plt.show()

    # ridge parameter histogram plots
    if ridge_histogram:
        bin_counts, (x_bin_bounds, y_bin_bounds) = plot_utils.hist1d(
            results['local_optimal_ridge'],
            stacked_data=results['local_performance'],
            log_x=True,
            n_bins=len(ridges),
            n_stacked_bins=10,
            stacked_cmap='spectral',
            xlabel='ridge parameter',
            ylabel='regressands',
            title=(model_name + 'ridge parameters'),
            stacked_label='test performance',
        )
        global_optimum = results['global_optimal_ridge']
        global_index = np.nonzero(x_bin_bounds <= global_optimum)[0][-1]
        bounds = x_bin_bounds
        plt.plot(
            scipy.stats.gmean([bounds[global_index],
                               bounds[global_index + 1]]),
            bin_counts.sum(1)[global_index],
            '.k',
            marker='*',
            markersize=15,
            label='global optimum',
        )
        plt.legend(numpoints=1, fontsize=20)
        if save_dir is not None:
            plt.savefig(outputs['ridge_histogram'])
        plt.show()

    # fMRI-specific reports
    if subject is not None and transform is not None:
        import cortex

        # performance flatmap
        if performance_flatmap:
            volume = cortex.Volume(
                results['local_performance'],
                subject=subject,
                xfmname=transform,
                cmap=cmap,
                vmin=0,
                vmax=.5,
                colorbar_ticklabelsize=15,
            )
            cortex.quickshow(volume)
            plt.title(model_name + 'test performance', fontsize=30)
            if save_dir is not None:
                plt.savefig(outputs['performance_flatmap'])
            plt.show()

        # ridge parameter flatmap
        if ridge_flatmap:
            volume = cortex.Volume(
                -np.log(results['local_optimal_ridge']),
                subject=subject,
                xfmname=transform,
                cmap=cmap,
                vmin=-np.log(ridges[-1]),
                vmax=-np.log(ridges[0]),
            )

            if len(ridges) > 5:
                ticks = np.logspace(
                    np.log10(ridges[0]),
                    np.log10(ridges[-1]),
                    5,
                )
            else:
                ticks = ridges

            cortex.quickshow(
                volume,
                colorbar_ticks=-np.log(ticks),
                colorbar_ticklabels=['{:0.2f}'.format(tick) for tick in ticks],
                colorbar_ticklabelsize=15,
            )
            plt.title(model_name + 'ridge parameters', fontsize=30)
            if save_dir is not None:
                plt.savefig(outputs['ridge_flatmap'])
            plt.show()
예제 #13
0
normal arithmetic operators like +, -, *, /, and **
"""

import cortex
import numpy as np
np.random.seed(1234)
import matplotlib.pyplot as plt

subject = 'S1'
xfm = 'fullhead'

# Creating a random dataset that is the shape for this transform with one
# entry for each voxel
test_data = np.random.randn(31, 100, 100)

# This creates a Volume object for our test dataset for the given subject
# and transform
vol_data = cortex.Volume(test_data, subject, xfm, vmin=-2, vmax=2)
cortex.quickshow(vol_data)
plt.show()

# Now you can do arithmetic with the Volume
vol_plus = vol_data + 1
cortex.quickshow(vol_plus)
plt.show()

# You can also do multiplication
vol_mult = vol_data * 4
cortex.quickshow(vol_mult)
plt.show()
예제 #14
0
"""
import six
import cortex
import matplotlib.pyplot as plt
if six.PY2:
    from urllib import urlretrieve
elif six.PY3:
    from urllib.request import urlretrieve

# Download the dataset and load it
_ = urlretrieve("http://gallantlab.org/pycortex/S1_retinotopy.hdf",
                "S1_retinotopy.hdf")
ret_data = cortex.load("S1_retinotopy.hdf")

# The retinotopy data has to be divided into left and right hemispheres
left_data = ret_data.angle_left
cortex.quickshow(left_data,
                 with_curvature=True,
                 curvature_contrast=0.5,
                 curvature_brightness=0.5,
                 curvature_threshold=True)
plt.show()

right_data = ret_data.angle_right
cortex.quickshow(right_data,
                 with_curvature=True,
                 curvature_contrast=0.5,
                 curvature_brightness=0.5,
                 curvature_threshold=True)
plt.show()
예제 #15
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)

images['rsq_combined'] = cortex.Vertex2D(rsq_visual_norm,rsq_motor_norm, 
                            subject='fsaverage_gross',
예제 #16
0
def zoom_to_roi(subject, roi, hem, margin=10.0):
    roi_verts = cortex.get_roi_verts(subject, roi)[roi]
    roi_map = cortex.Vertex.empty(subject)
    roi_map.data[roi_verts] = 1

    (lflatpts, lpolys), (rflatpts, rpolys) = cortex.db.get_surf(subject,
                                                                "flat",
                                                                nudge=True)
    sel_pts = dict(left=lflatpts, right=rflatpts)[hem]
    roi_pts = sel_pts[np.nonzero(getattr(roi_map, hem))[0], :2]

    xmin, ymin = roi_pts.min(0) - margin
    xmax, ymax = roi_pts.max(0) + margin
    plt.axis([xmin, xmax, ymin, ymax])


# Create dataset
data = cortex.Volume.random('S1', 'fullhead')

# Plot it using quickflat
cortex.quickshow(data)

# Zoom on just one region
zoom_to_roi('S1', 'AC', 'left')

# notice that the quality of this figure is now quite poor/grainy
# we can improve this by changing the 'height' argument to quickflat

cortex.quickshow(data, height=2048)
zoom_to_roi('S1', 'AC', 'left')
예제 #17
0
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],
           lflatpts[selected_pts, 1],
           s=50,
           c=sparse_data,
예제 #18
0
voxels and then create a cortex.Volume object. Then, you get a mapper to go
between voxels and vertices for the specific subject and transform you are
working with. Pass the voxel volume through the mapper and you get out a
vertex mapping of that data. You can plot both of these as you normally would.
"""

import cortex
import cortex.polyutils
import numpy as np
np.random.seed(1234)
import matplotlib.pyplot as plt

subject = 'S1'
xfm = 'fullhead'

# First create example voxel data for this subject and transform
voxel_data = np.random.randn(31, 100, 100)
voxel_vol = cortex.Volume(voxel_data, subject, xfm)

# Then we have to get a mapper from voxels to vertices for this transform
mapper = cortex.get_mapper(subject, xfm, 'line_nearest', recache=True)

# Just pass the voxel data through the mapper to get vertex data
vertex_map = mapper(voxel_vol)

# You can plot both as you would normally plot Volume and Vertex data
cortex.quickshow(voxel_vol)
plt.show()
cortex.quickshow(vertex_map)
plt.show()
예제 #19
0
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()
    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)
    ax.axis('off')

plt.subplots_adjust(left=.01,
                    right=.99,
                    top=.99,
                    bottom=.01,
예제 #21
0
Creating a flatmap from a folded cortical surface always introduces some
distortion. This is similar to what happens when a map of the globe is flattened
into a 2-D map like a Mercator projection. For the cortical surface the amount
and type of distortion will depend on the curvature of the surface (i.e. whether
it is on a gyrus or a sulcus) and on the distance to the nearest cut.

In general, we recommend examining data both in flattened and original 3-D space
using the interactive webGL viewer, but it is also informative to visualize the
distortion directly.

One method to show distortion is to visualize how geodesic discs, which contain
all of the points within some geodesic distance of a central point, appear on the
flattened cortical surface. 

This technique is traditionally used to characterize and visualize distortions
introduced by flattening the globe onto a map:

.. image::https://upload.wikimedia.org/wikipedia/commons/8/87/Tissot_mercator.png

"""

import cortex
import matplotlib.pyplot as plt

tissot = cortex.db.get_surfinfo("S1", "tissots_indicatrix", radius=10, spacing=30)
tissot.cmap = 'plasma'

cortex.quickshow(tissot, with_labels=False, with_rois=False, with_colorbar=False)

plt.show()
예제 #22
0
import numpy as np
np.random.seed(1234)


# Create a random pycortex Volume
volume = cortex.Volume.random(subject='S1', xfmname='retinotopy')

# Plot a flatmap with the data projected onto the surface
# By default ROIs and their labels will be overlaid to the plot
# Also a colorbar will be added
_ = cortex.quickflat.make_figure(volume)
plt.show()

# The cortex.quickshow method is a pointer to quickflat.make_figure
# and will plot exactly the same as the above plot
_ = cortex.quickshow(volume)
plt.show()

# Highlight the curvature
_ = cortex.quickflat.make_figure(volume, with_curvature=True)
plt.show()

# Remove ROI labels from the plot
_ = cortex.quickflat.make_figure(volume,
                                 with_curvature=True,
                                 with_labels=False)
plt.show()

# Remove ROIs from the plot
_ = cortex.quickflat.make_figure(volume,
                                 with_curvature=True,
예제 #23
0
파일: utils.py 프로젝트: mszinte/PredictEye
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
예제 #24
0
# the polys (triangles) are the same for the fiducial and flat surfaces
(lfidpts, lpolys), _ = cortex.db.get_surf(subject, "fiducial")

# load flattened surfaces
(lflatpts, lpolys), _ = cortex.db.get_surf(subject, "flat")

# Create the Distortion object
dist = Distortion(lflatpts, lfidpts, lpolys)

# 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)

cortex.quickshow(areal_dist, with_rois=False, with_labels=False)


# 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(metric_dist, with_rois=False, with_labels=False)


# Both of these distortion metrics can also be fetched easily via the pycortex
# database

# these also return Vertex objects like those we created above
areal_dist_2 = cortex.db.get_surfinfo(subject, "distortion", dist_type="areal")
metric_dist_2 = cortex.db.get_surfinfo(subject, "distortion", dist_type="metric")
예제 #25
0
"""

import cortex
import numpy as np
np.random.seed(1234)
import matplotlib.pyplot as plt

subject = 'S1'
xfm = 'fullhead'

# Creating a random dataset that is the shape for this transform with one
# entry for each voxel
test_data = np.random.randn(31, 100, 100)

# This creates a Volume object for our test dataset for the given subject
# and transform
vol_data = cortex.Volume(test_data, subject, xfm)
cortex.quickshow(vol_data)
plt.show()

# Can also alter the minimum and maximum values shown on the colorbar
vol_data_thresh = cortex.Volume(test_data, subject, xfm, vmin=-1, vmax=1)
cortex.quickshow(vol_data_thresh)
plt.show()

# If you have NaN values, those voxels show up transparent on the brain
test_data[10:15, :, :] = np.nan
vol_data_nan = cortex.Volume(test_data, subject, xfm)
cortex.quickshow(vol_data_nan)
plt.show()
예제 #26
0
# 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()
예제 #27
0
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]))
예제 #28
0
# 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()
예제 #29
0
import cortex.polyutils
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")
]
numl = surfs[0].pts.shape[0]

# Now we need to pick the start and end points of the line we will draw
pt_a = 100
pt_b = 50000

# Then we find the geodesic path between these points
path = surfs[0].geodesic_path(pt_a, pt_b)

# In order to plot this on the cortical surface, we need an array that is the
# same size as the number of vertices in the left hemisphere
path_data = np.zeros(numl)
for v in path:
    path_data[v] = 1

# And now plot these distances onto the cortical surface
path_verts = cortex.Vertex(path_data, subject, cmap="Blues_r")
cortex.quickshow(path_verts, with_colorbar=False)
plt.show()