示例#1
0
    def roi_mask_v2(self, roimask, contrast_data):

        filename = tempfile.mktemp(suffix='.png',
                                   dir=self.tmp_image_dir,
                                   prefix='roi_masks-')
        mask = cortex.db.get_mask('MNI', 'atlas')
        # a = b
        roimask = roimask * 1.0
        roimask[mask == False] = np.nan
        roivol = cortex.Volume(roimask, 'MNI', 'atlas', mask=mask)
        # Create flatmap
        fig = cortex.quickflat.make_figure(cortex.Volume(contrast_data,
                                                         'MNI',
                                                         'atlas',
                                                         vmin=0,
                                                         vmax=1,
                                                         cmap='Blues'),
                                           with_colorbar=False,
                                           with_curvature=True,
                                           bgcolor=None)
        # Add rois
        #if not contrast_data.isPmap:
        #    add_hash_layer(fig, roivol, [255,255,255], [0,8,12])
        add_hash_layer(fig, roivol, [10, 0, 0], [3, 8, 8])
        dpi = 100
        imsize = fig.get_axes()[0].get_images()[0].get_size()
        fig.set_size_inches(np.array(imsize)[::-1] / float(dpi))
        fig.savefig(filename, transparent=True, dpi=dpi)
        fig.clf()
        pltclose(fig)

        return filename
示例#2
0
def save_cca_volweights(fmri_weights, mask_file, out_dir, prefix_name,
                        out_png=True, two_side=False):
    """Save fmri weights derived from CCA as nifti files."""
    n_components = fmri_weights.shape[1]
    mask = data_swap(mask_file)
    vxl_idx = np.nonzero(mask.flatten()==1)[0]
    for i in range(n_components):
        tmp = np.zeros_like(mask.flatten(), dtype=np.float64)
        tmp[vxl_idx] = fmri_weights[:, i]
        tmp = tmp.reshape(mask.shape)
        nii_file = os.path.join(out_dir, prefix_name+'%s.nii.gz'%(i+1))
        save2nifti(tmp, nii_file)
        if out_png:
            import cortex
            from matplotlib import cm
            subj_id = out_dir.split('/')[-3]
            if two_side:
                img = cortex.quickflat.make_figure(cortex.Volume(nii_file,
                                    subj_id, 'func2anat', cmap=cm.bwr,
                                    vmin=-1., vmax=1.),
                                with_curvature=True)
            else:
                img = cortex.quickflat.make_figure(cortex.Volume(nii_file,
                                        subj_id, 'func2anat', cmap=cm.hot,
                                        vmin=0., vmax=1.),
                                with_curvature=True)
            png_file = os.path.join(out_dir, prefix_name+'%s.png'%(i+1))
            img.savefig(png_file, dpi=200)
示例#3
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)
示例#4
0
    def __init__(self,
                 data,
                 permuted_data,
                 name,
                 transform,
                 func_to_mni,
                 vmin,
                 vmax,
                 cmap='RdBu_r'):

        cortex.Volume.__init__(self,
                               data,
                               name,
                               transform,
                               vmin=vmin,
                               vmax=vmax,
                               cmap=cmap)

        self.permuted_contrast_pval = None
        self.threshold_05 = None
        self.threshold_01 = None
        self.threshold_05_mni = None
        self.threshold_01_mni = None

        if permuted_data is not None:

            # permuted contrast pycortex value
            self.permuted_contrast_pval = permuted_data

            # threshold 05
            threshold_05 = permuted_data
            threshold_05[threshold_05 > 0] = FDR(
                threshold_05[threshold_05 > 0], 0.05, do_correction=False)[0]
            self.threshold_05 = cortex.Volume(threshold_05,
                                              name,
                                              transform,
                                              vmin=-0.5,
                                              vmax=0.5)

            # threshold 05 mni
            self.threshold_05_mni = transform_to_mni(self.threshold_05,
                                                     func_to_mni).get_data().T

            # threshold 01
            threshold_01 = permuted_data
            threshold_01[threshold_01 > 0] = FDR(
                threshold_01[threshold_01 > 0], 0.01, do_correction=False)[0]
            self.threshold_01 = cortex.Volume(threshold_01,
                                              name,
                                              transform,
                                              vmin=-0.5,
                                              vmax=0.5)

            # threshold 01 mni
            self.threshold_01_mni = transform_to_mni(self.threshold_01,
                                                     func_to_mni).get_data().T
