def run_from_args(args):
    img = nibabel.load(args.coord)
    coord = img.get_data()
    white = CorticalMesh.read(args.white)
    dti = nibabel.load(args.dyad).get_data()
    gdti = (coord * dti[..., None]).sum(-2)
    if args.mask is None:
        surf_mask = np.ones(white.nvertices, dtype='bool')
    else:
        surf_mask = nibabel.load(args.mask).darrays[0].data != 0
    idx_vertex = None if args.idx_vertex is None else nibabel.load(args.idx_vertex).get_data()
    if idx_vertex.ndim == 4:
        idx_vertex = idx_vertex[..., 0]
    distance = None if args.distance is None else nibabel.load(args.distance).get_data()
    tofit = model(abs(gdti[..., 0]), white, img.affine, surf_mask, min_dist=args.min_dist, smooth_weight=args.weight,
                  watson=args.watson, idx_vertex=idx_vertex, dist=distance)
    res = pymc3.find_MAP(model=tofit, fmin=optimize.fmin_cg)

    if args.radial_index is not None:
        model_ri = tofit.fastfn(tofit.model_ri_3d)(res)
        obs_ri = tofit.fastfn(tofit.observed_ri_3d)(res)
        nibabel.Nifti1Image(np.stack([model_ri, obs_ri], -1), img.affine).to_filename(args.radial_index)

    bm = cifti.BrainModel.from_surface(np.where(surf_mask)[0], surf_mask.size, white.anatomy.cifti)
    mat = np.stack([res['d0'], res['log_sigma'], np.exp(res['log_sigma'])])
    cifti.write(args.output, mat, (cifti.Scalar.from_names(['offset', 'log_width', 'width']), bm))
Beispiel #2
0
def savemap(name, data, brain_mask, axes, directory="figures"):
    if not os.path.exists(directory):
        os.makedirs(directory)
    file_path = f"{directory}/{name}.dtseries.nii"
    # noinspection PyTypeChecker
    if not isinstance(axes, collections.Iterable):
        axes = (axes, )
    cifti.write(file_path, data, axes + (brain_mask,))
    return os.getcwd() + os.sep + file_path
Beispiel #3
0
def map_regions_pc_cole():
    no_color = (1.0, 1.0, 1.0, 0.0)
    tpt = tpt_cole
    img, (lbl, brain) = cifti.read(tpt.file_full_path)
    regions = lbl.label.item()
    for h in [HierarchyName.EXTENDED_PERIPHERY_CORE, HierarchyName.RESTRICTED_PERIPHERY_CORE]:
        hierarchy = tpt.net_hierarchy(h)
        cp_out = {}
        img_out = np.zeros(img.shape)
        found_regions = {}

        for index, (name, c) in regions.items():
            if index == 0 or index > 360:
                cp_out[index] = name, no_color
                continue

            net, lh = name.split("_")
            net_parts = net.split("-")
            net, rgn = ("".join(net_parts[:2]), net_parts[2]) if len(net_parts) == 3 else net_parts
            is_p = net in hierarchy["P"]
            is_c = net in (hierarchy["RC"] if "RC" in hierarchy else hierarchy["EC"])
            if rgn not in found_regions:
                new_index = len(found_regions) + 1
                found_regions[rgn] = new_index
                if is_p:
                    color = PC_colors_tuple[0]
                elif is_c:
                    color = PC_colors_tuple[1]
                else:
                    color = no_color
                    print(f"{net} without color in {lbl}")
                cp_out[new_index] = rgn, color
            else:
                new_index = found_regions[rgn]

            img_out[img == index] = new_index

        # noinspection PyTypeChecker
        cifti.write(f"figures/cole.{lbl}.dlabel.nii", img_out, (cifti.Label([cp_out]), brain))
        os.system(f"wb_command -cifti-separate figures/cole.{lbl}.dlabel.nii COLUMN "
                  f"-label CORTEX_LEFT figures/cole.{lbl}.L.label.gii "
                  f"-label CORTEX_RIGHT figures/cole.{lbl}.R.label.gii")
        os.system(f"wb_command -label-to-border "
                  f"{get_full_path(AssetCategory.HCP1200, 'anat.midthickness.32k.L.surf.gii')} "
                  f"figures/cole.{lbl}.L.label.gii figures/cole.{lbl}.L.border")
        os.system(f"wb_command -label-to-border "
                  f"{get_full_path(AssetCategory.HCP1200, 'anat.midthickness.32k.R.surf.gii')} "
                  f"figures/cole.{lbl}.R.label.gii figures/cole.{lbl}.R.border")
