Пример #1
0
def main(sourcedata,
         derivatives,
         subject,
         session):
    out_dir = op.join(derivatives, 
                          'pycortex',
                          'sub-{}'.format(subject)) 

    for version in ['light', 'full']:
        d = op.join(out_dir, version)
        if not op.exists(d):
            os.makedirs(d)
    
    if subject not in cortex.db.subjects:
        cortex.fmriprep.import_subj(subject, '/derivatives', None, dataset='odc')

    pc_subject = 'odc.{}'.format(subject)

    images = {}
    t1w = get_bids_file(derivatives, 'averaged_mp2rages', 'anat',
                         subject, 'T1w', session, 'average')
    images['t1w'] = cortex.Volume(t1w, pc_subject, 'identity', vmin=0, vmax=4095)

    t1map = get_bids_file(derivatives, 'averaged_mp2rages', 'anat',
                           subject, 'T1map', session, 'average')
    images['t1map'] = cortex.Volume(t1map, pc_subject, 'identity', vmin=1000, vmax=2200)

    t2starmap = get_bids_file(derivatives, 'qmri_memp2rages', 'anat',
                            subject, 't2starmap', session, 'average')
    images['t2starmap'] = cortex.Volume(t2starmap, pc_subject, 'identity', vmin=10, vmax=60)

    s0 = get_bids_file(derivatives, 'qmri_memp2rages', 'anat',
                            subject, 'S0', session, 'average')
    images['s0'] = cortex.Volume(s0, pc_subject, 'identity')


    for echo_ix in range(1,5):
        echo = get_bids_file(sourcedata, '', 'anat', subject, 'MPRAGE',
                              session='anat', acquisition='memp2rage', echo=echo_ix,
                              inversion=2, part='mag')
        if echo_ix == 1:
            transform = cortex.xfm.Transform(np.identity(4), echo)
            transform.save(subject, 'memp2rage')
            max_first_echo = np.percentile(image.load_img(echo).get_data(), 95)
        images['echo{}'.format(echo_ix)] = cortex.Volume(echo, 
                                                         pc_subject, 
                                                         'memp2rage',
                                                         vmin=0,
                                                         vmax=max_first_echo)
    ds = cortex.Dataset(t1map=images['t1map'],
                        s0=images['s0'],
                        t2starmap=images['t2starmap'])
                                     
    cortex.webgl.make_static(op.join(out_dir, 'light'), ds)
    cortex.webshow(ds)

    ds = cortex.Dataset(**images)
    cortex.webgl.make_static(op.join(out_dir, 'full'), ds)
    cortex.webshow(ds)
Пример #2
0
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)
Пример #3
0
def test_overwrite():
    tf = tempfile.NamedTemporaryFile(suffix=".hdf")
    ds = cortex.Dataset(test=(np.random.randn(*volshape), subj, xfmname))
    ds.save(tf.name)

    ds.save()
    assert ds.test.data.shape == volshape
Пример #4
0
def generate_pycortex_static(volumes, output_dir):
    app_path = os.path.abspath(os.path.dirname(__file__))
    tpl_path = os.path.join(app_path, 'templates/pycortex/dataview.html')
    ds = cortex.Dataset(**volumes)
    cortex.webgl.make_static(output_dir,
                             ds,
                             template=tpl_path,
                             html_embed=False,
                             copy_ctmfiles=False)
Пример #5
0
def test_mask_save():
    tf = tempfile.NamedTemporaryFile(suffix=".hdf")
    ds = cortex.Dataset(test=(np.random.randn(*volshape), subj, xfmname))
    ds.append(masked=ds.test.masked['thin'])
    data = ds.masked.data
    ds.save(tf.name)

    ds = cortex.load(tf.name)
    assert ds.masked.shape == volshape
    assert np.allclose(ds.masked.data, data)