示例#5
0
    def show(self,nii=None,**kwargs):
        # get data from nii image
        data = self._get_nii_data(nii_name=nii)
        print(data)
        # create pycortex volume structure
        #####use vmin/vmax kwrags######
        self.vol = cortex.Volume(data,self.pycx_id,self.xfm_name,
                                    #           with_curvature=True,
                                    # curvature_contrast=0.65,
         #                            curvature_brightness=0.16,
         #                            curvature_threshold=True,
                                    **kwargs)
        
        # open in browser
        self.view = cortex.webshow(self.vol,autoclose=False,
                                    # with_curvature=True,
                                    # curvature_contrast=0.65,
         #                            curvature_brightness=0.16,
         #                            curvature_threshold=True,
                                    **kwargs)
        # view = cortex.webs`how(vol, port=port, autoclose=False, 
        #                     template=html_template, title='instabrain')
        self.view.animate([{'state':'surface.%s.specularity'%(self.subj.fsub),'idx':0,'value':0}])
        if self.subj.fsub == 'fsaverage':
            time.sleep(3)
            self.view.animate([{'state':'mix','idx':.5,'value':.5}])

        if nii is None or 'mask' in nii:
            self.view.setVminmax(-1,1)
    def debug_roi_mask(self, roimask, contrast_data):
        # Create random filename
        # filename = tempfile.mktemp(suffix='.png', dir=self.path, prefix='flatmap-')
        prefix = 'group'
        if contrast_data.isPmap:
            print('This is a Pmap!')
            filename = '{0}_{1}_{2}_flatPmap.png'.format(
                prefix, contrast_data.contrast.experiment.name,
                contrast_data.contrast.contrast_name)
        else:
            print('This is a not a Pmap!')
            filename = '{0}_{1}_{2}_flatmap.png'.format(
                prefix, contrast_data.contrast.experiment.name,
                contrast_data.contrast.contrast_name)
        filename = os.path.join(self.path, filename)
        print filename
        # mask = cortex.db.get_mask('MNI', 'atlas')
        roivol = cortex.Volume(roimask, 'MNI', 'atlas')
        # roivol[mask==False] = np.nan

        # Save flatmap
        cortex.quickflat.make_png(os.path.join(self.output_root, filename),
                                  contrast_data,
                                  with_colorbar=False,
                                  with_curvature=True,
                                  extra_hatch=(roivol, [255, 255, 255]),
                                  bgcolor='black')

        # Create HTML pointing to flatmap
        html = "<img src='{filename}'/>".format(filename=filename)

        return html
示例#7
0
    def __init__(self, name, transform, path):

        # basic attributes
        self.name = name
        self.transform = transform
        self.func_to_mni = cortex.db.get_mnixfm(name, transform)

        # attributes from file
        with tables.open_file(path) as tf:

            # voxels_predicted
            self.pred_score = tf.root.corr.read()
            threshold = 0.05
            self.voxels_predicted = self.pred_score > threshold

            # weights
            self.weights = tf.root.udwt.read()
            self.weights[:, self.voxels_predicted is False] = 0

        #predicted_mask_mni
        tmp = cortex.Volume(self.voxels_predicted.astype("float"), name,
                            transform)
        self.predicted_mask_mni = cortex.mni.transform_to_mni(
            tmp, self.func_to_mni).get_data().T
        self.predicted_mask_mni = (self.predicted_mask_mni > 0) * 1.0
示例#8
0
 def permuted_contrast_pval(self):
     if not hasattr(self, "_permuted_contrast"):
         p_contrast_vecs = np.dot(self.contrast.permuted_vectors,
                                  self.ref_to_subject.weights)
         contrast_vect = np.dot(self.contrast.vector,
                                self.ref_to_subject.weights)
         if self.contrast.double_sided:
             counts = (contrast_vect <= p_contrast_vecs).mean(0)
             counts[counts ==
                    0] = 1.0 / p_contrast_vecs.shape[0]  # can't have pval=0
             counts[self.ref_to_subject.voxels_predicted ==
                    False] = 0  # these are areas with no predictions
             p_map = counts  # -np.log10(counts)
         else:
             #stds = p_contrast_vecs.std(0)
             #p_map = np.norm.cdf(np.zeros(contrast_vect.shape),loc = contrast_vect, scale=stds)
             #p_map = -np.log10(p_map)
             counts = (np.zeros_like(contrast_vect) >=
                       p_contrast_vecs).mean(0)
             counts[counts ==
                    0] = 1.0 / p_contrast_vecs.shape[0]  # can't have pval=0
             counts[self.ref_to_subject.voxels_predicted ==
                    False] = 0  # these are areas with no predictions
             p_map = counts  #-np.log10(counts)
         self._permuted_contrast_pval = cortex.Volume(
             p_map,
             self.ref_to_subject.pycortex_surface,
             self.ref_to_subject.pycortex_transform,
             vmin=0,
             vmax=1)
     return self._permuted_contrast_pval
