Ejemplo n.º 1
0
def get_val(sessions=None, masked=True, repeats=False):
    """Retrieves training data for given sessions.
    Default: all sessions, mask applied"""

    if sessions is None:
        sessions = range(3)

    if repeats:
        if isinstance(masked, bool) and masked:
            return tables.openFile(val_file_repeats).getNode("/alldata").read()
        elif isinstance(masked, np.ndarray):
            return tables.openFile(val_file_repeats).getNode("/alldata").read().reshape(270, 30, 10, 100, 100).transpose(0, 1, 3, 4, 2)[:, masked, :]
        else:
            raise Exception("Repeats data is masked")
    else:
        if isinstance(masked, bool) and masked:
            #mask = get_mask()
            mask = cortex.get_cortical_mask("MLfs",
                                            "20121210ML_auto1", "thick")
            return np.concatenate(
                [tables.openFile(t).getNode('/data').read()[:, mask]
                 for t in [val_files[i] for i in sessions]])
        elif isinstance(masked, np.ndarray):
            mask = masked
            return np.concatenate(
                [tables.openFile(t).getNode('/data').read()[:, mask]
                 for t in [val_files[i] for i in sessions]])
        else:
            raise NotImplementedError("This will exceed 4G of RAM")
Ejemplo n.º 2
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)
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
def create_cortical_mask(subject, xfmname, type, epi, temp_dir_cortex):
    import cortex
    import nibabel as nb
    import os#, tempfile

    #tempdir = tempfile.gettempdir()
    try:
        os.makedirs(temp_dir_cortex)
    except OSError:
        pass

    out_file = os.path.join(temp_dir_cortex, 'cortex_%s.nii.gz'%type)

    mask = cortex.get_cortical_mask(subject, xfmname, type=type)
    epi_nii = nb.load(epi)
    dims = epi_nii.shape

    mask_img = nb.Nifti1Image(dataobj=mask.transpose((2,1,0)), affine=epi_nii.affine, header=epi_nii.header)
    
    mask_img.to_filename(out_file)

    return out_file
Ejemplo n.º 5
0
def get_train(sessions=None, masked=True):
    """Retrieves training data for given sessions.
    Default: all sessions, mask applied"""

    if sessions is None:
        sessions = range(3)

    if isinstance(masked, bool) and masked:
        #mask = get_mask()
        mask = cortex.get_cortical_mask("MLfs", "20121210ML_auto1", "thick")
        return np.concatenate(
            [tables.openFile(t).getNode('/data').read()[:, mask]
            for t in [train_files[i] for i in sessions]])
    elif isinstance(masked, np.ndarray):
        mask = masked
        return np.concatenate(
            [tables.openFile(t).getNode('/data').read()[:, mask]
            for t in [train_files[i] for i in sessions]])
    else:
        # raise NotImplementedError("This will exceed 4G of RAM")
        return np.concatenate(
            [tables.openFile(t).getNode('/data').read()
            for t in [train_files[i] for i in sessions]])
Ejemplo n.º 6
0
    glob.glob("{base_dir}/pp_data/{sub}/func/*.nii.gz".format(
        base_dir=base_dir, sub=subject)))
ref_file = file_list[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)
Ejemplo n.º 7
0
    # then, we use the generated flirt matrix to import the subject into the session.
    xfm_data = np.loadtxt(mtx_file)
    xfm = cortex.xfm.Transform.from_fsl(xfm=xfm_data,
                                        func_nii=example_epi_file,
                                        anat_nii=fs_T1_nii_file)
    # # Save as pycortex 'coord' transform
    xfm.save('sub-{subject}'.format(subject=subject), 'fmriprep_T1', 'coord')

    ###################################################################
    ###
    # and, while we're at it, create a cortical mask and save it.
    ###
    ###################################################################

    mask = cortex.get_cortical_mask('sub-{subject}'.format(subject=subject),
                                    'fmriprep_T1',
                                    type='thick')

    epi_nii = nb.load(example_epi_file)
    dims = epi_nii.shape

    mask_img = nb.Nifti1Image(dataobj=mask.transpose((2, 1, 0)),
                              affine=epi_nii.affine,
                              header=epi_nii.header)

    cortical_mask_file = os.path.join(
        base_dir, settings['result_dir'],
        settings['cortical_mask_filename'].format(subject=subject,
                                                  session=settings['session']))
    mask_img.to_filename(cortical_mask_file)
Ejemplo n.º 8
0
 def __init__(self):
     tmp_mni_mask = cortex.get_cortical_mask("MNI", "atlas", "thin")
     self.all_non_zero = np.where(tmp_mni_mask != 0)
     self.mni_dim = tmp_mni_mask.shape
     self.n_mni_voxels = len(self.all_non_zero[0])
Ejemplo n.º 9
0
valstim = data.get_gabor("val").T

delays = [2, 3, 4]
deltrnstim = np.hstack([np.roll(trnstim, d, 0) for d in delays])[:numtime]
delvalstim = np.hstack([np.roll(valstim, d, 0) for d in delays])

#sdeltrnstim = scipy.sparse.csr_matrix(deltrnstim)
#sdelvalstim = scipy.sparse.csr_matrix(delvalstim)

zs = lambda m: (m - m.mean(0)) / m.std(0)

sdeltrnstim = deltrnstim = np.nan_to_num(zs(deltrnstim))
sdelvalstim = delvalstim = np.nan_to_num(zs(delvalstim))

# Select some voxels
cort_mask = cortex.get_cortical_mask("MLfs", "20121210ML_auto1", "thick")
#rois = ["V1", "V2", "V3"]
rois = ["V1"]
masks = [cortex.get_roi_mask("MLfs",
                             "20121210ML_auto1",
                             roi=roi)[roi] > 0 for roi in rois]
roimask = reduce(lambda x, y: (x + y), masks)
wardmask = cort_mask - roimask

# Load training, test fMRI data
trndata_roi = np.nan_to_num(data.get_train(masked=roimask)[:numtime])
trndata_ward = np.nan_to_num(data.get_train(masked=wardmask)[:numtime])

connectivity = image.grid_to_graph(n_x=wardmask.shape[0],
                                   n_y=wardmask.shape[1],
                                   n_z=wardmask.shape[2],