Пример #6
0
def main(subject, session, sourcedata, standard_space=False, thr=thr, smoothed=False):
    left, right = cortex.db.get_surf(f'sub-{subject}', 'fiducial', merge=False)
    left, right = cortex.Surface(*left), cortex.Surface(*right)


    d = {}


    if standard_space:
        space = 'fsaverage'
        d['wang15_ips'] = get_wang15_ips('fsaverage', sourcedata)
        fs_subject = 'fsaverage'
    else:
        space = 'fsnative'
        d['wang15_ips'] = get_wang15_ips(subject, sourcedata)
        fs_subject = f'sub-{subject}'


    key = 'encoding_model.cv'

    if smoothed:
        key += '.smoothed'


    for session in ['3t2', '7t2']:

        r2_cv = []

        for run in range(1, 9):

            r2 = []

            for hemi in ['L', 'R']:
                r2.append(surface.load_surf_data(op.join(sourcedata, 'derivatives', f'{key}/sub-{subject}/ses-{session}/func/sub-{subject}_ses-{session}_run-{run}_desc-cvr2.optim_space-{space}_hemi-{hemi}.func.gii')))
            
            r2_cv.append(np.concatenate(r2))
        
        r2_cv = np.mean(np.clip(r2_cv, 0.0, np.inf), 0)
        print(np.quantile(r2_cv, .95))
        alpha = np.clip(r2_cv-thr, 0., .1) /.1
        d[f'r2_cv.{session}'] = get_alpha_vertex(r2_cv, alpha, cmap='hot',
                subject=subject, vmin=0.0, vmax=.5, standard_space=standard_space)


        r2 = _load_parameters(subject, session, 'r2.optim', space, smoothed)
        alpha = np.clip(r2.data-thr, 0., .1) /.1

        d[f'r2.{session}'] = get_alpha_vertex(r2.data, alpha, cmap='hot',
                subject=subject, vmin=0.0, vmax=.5, standard_space=standard_space)

    ds = cortex.Dataset(**d)
    cortex.webshow(ds)

    x = np.linspace(0, 1, 101, True)
    y = np.linspace(np.log(5), np.log(vmax), len(x), True)
Пример #7
0
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)
Пример #8
0
def test_pack():
    tf = tempfile.NamedTemporaryFile(suffix=".hdf")
    ds = cortex.Dataset(test=(np.random.randn(*volshape), subj, xfmname))
    ds.save(tf.name, pack=True)

    ds = cortex.load(tf.name)
    pts, polys = cortex.db.get_surf(subj, "fiducial", "lh")
    dpts, dpolys = ds.get_surf(subj, "fiducial", "lh")
    assert np.allclose(pts, dpts)

    rois = cortex.db.get_overlay(subj, "rois")
    # Dataset.get_overlay returns a file handle, not an ROIpack ?
    #assert rois.rois.keys() == ds.get_overlay(subj, "rois").rois.keys()

    xfm = cortex.db.get_xfm(subj, xfmname)
    assert np.allclose(xfm.xfm, ds.get_xfm(subj, xfmname).xfm)
Пример #9
0
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)
Пример #10
0
def generate_pycortex_static(volumes, output_dir, title=None):
    """
    Parameters
    ----------

    volumes: dict
        key is volume name; value is a set of images.

    output_dir: str
        file location to dump output html

    title: str (optional)
        HTML title of pycortex viewer.
    """
    app_path = os.path.abspath(os.path.dirname(__file__))
    tpl_path = os.path.join(app_path, 'templates/pycortex/dataview.html')
    ds = cortex.Dataset(**volumes)
    title = title or ', '.join(volumes.keys())
    cortex.webgl.make_static(output_dir, ds, template=tpl_path, html_embed=False,
                             copy_ctmfiles=False, title=title)