示例#9
0
 def predicted_mask_mni(self):
     if not hasattr(self, "_predicted_mask_mni"):
         tmp = cortex.Volume(self.voxels_predicted.astype("float"),
                             self.pycortex_surface, self.pycortex_transform)
         self._predicted_mask_mni = cortex.mni.transform_to_mni(
             tmp, self.func_to_mni, use_flirt=use_flirt).get_data().T
         self._predicted_mask_mni = (self._predicted_mask_mni > 0) * 1.0
     return self._predicted_mask_mni
示例#10
0
def test_volumedata_copy_with_custom_mask():
    mask = cortex.get_cortical_mask(subj, xfmname, "thick")
    mask[16] = True
    nmask = mask.sum()
    data = np.random.randn(nmask)
    v = cortex.Volume(data, subj, xfmname, mask=mask)
    vc = v.copy(v.data)
    assert np.allclose(v.data, vc.data)
    def __call__(self, contrast_data):
        # Create random filename
        # filename = tempfile.mktemp(suffix='.png', dir=self.path, prefix='flatmap-')

        if hasattr(contrast_data, 'ref_to_subject'):
            prefix = contrast_data.ref_to_subject.name
        else:
            prefix = 'group'

        if np.sum(contrast_data.data < 0) == 0:
            prefix += '_pmap'

            # tmp_volume = cortex.Volume(contrast_data.data, contrast_data.subject,
            #                                              contrast_data.xfmname,
            #                                             vmin = contrast_data.vmin,
            #                                             vmax = contrast_data.vmax,
            #                                             cmap = contrast_data.vmax,
            #                                             ** self.quickflat_args)
            tmp_volume = contrast_data
            # tmp_volume.data[contrast_data.ref_to_subject._voxels_predicted==False] = np.nan
        else:
            tmp_volume = cortex.Volume(contrast_data.data,
                                       contrast_data.subject,
                                       contrast_data.xfmname,
                                       **self.quickflat_args)
            # tmp_volume.data[contrast_data.ref_to_subject._voxels_predicted==False] = np.nan
            tmp_volume.data[tmp_volume.data == 0] = np.nan

        filename = '{0}_{1}_{2}_simpleFlatmap.png'.format(
            prefix, contrast_data.contrast.experiment.name,
            contrast_data.contrast.contrast_name)
        filename = os.path.join(self.path, filename)
        print filename

        # Save flatmap
        try:
            cortex.quickflat.make_png(os.path.join(self.output_root, filename),
                                      tmp_volume,
                                      with_colorbar=False,
                                      with_curvature=True,
                                      cvmin=-2,
                                      cvmax=2,
                                      **self.quickflat_args)
        except:
            cortex.quickflat.make_png(os.path.join(self.output_root, filename),
                                      tmp_volume,
                                      with_colorbar=False,
                                      with_curvature=True,
                                      cvmin=-2,
                                      cvmax=2,
                                      recache=True,
                                      **self.quickflat_args)

        # Create HTML pointing to flatmap
        html = "<img src='{filename}'/>".format(d=contrast_data,
                                                filename=filename)

        return self.make_output(Result(html, contrast_data))