Beispiel #4
0
def save_to_dtseries(filename, brain_model, mat):
    '''
    saves a dtseries.nii file given the data matrix and the brain model.
    The series axis is generated so as to fit the size of the matrix (every row is a time point).

    :param filename: the file to save
    :param brain_model: a Cifti.Axis.BrainModel object
    :param mat: the data matrix
    :return:
    '''
    if len(np.shape(mat)) == 2:
        assert mat.shape[1] == np.size(brain_model.arr)
    elif len(np.shape(mat)) == 1:
        mat = np.reshape(mat, [1, np.size(brain_model.arr)])
    series = cifti.Series(start=0, step=1, size=mat.shape[0])
    if not filename.endswith(".dtseries.nii"):
        filename += ".dtseries.nii"
    gb.curr_cifti_filenames.append(filename)
    cifti.write(filename, mat, (series, brain_model))
    return filename
Beispiel #5
0
def save_brainimg(imgpath, data, header):
    """
    Save brain image identified by its suffix
    suffix now support
     
    Nifti: .nii.gz
    freesurfer: .mgz, .mgh
    cifti: .dscalar.nii, .dlabel.nii, .dtseries.nii
        
    Parameters:
    ------------
    imgpath: brain image path to be saved
    data: brain image data matrix
    header: brain image header
        
    Returns:
    --------
    """
    imgname = os.path.basename(imgpath)
    imgsuffix = imgname.split('.')[1:]
    imgsuffix = '.'.join(imgsuffix)

    if imgsuffix == 'nii.gz':
        data = np.transpose(data, (1, 2, 3, 0))
        outimg = nib.Nifti1Image(data, None, header)
        nib.save(outimg, imgpath)
    elif imgsuffix == 'mgz' or imgsuffix == 'mgh':
        data = np.transpose(data, (1, 2, 3, 0))
        outimg = nib.MGHImage(data, None, header)
        nib.save(outimg, imgpath)
    elif imgsuffix == 'dscalar.nii' or imgsuffix == 'dlabel.nii' or imgsuffix == 'dtseries.nii':
        data = data[..., 0, 0]
        map_name = [''] * data.shape[0]
        bm_full = header[1]
        cifti.write(imgpath, data,
                    (cifti.Scalar.from_names(map_names), bm_full))
    else:
        raise Exception(
            'Not support this format of brain image data, please contact with author to update this function.'
        )
Beispiel #6
0
def map_nets_sh2007():
    tpt = tpt_sh
    img, (lbl, brain) = cifti.read(tpt.file_full_path)
    regions = lbl.label.item()

    net_out = {}
    img_out = np.zeros(img.shape)

    nets = tpt.net_order
    palette = tpt.net_colors
    for index, (name, c) in regions.items():
        if index == 0:
            net_out[index] = name, c
            continue

        network = name.split("_")[2]
        net_index = nets.index(network) + 1
        if net_index not in net_out:
            net_out[net_index] = network, palette[net_index - 1] + [1, ]
        img_out[img == index] = net_index
    # noinspection PyTypeChecker
    cifti.write(f"figures/sh7nets.dlabel.nii", img_out, (cifti.Label([net_out]), brain))
Beispiel #7
0
def map_regions_pc_sh2007():
    tpt = tpt_sh
    img, (lbl, brain) = cifti.read(tpt.file_full_path)
    regions = lbl.label.item()
    hierarch = tpt.net_hierarchy(HierarchyName.PERIPHERY_CORE)
    cp_out = {}
    img_out = np.zeros(img.shape)
    found_regions = {}

    for index, (name, c) in regions.items():
        if index == 0:
            cp_out[index] = name, c
            continue

        parts = name.split("_")
        lr, network, rgn, num = parts[1], parts[2], parts[-2], parts[-1]
        cp = 0 if network in hierarch["P"] else 1
        if rgn not in found_regions:
            new_index = len(found_regions) + 1
            found_regions[rgn] = new_index
            cp_out[new_index] = rgn, PC_colors_tuple[cp]
        else:
            new_index = found_regions[rgn]

        img_out[img == index] = new_index

    # noinspection PyTypeChecker
    cifti.write(f"figures/sh7cp.dlabel.nii", img_out, (cifti.Label([cp_out]), brain))
    os.system(f"wb_command -cifti-separate figures/sh7cp.dlabel.nii COLUMN "
              f"-label CORTEX_LEFT figures/sh7cp.L.label.gii "
              f"-label CORTEX_RIGHT figures/sh7cp.R.label.gii")
    os.system(f"wb_command -label-to-border "
              f"{get_full_path(AssetCategory.HCP1200, 'anat.midthickness.32k.L.surf.gii')} "
              f"figures/sh7cp.L.label.gii figures/sh7cp.L.border")
    os.system(f"wb_command -label-to-border "
              f"{get_full_path(AssetCategory.HCP1200, 'anat.midthickness.32k.R.surf.gii')} "
              f"figures/sh7cp.R.label.gii figures/sh7cp.R.border")