Пример #11
0
def test_pack():
    tf = tempfile.NamedTemporaryFile(suffix=".hdf")
    ds = cortex.Dataset(test=(np.random.randn(*volshape), subj, xfmname))
    ds.save(tf.name, pack=True)

    ds = cortex.load(tf.name)
    pts, polys = cortex.db.get_surf(subj, "fiducial", "lh")
    dpts, dpolys = ds.get_surf(subj, "fiducial", "lh")
    assert np.allclose(pts, dpts)

    overlay_db = cortex.db.get_overlay(subj, None, modify_svg_file=False)
    rois_db = overlay_db.rois.labels.elements.keys()
    # keep the temporary file object in memory to avoid the file being deleted
    temp_file = ds.get_overlay(subj, "rois")
    overlay_ds = cortex.db.get_overlay(subj,
                                       temp_file.name,
                                       modify_svg_file=False)
    rois_ds = overlay_ds.rois.labels.elements.keys()
    assert rois_db == rois_ds

    xfm = cortex.db.get_xfm(subj, xfmname)
    assert np.allclose(xfm.xfm, ds.get_xfm(subj, xfmname).xfm)
Пример #12
0
    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)

plt.scatter(log_r2.data, nat_r2.data)
plt.plot([0, 1], [0, 1], c='k')
plt.show()

cortex.webshow(ds)
Пример #13
0
    roi_mni[roi_mni_tmp] = 1

print roi_mni.shape

# Transform ROI to Subject space
print "Transform ROI to subject space"
roi_func = transform_mni_to_subject(subject, xfmname, roi_mni, func_to_mni)
roi_func = roi_func.get_data()
# roi_func = np.where(roi_func, 1, 0)  # Make sure things are binary
print roi_func.shape

# Save ROI (MNI space) as NIFTI file
roi_mni_nii = ni.Nifti1Image(roi_mni, xfm_mni)
filename = "/tmp/roi_mni.nii"
roi_mni_nii.to_filename(filename)

# Save ROI (subject space) as NIFTI file
ref_filename = cortex.db.get_xfm(subject, xfmname).reference.get_filename()
xfm_subject = ni.load(ref_filename).get_affine()
roi_func_nii = ni.Nifti1Image(roi_func, xfm_subject)
filename = "/tmp/roi_func.nii"
roi_func_nii.to_filename(filename)

# Create static viewer
roivol = cortex.Volume(roi_func.T, subject, xfmname, cmap='gray_r', mask=mask)
mastervol = dict()
mastervol["roivol"] = roivol
ds = cortex.Dataset(**mastervol)
viewername = "/tmp/roi_viewer"
cortex.webgl.make_static(viewername, ds)
Пример #14
0
Recently, many people have start to use fmriprep as a complete preprocessing workflow of anatomical and functional data. Pycortex has a convenience function to import
the output of this workflow.

This example is based on the fmriprep 1.0.15 output of openfmri ds000164 that can be found on openneuro.org: https://openneuro.org/datasets/ds000164/versions/00001