示例#12
0
    def roi_mask_v2(self, roimask, contrast_data):

        # Create random filename
        prefix = 'group'
        if contrast_data.isPmap:
            print('This is a Pmap!')
            filename = '{0}_{1}_{2}_flatPmap.png'.format(
                prefix, contrast_data.contrast.experiment.name,
                contrast_data.contrast.contrast_name)
        else:
            print('This is a not a Pmap!')
            filename = '{0}_{1}_{2}_flatmap.png'.format(
                prefix, contrast_data.contrast.experiment.name,
                contrast_data.contrast.contrast_name)
        filename = os.path.join(self.path, filename)
        print filename
        mask = cortex.db.get_mask('MNI', 'atlas')
        # a = b
        roimask = roimask * 1.0
        roimask[mask == False] = np.nan
        roivol = cortex.Volume(roimask, 'MNI', 'atlas', mask=mask)
        # print np.sum(np.isnan(roivol.data))

        # Create flatmap
        #'YlGn'
        fig = cortex.quickflat.make_figure(contrast_data,
                                           with_colorbar=False,
                                           with_curvature=True,
                                           bgcolor='black')

        # Add rois

        if not contrast_data.isPmap:
            add_hash_layer(fig, roivol, [255, 255, 255], [0, 8, 12])
        add_hash_layer(fig, roivol, [10, 0, 0], [3, 8, 8])
        # add_hash_layer(fig, roivol, [10,10,0], [2,6,2])

        #add_hash_layer(fig, roivol, [0,50,0], [0,6,4])
        #add_hash_layer(fig, roivol, [10,10,0], [2,6,2])
        #add_hash_layer(fig, roivol, [255,255,255], [4,6,2])

        # Save flatmap

        dpi = 100

        imsize = fig.get_axes()[0].get_images()[0].get_size()
        fig.set_size_inches(np.array(imsize)[::-1] / float(dpi))
        # if bgcolor is None:
        fig.savefig(filename, transparent=True, dpi=dpi)
        # else:
        #     fig.savefig(filename, facecolor=filename, transparent=False, dpi=dpi)
        fig.clf()
        pltclose(fig)

        # Create HTML pointing to flatmap
        html = "<img src='{filename}'/>".format(filename=filename)

        return html
示例#13
0
 def update_show(self,nii):
     data = os.path.join(data_dir,nii)
     vol = cortex.Volume(data,self.pycx_id,self.xfm_name)
     mos, _ = cortex.mosaic(vol.data)
     # mos, _ = cortex.mosaic(vol.volume[0],show=False)
     self.view.dataviews.data.data[0]._setData(0,mos)
     # self.view.dataviews.data.data[0]._setData(1,mos)
     # if init:
     #     self.view.setVminmax(np.percentile(data,75),np.percentile(data,99))
     self.view.setFrame(1)
示例#14
0
 def thresholded_contrast_01(self):
     if not hasattr(self, "_thresholded_contrast_01"):
         thresholded_contrast_01 = self.permuted_contrast_pval.data
         thresholded_contrast_01[thresholded_contrast_01 > 0] = FDR(
             thresholded_contrast_01[thresholded_contrast_01 > 0],
             0.01,
             do_correction=False)[0]
         self._thresholded_contrast_01 = cortex.Volume(
             thresholded_contrast_01,
             self.ref_to_subject.pycortex_surface,
             self.ref_to_subject.pycortex_transform,
             vmin=-0.5,
             vmax=0.5)
     return self._thresholded_contrast_01
示例#15
0
def generate_pycortex_volume(image):
    nifti_file = str(image.file.path)
    transform_name = "trans_%s" % image.pk
    temp_dir = tempfile.mkdtemp(dir=settings.PYCORTEX_DATASTORE)
    try:
        new_mni_dat = os.path.join(temp_dir, "mni152reg.dat")
        mni_mat = os.path.join(temp_dir, "mni152reg.mat")
        reference = os.path.join(os.environ['FREESURFER_HOME'], 'subjects',
                                 'fsaverage', 'mri', 'brain.nii.gz')
        shutil.copy(
            os.path.join(os.environ['FREESURFER_HOME'], 'average',
                         'mni152.register.dat'), new_mni_dat)
        #this avoids problems with white spaces in file names
        tmp_link = os.path.join(temp_dir, "tmp.nii.gz")
        os.symlink(nifti_file, tmp_link)
        try:
            subprocess.check_output([
                os.path.join(os.environ['FREESURFER_HOME'], "bin",
                             "tkregister2"), "--mov", tmp_link, "--targ",
                reference, "--reg", new_mni_dat, "--noedit", "--nofix",
                "--fslregout", mni_mat
            ])
        except CalledProcessError, e:
            raise RuntimeError(
                str(e.cmd) + " returned code " + str(e.returncode) +
                " with output " + e.output)

        x = np.loadtxt(mni_mat)
        xfm = cortex.xfm.Transform.from_fsl(x, nifti_file, reference)
        xfm.save("fsaverage", transform_name, 'coord')

        dv = cortex.Volume(nifti_file,
                           "fsaverage",
                           transform_name,
                           cmap="RdBu_r",
                           dfilter="trilinear",
                           description=image.description)

        # default colormap range evaluated only at runtime (Dataview.to_json())
        # excludes max/min 1% : np.percentile(np.nan_to_num(self.data), 99)
        use_vmax = dv.to_json()['vmax'][0]
        dv.vmin = use_vmax * -1
        dv.vmax = use_vmax

        return dv