Beispiel #8
0
def map_nets_cole():
    tpt = tpt_cole
    img, (lbl, brain) = cifti.read(tpt.file_full_path)
    regions = lbl.label.item()

    net_out = {}
    img_out = np.zeros(img.shape)

    nets = tpt.net_order
    palette = tpt.net_colors
    for index, (name, c) in regions.items():
        if index == 0:
            net_out[index] = name, c
            continue

        network, lh = name.split("_")
        net_parts = network.split("-")
        network, rgn = ("".join(net_parts[:2]), net_parts[2]) if len(net_parts) == 3 else net_parts
        net_index = nets.index(network) + 1
        if net_index not in net_out:
            net_out[net_index] = network, palette[net_index - 1] + [1, ]
        img_out[img == index] = net_index
    # noinspection PyTypeChecker
    cifti.write(f"figures/colenets.dlabel.nii", img_out, (cifti.Label([net_out]), brain))
Beispiel #9
0
    dd = dd - np.mean(dd,axis=0)
    next = (dd * normproj).A
    hypsource[hemi] = next
    zscore(hypsource[hemi],chunks_attr=None)
    finalproj[hemi] = normproj
    t2 = time.time()
    print('Hyperalignment for %s hemisphere took %s minutes' % (hemi, ((t2-t1)/60.)))

# Apply projections to other tasks:
# tasks = ['rfMRI_REST2','tfMRI_WM','tfMRI_GAMBLING','tfMRI_LANGUAGE','tfMRI_MOTOR','tfMRI_RELATIONAL','tfMRI_SOCIAL']
tasks = ['tfMRI_RELATIONAL']
for task in tasks:
    for ses in ['LR','RL']:
        if task == 'rfMRI_REST2':
            cname = '%s/%s/%s_%s/%s_%s_10k_Atlas_MSMAll_clean_24nuisance.reg_lin.trend_filt_sm6' % (tempdir,sub,task,ses,task,ses)
        else:
            cname = '%s/%s/%s_%s/%s_%s_Atlas_MSMAll_10k_anat_cortex' % (tempdir,sub,task,ses,task,ses)
        
        tmpimg =cifti.read('%s.dtseries.nii' % cname)
        tmpwrite = tmpimg[0].copy()
        nvols = tmpimg[0].shape[0]
        for hemi in ['L','R']:
            nverts = len(ind[hemi])
            blank = np.zeros([nvols,nverts])
            img = tmpimg[0][:,ind[hemi]]
            img = img[:,maskimg[hemi]]
            himg1 = img.dot(finalproj[hemi])
            blank[:,maskimg[hemi]] = himg1
            tmpwrite[:,ind[hemi]] = blank
        cifti.write('%s/%s/%s_%s/%s_%s_Atlas_MSMAll_10k_R1LRRL_hyp.dtseries.nii' % (tempdir,sub,task,ses,task,ses),tmpwrite,tmpimg[1])
    hypsource[hemi] = next
    zscore(hypsource[hemi], chunks_attr=None)
    finalproj[hemi] = normproj
    t2 = time.time()
    print('Hyperalignment for %s hemisphere took %s minutes' %
          (hemi, ((t2 - t1) / 60.)))

# Apply projections to other tasks:
tasks = [
    'rfMRI_REST2', 'tfMRI_WM', 'tfMRI_GAMBLING', 'tfMRI_LANGUAGE',
    'tfMRI_MOTOR', 'tfMRI_RELATIONAL', 'tfMRI_SOCIAL'
]
for task in tasks:
    for ses in ['LR', 'RL']:
        cname = '%s/%s/%s_%s/%s_%s_10k_Atlas_MSMAll_clean_24nuisance.reg_lin.trend_filt_sm6' % (
            tempdir, sub, task, ses, task, ses)
        tmpimg = cifti.read('%s.dtseries.nii' % cname)
        tmpwrite = tmpimg[0].copy()
        nvols = tmpimg[0].shape[0]
        for hemi in ['L', 'R']:
            nverts = len(ind[hemi])
            blank = np.zeros([nvols, nverts])
            img = tmpimg[0][:, ind[hemi]]
            img = img[:, maskimg[hemi]]
            himg1 = img.dot(finalproj[hemi])
            blank[:, maskimg[hemi]] = himg1
            tmpwrite[:, ind[hemi]] = blank
        cifti.write(
            '%s/%s/%s_%s/%s_%s_10k_Atlas_MSMAll_clean_24nuisance.reg_lin.trend_filt_sm6_R1LRRL_hyp.dtseries.nii'
            % (tempdir, sub, task, ses, task, ses), tmpwrite, tmpimg[1])