NB: `cortex.fmriprep` is a work-in-progress and cannot currently handle multiple datasets when the subject IDs are the same (see https://github.com/gallantlab/pycortex/issues/304).
"""

import cortex
from cortex import fmriprep
from os import path as op

# Location of the downloaded openfmri dataset
source_directory = '/derivatives/ds000164'
# fmriprep subject name (without "sub-")
subject_id = '001'

# import subject into pycortex database
fmriprep.import_subj(subject_id, source_directory)

# We can use visualize the imported subject's T1-weighted image
anat_nifti = 'fmriprep/sub-001/anat/sub-001_T1w_preproc.nii.gz'
t1_image_path = op.join(source_directory, anat_nifti)

# Now we can make a volume using the built-in identity transform
t1w_volume = cortex.Volume(t1_image_path, subject_id, 'identity')

# And show the result.
ds = cortex.Dataset(t1w=t1w_volume)
cortex.webgl.show(ds)
Пример #15
0
try:
    os.makedirs(dataset_dir)
    os.makedirs(webviewer_dir)
except:
    pass

tc_file = "{base_dir}/pp_data/{subject}/func/{subject}_task-{tc_file_end}.nii.gz".format(
    base_dir=base_dir, subject=subject, tc_file_end=tc_file_end)
print('load: {} {}'.format(subject, tc_file_end))

img_tc = nb.load(tc_file)
tc = img_tc.get_data()

# create volume
volume_tc = cortex.Volume(data=tc.transpose((3, 2, 1, 0)),
                          subject=subject,
                          xfmname=xfm_name,
                          cmap='BuBkRd',
                          description='BOLD')

# create dataset
print('save pycortex dataset: time course')
dataset_tc = cortex.Dataset(data=volume_tc)
dataset_tc.save("{dataset_dir}{tc_file_end}_tc.hdf".format(
    tc_file_end=tc_file_end, dataset_dir=dataset_dir))

# create webgl
print('save pycortex webviewer: time course')
cortex.webgl.make_static(outpath=webviewer_dir, data=volume_tc)
        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)
Пример #17
0
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)
Пример #18
0
def main(derivatives, subject):

    pc_subject = 'odc.{}'.format(subject)

    coordinates = []
    for hemi in ['lh', 'rh']:
        coordinates.append(
            pd.read_pickle(
                op.join(
                    derivatives, 'coordinate_patches', 'sub-{subject}', 'anat',
                    'sub-{subject}_hemi-{hemi}_coordinatepatch.pkl').format(
                        **locals())))

    coordinates = pd.concat(coordinates, axis=0, ignore_index=True)
    print(coordinates.shape)
    print(coordinates.head())
    print(coordinates['x'].dtype)

    images = {}
    images['x'] = cortex.Vertex(coordinates['x'].values,
                                'odc.{}'.format(subject),
                                cmap='BROYG',
                                vmin=-35,
                                vmax=35)
    images['y'] = cortex.Vertex(coordinates['y'].values,
                                'odc.{}'.format(subject),
                                cmap='BROYG',
                                vmin=-35,
                                vmax=35)

    # 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.05

    hsv_angle = np.ones((len(r2), 3))
    hsv_angle[:, 0] = angle.copy()
    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)
    cortex.webshow(cortex.Dataset(**images))
Пример #19
0
    parss_r = parss_l.replace('hemi-L', 'hemi-R')
    parss = np.vstack((surface.load_surf_data(parss_r),
                       surface.load_surf_data(parss_r)))

    mu_v = cortex.Vertex(np.exp(parss[:, 0]),
                         'fsaverage', vmin=0, vmax=60)
    mu_log_v = cortex.Vertex(parss[:, 0], 'fsaverage', vmin=0, vmax=60)
    sd_v = cortex.Vertex(np.exp(parss[:, 1]),
                         'fsaverage', vmin=0, vmax=60)
    amplitude_v = cortex.Vertex(parss[:, 2], 'fsaverage')
    baseline_v = cortex.Vertex(parss[:, 3], 'fsaverage')

    ds = cortex.Dataset(
        r2=r2s_v,
        r2_triallise=r2s_trialwise_v,
        mu=mu_v,
        mu_log=mu_log_v,
        sd=sd_v,
        amplitude=amplitude_v,
        baseline=baseline_v)

    cortex.webshow(ds)

else:
    subject = '*'

    # r2s_cv_l = op.join(derivatives, 'modelfitsurf_cv_smoothed',
                       # f'sub-{subject}', 'func', f'sub-{subject}_space-fsaverage_desc-r2_hemi-L_cvrun-*.func.gii')
    # r2s_cv_r = r2s_cv_l.replace('hemi-L', 'hemi-R')
    # r2s_cv_l = np.clip([surface.load_surf_data(fn)
                        # for fn in glob.glob(r2s_cv_l)], 0, 1)
    # r2s_cv_r = np.clip([surface.load_surf_data(fn)
Пример #20
0
def test_convertraw():
    ds = cortex.Dataset(test=(np.random.randn(*volshape), subj, xfmname))
    ds.test.raw
Пример #21
0
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')
Пример #22
0
        'data': data['retinal_gain_index'].T,  # data to draw
        'cmap': cmap_gain,  # colormap to use
        'alpha': alpha.T,  # alpha map
        'vmin': 0,  # minimal value iqn colormap
        'vmax': 1,  # maximal value in colormap
        'curv_brightness': 0.05,  # curvature brightness
        'curv_contrast': 0.1,  # curvature contrast
        'cbar': 'discrete'
    }  # color bar layout
    vol_names.append('retinal_gain_index')  # save volume name

    # draw volumes, add to the overlay, create dataset
    dataset_name                   =   'loo_dataset_{mask_dir}.hdf'.\
                                                        format(mask_dir = mask_dir)                         # define dataset name

    dataset_webgl = cortex.Dataset()  # pre-define dataset

    for vol_name in vol_names:
        roi_name                        =   'loo_{vol_name}_{mask_dir}'.\
                                                    format(vol_name = vol_name, mask_dir = mask_dir)        # define roi name

        if mask_dir == 'pos':
            roi_param = {
                'add_roi': True,  # add roi to overlay.svg
                'roi_name': roi_name
            }  # name of the roi
            exec(
                'param_{vol_name}.update(roi_param)'.format(vol_name=vol_name))
        else:
            roi_param = {
                'add_roi': False,  # add roi to overlay.svg
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)
Пример #24
0
transform = cortex.xfm.Transform(np.identity(4), ref_file)
transform.save(subject, xfm_name, 'magnet')

# Add masks to pycortex transform
# -------------------------------
print('create pycortex transform')
xfm_masks = analysis_info['xfm_masks']
ref = nb.load(ref_file)
for xfm_mask in xfm_masks:

    mask = cortex.get_cortical_mask(subject=subject,
                                    xfmname=xfm_name,
                                    type=xfm_mask)
    mask_img = nb.Nifti1Image(dataobj=mask.transpose((2, 1, 0)),
                              affine=ref.affine,
                              header=ref.header)
    mask_file = "{cortex_dir}/transforms/{xfm_name}/mask_{xfm_mask}.nii.gz".format(
        cortex_dir=cortex_dir, xfm_name=xfm_name, xfm_mask=xfm_mask)
    mask_img.to_filename(mask_file)

# Create participant pycortex overlays
# ------------------------------------
print('create subject pycortex overlays to check')
voxel_vol = cortex.Volume(np.random.randn(mask.shape[0], mask.shape[1],
                                          mask.shape[2]),
                          subject=subject,
                          xfmname=xfm_name)
ds = cortex.Dataset(rand=voxel_vol)
cortex.webgl.make_static(outpath=temp_dir, data=ds)
Пример #25
0
def main(subject,
         session,
         sourcedata,
         standard_space=False,
         thr=thr,
         smoothed=False):
    left, right = cortex.db.get_surf(f'sub-{subject}', 'fiducial', merge=False)
    left, right = cortex.Surface(*left), cortex.Surface(*right)

    d = {}

    if standard_space:
        space = 'fsaverage'
        d['wang15_ips'] = get_wang15_ips('fsaverage', sourcedata)
    else:
        space = 'fsnative'
        d['wang15_ips'] = get_wang15_ips(subject, sourcedata)

    concatenated = False

    for session in ['3t1', '7t1', '3t2', '7t2']:

        # for desc, split_certainty in zip(['', '.certain', '.uncertain'], [False, True, True]):
        for desc, split_certainty in zip([''], [False]):
            ext = ''
            # if pca_confounds:
            # ext += '.pca_confounds'
            if smoothed:
                ext += '.smoothed'

            print(desc)
            r2 = _load_parameters(subject,
                                  session,
                                  'r2.optim' + desc,
                                  space,
                                  smoothed,
                                  split_certainty=split_certainty,
                                  concatenated=concatenated,
                                  pca_confounds=False)

            if r2 is not None:
                alpha = np.clip(r2.data - thr, 0., .1) / .1

                d[f'r2.{session}{ext}{desc}'] = get_alpha_vertex(
                    r2.data,
                    alpha,
                    cmap='hot',
                    subject=subject,
                    vmin=0.0,
                    vmax=.5,
                    standard_space=standard_space)

                mu = _load_parameters(subject,
                                      session,
                                      'mu.optim' + desc,
                                      space,
                                      smoothed,
                                      split_certainty=split_certainty,
                                      concatenated=concatenated)

                d[f'mu.{session}{ext}{desc}'] = get_alpha_vertex(
                    mu.data,
                    alpha,
                    cmap='nipy_spectral',
                    subject=subject,
                    vmin=np.log(5),
                    vmax=np.log(28),
                    standard_space=standard_space)

    ds = cortex.Dataset(**d)
    cortex.webshow(ds)

    x = np.linspace(0, 1, 101, True)
    y = np.linspace(np.log(5), np.log(vmax), len(x), True)

    plt.imshow(plt.cm.nipy_spectral(x)[np.newaxis, ...],
               extent=[np.log(5),
                       np.log(vmax),
                       np.log(5),
                       np.log(vmax)],
               aspect=1. / 10.,
               origin='lower')

    ns = np.array([5, 7, 10, 14, 20, 28, 40, 56, 80])
    ns = ns[ns <= vmax]

    plt.xticks(np.log(ns), ns)
    # plt.xlim(np.olg(5, np.log(vmax))
    plt.show()
Пример #26
0
def main(sourcedata, derivatives, subject='tk', dataset='odc'):

    pc_subject = '{}.{}'.format(dataset, subject)
    template = '{derivatives}/modelfitting/glm7/sub-{subject}/ses-{session}/func/sub-{subject}_ses-{session}_left_over_right_zmap.nii.gz'

    session = 'odc2'
    zmap1 = template.format(**locals())

    session = 'odc3'
    zmap2 = template.format(**locals())

    session = 'cas'
    zmap3 = template.format(**locals())

    t1w = get_bids_file(derivatives, 'averaged_mp2rages', 'anat', subject,
                        'T1w', 'anat', 'average')

    zmap1 = image.resample_to_img(zmap1, t1w, interpolation='nearest')
    zmap2 = image.resample_to_img(zmap2, t1w, interpolation='nearest')
    zmap3 = image.resample_to_img(zmap3, t1w, interpolation='nearest')

    transform = cortex.xfm.Transform(np.identity(4), t1w)
    #transform.save(pc_subject, 'identity.t1w', 'magnet')

    mask1 = image.math_img('np.abs(zmap)', zmap=zmap1).get_data().T
    mask2 = image.math_img('np.abs(zmap)', zmap=zmap2).get_data().T
    mask3 = image.math_img('np.abs(zmap) > 2', zmap=zmap3).get_data().T

    print(mask3.sum())

    mask3 = ndimage.binary_closing(mask3, iterations=2)
    print(mask3.sum())

    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 = {}
    zmap1 = zmap1.get_data().T
    zmap1[zmap1 == 0] = np.nan

    zmap2 = zmap2.get_data().T
    zmap2[zmap2 == 0] = np.nan

    zmap3 = zmap3.get_data().T
    zmap3[zmap3 == 0] = np.nan

    images['PRF polar angle'] = cortex.VertexRGB(rgb_angle[:, 0],
                                                 rgb_angle[:, 1],
                                                 rgb_angle[:, 2],
                                                 alpha=alpha_angle,
                                                 subject=pc_subject)

    #images['zmap_ses-odc2'] = cortex.Volume2D(zmap1,
    #mask,
    #pc_subject,
    #'identity.t1w', vmin=-3, vmax=3, vmin2=0, vmax2=3,
    #cmap='BuBkRd_alpha_2D')

    #images['zmap_ses-odc3'] = cortex.Volume2D(zmap2,
    #mask,
    #pc_subject,
    #'identity.t1w', vmin=-3, vmax=3, vmin2=0, vmax2=3,
    #cmap='BuBkRd_alpha_2D')

    images['ODCs Amsterdam 1'] = cortex.Volume2D(zmap1,
                                                 mask3,
                                                 pc_subject,
                                                 'identity.t1w',
                                                 vmin=-3,
                                                 vmax=3,
                                                 vmin2=0,
                                                 vmax2=3,
                                                 cmap='BuBkRd_alpha_2D')

    images['ODCs Amsterdam 2'] = cortex.Volume2D(zmap2,
                                                 mask3,
                                                 pc_subject,
                                                 'identity.t1w',
                                                 vmin=-3,
                                                 vmax=3,
                                                 vmin2=0,
                                                 vmax2=3,
                                                 cmap='BuBkRd_alpha_2D')

    images['ODCs Beijing'] = cortex.Volume2D(zmap3,
                                             mask3,
                                             pc_subject,
                                             'identity.t1w',
                                             vmin=-3,
                                             vmax=3,
                                             vmin2=0,
                                             vmax2=3,
                                             cmap='BuBkRd_alpha_2D')

    ds = cortex.Dataset(**images)

    cortex.webgl.make_static(outpath=op.join(derivatives, 'pycortex', subject),
                             data=ds)
    cortex.webshow(ds)
Пример #27
0
                                vmin2=settings['rsq_threshold'],
                                vmax2=1.0,
                                cmap='RdBu_r_alpha')
    vrsq = cortex.Volume2D(rsq.T,
                           rsq.T,
                           'sub-{subject}'.format(subject=subject),
                           'fmriprep_T1',
                           vmin=0,
                           vmax=0.8,
                           vmin2=settings['rsq_threshold'],
                           vmax2=1.0,
                           cmap='fire_alpha')

    ds = cortex.Dataset(polar=vrgba,
                        ecc=vecc,
                        size=vsize,
                        amplitude=vbeta,
                        baseline=vbaseline,
                        rsq=vrsq)
    ds.save(
        os.path.join(base_dir, 'derivatives', 'out', 'pp',
                     'sub-{subject}'.format(subject=subject),
                     'ses-{ses}'.format(ses=settings['session']),
                     'pycortex_ds.h5'))

if args.webgl_pRFs == 1:
    outpath = os.path.join(base_dir, 'derivatives', 'out', 'pp',
                           'sub-{subject}'.format(subject=subject),
                           'ses-{ses}'.format(ses=settings['session']),
                           'webgl')
    print("making static pycortex webgl instance in {outpath}".format(
        outpath=outpath))
Пример #28
0
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)
Пример #29
0
freq_log10 = np.log10(freq)

#freq[freq <1] = np.nan
#freq[freq > 60] = np.nan
#freq[r2 < .1] = np.nan

images = {}
images['frequency'] = cortex.Volume(freq,
                                    pc_subject,
                                    'identity.t1w.v2',
                                    vmin=0.1,
                                    vmax=60)
images['r2'] = cortex.Volume(r2,
                             pc_subject,
                             'identity.t1w.v2',
                             vmin=0,
                             vmax=0.7)
images['log_freq'] = cortex.Volume(log_freq.get_data().T,
                                   pc_subject,
                                   'identity.t1w.v2',
                                   vmin=-1,
                                   vmax=5)
images['log10'] = cortex.Volume(freq_log10, pc_subject, 'identity.t1w.v2')
images['amplitude'] = cortex.Volume(amplitude.get_data().T, pc_subject,
                                    'identity.t1w.v2')
images['log_sd'] = cortex.Volume(log_sd.get_data().T, pc_subject,
                                 'identity.t1w.v2')

ds = cortex.Dataset(**images)
cortex.webshow(images)
Пример #30
0
                                      'sub-' + sub_num,
                                      'fmriprep_T1',
                                      vmin=0,
                                      vmax=1,
                                      vmin2=0,
                                      vmax2=5,
                                      cmap='BROYG_2D')  #'my_autumn')

#convert into a `Dataset`
DS = cortex.Dataset(polar=vrgba,
                    ecc=vecc,
                    size=vsize,
                    amplitude=vbeta,
                    baseline=vbaseline,
                    rsq=vrsq,
                    mean_epi=mean_epi,
                    face=v_face,
                    upper_limb=v_upper,
                    lower_limb=v_lower,
                    RvsL_upper=rl_upper,
                    RvsL_lower=rl_lower,
                    comb_FUL=v_combined,
                    Lhand=v_Lfingers_combined,
                    Rhand=v_Rfingers_combined)
# save in prf params dir
#DS.save(os.path.join(output_dir, 'pycortex_ds.h5'))

# Creates a static webGL MRI viewer in your filesystem
cortex.webgl.make_static(web_path,
                         DS)  #,template='SBref_sub-'+sub_num+'.html')