示例#16
0
    def debug_roi_mask(self, roimask, contrast_data):
        # Create random filename
        filename = tempfile.mktemp(suffix='.png',
                                   dir=self.path,
                                   prefix='flatmap-')

        roivol = cortex.Volume(roimask, 'MNI', 'atlas')

        # Save flatmap
        f = cortex.quickflat.make_png(os.path.join(self.output_root, filename),
                                      contrast_data,
                                      with_colorbar=False,
                                      with_curvature=True,
                                      extra_hatch=(roivol, [0, 250, 250]),
                                      bgcolor='black')

        # Create HTML pointing to flatmap
        html = "<img src='{filename}'/>".format(filename=filename)

        return html
示例#17
0
def createVolume(data, mask, surface, xfms, vmin=None, vmax=None, factor=0.95):
    """Helper function for creating a cortex volume for visualization.

    Parameters
    ----------
    data : np.ndarray
        The data to visualize.
    mask : np.ndarray
        Mask to use to transform.
    surface : TYPE 
        surface to use.
    xfms :  TYPE
        transform to use.
    vmin : float
        Default: Min of data.
    vmax : float
        Default: Max of data.
    factor : float
        Factor of vmax to use for visualization purposes.
             Default 0.95.

    Returns
    -------
    cortex volume
        
    """
    volData = np.zeros(mask.shape)
    volData[mask > 0] = data

    if vmin is None:
        vmin = np.min(volData)
    if vmax is None:
        vmax = np.max(volData) * factor
    else:
        vmax = factor * vmax

    return cortex.Volume(volData, surface, xfms, vmin=vmin, vmax=vmax)
示例#18
0
    def __call__(self, exp_name, subject, contrast, contrast_data):

        prefix = subject.name
        if np.sum(contrast_data.data < 0) == 0:
            prefix += '_pmap'
            volume = contrast_data
        else:
            volume = cortex.Volume(contrast_data.data, subject.name,
                                   subject.transform, **self.quickflat_args)

            volume.data[volume.data == 0] = np.nan

        file_name = '{0}_{1}_{2}_simple-flat-map.png'.format(
            prefix, exp_name, contrast.name)
        file_path = os.path.join(Config.image_dir, file_name)

        # Save flatmap
        try:
            cortex.quickflat.make_png(file_path,
                                      volume,
                                      with_colorbar=False,
                                      with_curvature=True,
                                      cvmin=-2,
                                      cvmax=2,
                                      **self.quickflat_args)
        except:
            cortex.quickflat.make_png(file_path,
                                      volume,
                                      with_colorbar=False,
                                      with_curvature=True,
                                      cvmin=-2,
                                      cvmax=2,
                                      recache=True,
                                      **self.quickflat_args)

        return HTMLImage('flat-map-analysis analysis', file_path)
示例#19
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)
示例#20
0
os.chdir("/auto/k1/fatma/python-packages/replication/code")

subject = "JGfs"
xfmname = "20110321JG_auto2"
volspace = (31, 100, 100)

# Get subject's cortical mask
mask = cortex.db.get_mask(subject, xfmname, "thick")

# Create random brain data
vol = np.zeros(volspace)
vol[mask] = np.random.random((vol[mask].shape))

# Create pycortex Volume
datavol = cortex.Volume(vol, subject, xfmname, cmap='RdBu_r', vmin=0, vmax=1)
# cortex.quickshow(datavol);

# Transform volume to MNI space
print "Transform volume to MNI space"
# 1. Compute transformation matrix
func_to_mni = compute_mni_transform(subject, xfmname)

# 2. Transform to functional volume to MNI space
func_in_mni = transform_to_mni(datavol, func_to_mni)

# 3. Get data
data = func_in_mni.get_data()

# Get MNI coordinates from JSON file
exp_json = read_json("experiments.json")
示例#21
0
        subject=subject,
        task=task,
        reg=regist_type,
        preproc=preproc)
    img_tc = nb.load(tc_file)
    tc = img_tc.get_fdata()

    # create directory
    webviewer_dir = '{base_dir}/pp_data/{subject}/gauss/pycortex_outputs/webviewer/{subject}_{task}_{reg}_{preproc}_tc'.format(
        base_dir=base_dir,
        subject=subject,
        task=task,
        reg=regist_type,
        preproc=preproc)

    try:
        os.makedirs(webviewer_dir)
    except:
        pass

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

    # create webgl
    print('save pycortex webviewer: time course {}'.format(task))
    cortex.webgl.make_static(outpath=webviewer_dir, data=volume_tc)
示例#22
0
transform = cortex.xfm.Transform(np.identity(4), t1w)
transform.save(pc_subject, 'identity.t1w.v2', 'magnet')

r2 = r2.get_data().T
freq = freq.get_data().T

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')
示例#23
0
import os
import tempfile

import numpy as np
import matplotlib.pyplot as plt

import cortex

subject = 'S1'

###############################################################################
# create some artificial data

shape = cortex.db.get_xfm(subject, 'identity').shape
data = np.arange(np.product(shape)).reshape(shape)
volume = cortex.Volume(data, subject=subject, xfmname='identity')

###############################################################################
# Show examples of multi-panels figures

params = cortex.export.params_flatmap_lateral_medial
cortex.export.plot_panels(volume, **params)
plt.show()

params = cortex.export.params_occipital_triple_view
cortex.export.plot_panels(volume, **params)
plt.show()

###############################################################################
# List all predefined angles
示例#24
0
#cortex.db.get_mask('MNI', 'atlas','thin')
n_v_mni = mask_mni.sum()

errors_files = []

for subject in subjects:
    start = time.time()
    mask = cortex.db.get_mask(surface.format(subject), xfm.format(subject),
                              'thick')
    nr = len(acc.item()['acc'][subject])
    mni_masked[subject] = np.zeros((nr, n_v_mni))
    for ir in range(nr):
        tmp = np.vstack(acc.item()['acc'][subject])[ir]
        vol = np.zeros(mask.shape)
        vol[mask] = tmp
        vol = cortex.Volume(tmp,
                            surface.format(subject),
                            xfm.format(subject),
                            mask=mask)
        try:
            mni_vol = mni.transform_to_mni(
                vol, mni_transforms[subject]).get_data().T
            mni_masked[subject][ir] = mni_vol[mask_mni]
        except:
            errors_files.append('subject {} row {}'.format(subject, ir))
        if ir % 10 == 1:
            print('time_left for {}, {} seconds'.format(
                subject, (time.time() - start) / (ir + 1) * (nr - ir - 1)))

for subject in subjects:
    np.save('bert2_uniform_mni_{}.npy'.format(subject), mni_masked[subject])
示例#25
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()
示例#26
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')
示例#27
0
def test_volumedata_copy():
    v = cortex.Volume(np.random.randn(*volshape), subj, xfmname)
    vc = v.copy(v.data)
    assert np.allclose(v.data, vc.data)
示例#28
0
    def __mean__(self, subjects, do_perm, contrast_results):

        # Prepare volumes
        volumes = {}
        if self.mask_pred:
            for s, cr in zip(subjects, contrast_results):
                mask = s.voxels_predicted
                mask = cortex.Volume(mask, s.name, s.transform)
                s.data[mask.data == True] = -1
                if do_perm:
                    #FIXME which threshold?
                    cr.thresholded_contrast.data[mask.data == True] = -1
                    volumes[cr.subject] = s

        if do_perm:
            if not self.mask_pred:
                volumes = {
                    con_res.subject: con_res.threshold_05
                    for con_res in contrast_results
                }
            else:
                pass
        else:
            volumes = {
                con_res.subject: con_res
                for con_res in contrast_results
            }

        for v in volumes.values():
            v.data = np.nan_to_num(v.data)

        # Re-compute mask
        if self.recomputed_mask:
            # FIXME should it be s.predicted_mask_mni ?
            # s2 = [s.predicted_mask_MNI for s in subjects]
            s2 = [s.predicted_mask_mni for s in subjects]
            self.nan_mask = np.mean(np.stack(s2), axis=0)
            self.nan_mask = self.nan_mask >= 3 / 8.0
            np.save(MNI_MASK_FILE, self.nan_mask)

        mni_volumes = [
            cortex.mni.transform_to_mni(volumes[s.name],
                                        s.func_to_mni).get_data().T
            for s in subjects
        ]

        # Smooth
        if self.smooth is not None:
            Logger.debug("Smoothing with %f mm kernel.." % self.smooth)
            atlasim = nipy.load_image(FSL_DEFAULT_TEMPLATE)
            smoother = nipy.kernel_smooth.LinearFilter(atlasim.coordmap,
                                                       atlasim.shape,
                                                       self.smooth)

            new_mni_volumes = []
            for ml in mni_volumes:
                # Create nipy-style Image from volume
                ml_img = nipy.core.image.Image(ml.T, atlasim.coordmap)
                # Pass it through smoother
                sm_ml_img = smoother.smooth(ml_img)
                # Store the result
                new_mni_volumes.append(sm_ml_img.get_data().T)
            mni_volumes = new_mni_volumes

        # Mean values
        group_mean = np.mean(np.stack(mni_volumes), axis=0)
        group_mean[self.nan_mask == False] = np.nan
        un_nan = np.isnan(group_mean) * self.nan_mask
        group_mean[un_nan] = 0

        max_v_volume = 1 if do_perm or self.do_1pct else 2

        if self.do_1pct:
            th = np.percentile(group_mean[group_mean != 0], 90)
            group_mean = group_mean >= th

        mean_volume = cortex.Volume(group_mean,
                                    'MNI',
                                    'atlas',
                                    vmin=-max_v_volume,
                                    vmax=max_v_volume)

        sub_volumes = [
            cortex.Volume(vol,
                          'MNI',
                          'atlas',
                          vmin=-np.abs(vol).max(),
                          vmax=np.abs(vol).max()) for vol in mni_volumes
        ]

        for sub, vol in zip(subjects, sub_volumes):
            vol.data[sub.predicted_mask_mni == False] = np.nan

        return mean_volume, sub_volumes
示例#29
0
    xfm,
    roi_list=None,  # Default (None) gives all available ROIs in overlays.svg
    gm_sampler=
    'cortical-conservative',  # Select only voxels mostly within cortex
    split_lr=
    True,  # Separate left/right ROIs (this occurs anyway with index volumes)
    threshold=0.9,  # convert probability values to boolean mask for each ROI
    return_dict=False  # return index volume, not dict of masks
)

lim = np.max(np.abs(index_volume))
# Plot the mask for one ROI onto a flatmap
roi_data = cortex.Volume(
    index_volume,
    subject,
    xfm,
    vmin=-lim,  # This is a probability mask, so only
    vmax=lim,  # so scale btw zero and one
    cmap="RdBu_r",  # Shades of blue for L hem, red for R hem ROIs
)

cortex.quickflat.make_figure(
    roi_data,
    thick=1,  # select a single depth (btw white matter & pia)
    sampler='nearest',  # no interpolation
    with_curvature=True,
    with_colorbar=True,
)
print("Index keys for which ROI is which in `index_volume`:")
print(index_keys)
plt.show()
示例#30
0
# Get the map of which voxels are inside of our ROI
roi_masks = cortex.utils.get_roi_masks(
    subject,
    xfm,
    roi_list=[roi],
    gm_sampler=
    'cortical-conservative',  # Select only voxels mostly within cortex
    split_lr=False,  # No separate left/right ROIs
    threshold=None,  # Leave roi mask values as probabilites / fractions
    return_dict=True)

# Plot the mask for one ROI onto a flatmap
roi_data = cortex.Volume(
    roi_masks[roi],
    subject,
    xfm,
    vmin=0,  # This is a probability mask, so only
    vmax=1,  # so scale btw zero and one
    cmap="inferno",  # For pretty
)

cortex.quickflat.make_figure(
    roi_data,
    thick=1,  # select a single depth (btw white matter & pia)
    sampler='nearest',  # no interpolation
    with_curvature=True,
    with_colorbar=True,
)

plt.show()