Exemple #1
0
def plot_connectome(mat, label_map, threshold='95%', GS=True):

    if GS:
        mat = mat[1:, 1:]  #fisrt row and column is global signal
    coords = plotting.find_parcellation_cut_coords(label_map)
    view = plotting.view_connectome(mat, coords, threshold=threshold)
    view.open_in_browser()
Exemple #2
0
def get_names_and_coords_of_parcels(uatlas):
    """
    Return list of coordinates and max label intensity for a 3D atlas parcellation image.

    Parameters
    ----------
    uatlas : str
        File path to atlas parcellation Nifti1Image in MNI template space.

    Returns
    -------
    coords : list
        List of (x, y, z) tuples corresponding to the center-of-mass of each parcellation node.
    atlas : str
        An arbitrary identified for the atlas based on the filename.
    par_max : int
        The maximum label intensity in the parcellation image.
    """
    import os.path as op
    from nilearn.plotting import find_parcellation_cut_coords
    if not op.isfile(uatlas):
        raise ValueError(
            '\nERROR: User-specified atlas input not found! Check that the file(s) specified with the -ua '
            'flag exist(s)')

    atlas = uatlas.split('/')[-1].split('.')[0]
    [coords,
     label_intensities] = find_parcellation_cut_coords(uatlas,
                                                       return_label_names=True)
    print("%s%s" % ('Region intensities:\n', label_intensities))
    par_max = len(coords)

    return coords, atlas, par_max
Exemple #3
0
def get_names_and_coords_of_parcels(uatlas_select):
    from nilearn.plotting import find_parcellation_cut_coords
    atlas_select = uatlas_select.split('/')[-1].split('.')[0]
    [coords,
     label_intensities] = find_parcellation_cut_coords(uatlas_select,
                                                       return_label_names=True)
    print("%s%s" % ('Region intensities:\n', label_intensities))
    par_max = len(coords)
    return coords, atlas_select, par_max
Exemple #4
0
def plot_connectome_mixture(data=None, index=None, metric="correlation", save_as=None, show=False, **kwargs):
   
    # extract time series from all subjects and concatenate them
    mm = data.X[index, :].copy()
    time_series = [np.vstack(mm)]

    # calculate correlation matrices across indexed frames in data 
    connectome_measure = ConnectivityMeasure(kind=metric)
    connectome_measure.fit_transform(time_series)
    connectivity = connectome_measure.mean_
    np.fill_diagonal(connectivity, 0)
    #connectivity[np.abs(connectivity) < 0.2] = 0.0 


    # grab center coordinates for atlas labels
    atlas = kwargs.pop('atlas', data.atlas)
    coords = plotting.find_parcellation_cut_coords(labels_img=atlas)

    # assign node colors
    cmap = kwargs.pop('cmap', 'jet')
    node_cmap = plt.get_cmap('bone')
    node_norm = mpl.colors.Normalize(vmin=-0.8, vmax=1.2)
    node_colors = np.ravel([_[-1] for i,_ in enumerate(coords)])
    node_colors = [_ / np.max(node_colors) for _ in node_colors]
    node_colors = node_cmap(node_norm(node_colors))

    # plot connectome matrix
    fig = plt.figure(figsize=(12,5))
    ax = plt.subplot2grid((1, 2), (0, 1),  rowspan=1, colspan=1) 
    display = plotting.plot_matrix(
        connectivity,
        vmin=-.5, vmax=.5, colorbar=True, cmap=cmap,
        axes=ax, #title='{} Matrix'.format(metric.title()),
        )

    # plot connectome with 99.7% edge strength in the connectivity
    ax = plt.subplot2grid((1, 2), (0, 0), rowspan=1, colspan=1)
    display = plotting.plot_connectome(
        connectivity, coords,
        edge_threshold="99.9%", display_mode='z',
        node_color=node_colors, node_size=20, edge_kwargs=dict(lw=4),
        edge_vmin=-.8, edge_vmax=.8, edge_cmap=cmap,
        colorbar=False, black_bg=not True, alpha=0.5,
        annotate=False,
        axes=ax,
        )
    if show is True:
        plt.show()
    plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95)
    if save_as:
        fig.savefig(save_as, transparent=True)#, facecolor='slategray', edgecolor='white')
    plt.close(fig)
    return display
Exemple #5
0
def get_names_and_coords_of_parcels(uatlas_select):
    import os.path as op
    from nilearn.plotting import find_parcellation_cut_coords
    if not op.isfile(uatlas_select):
        raise ValueError(
            '\nERROR: User-specified atlas input not found! Check that the file(s) specified with the -ua '
            'flag exist(s)')

    atlas_select = uatlas_select.split('/')[-1].split('.')[0]
    [coords,
     label_intensities] = find_parcellation_cut_coords(uatlas_select,
                                                       return_label_names=True)
    print("%s%s" % ('Region intensities:\n', label_intensities))
    par_max = len(coords)
    return coords, atlas_select, par_max
Exemple #6
0
def nbs_and_graphs(corr1, corr2, p_thresh, k, atlas, verbose):
    coordinates = plotting.find_parcellation_cut_coords(labels_img=atlas)
    corr1 = np.asarray(corr1, dtype="float")
    corr2 = np.asarray(corr2, dtype="float")

    if corr1.shape[0] != corr1.shape[1]:
        corr1 = np.moveaxis(corr1, 0, -1)
        corr2 = np.moveaxis(corr2, 0, -1)

    thresh = stats.t.isf(p_thresh, corr1.shape[2])
    pval, adj, _ = bct.nbs_bct(
        corr1, corr2, thresh, k=k, tail="both", paired=True, verbose=verbose
    )
    print(pval)
    gridkw = dict(width_ratios=[1, 2])
    fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw=gridkw, figsize=(15, 4))

    g = sns.heatmap(adj, square=True, ax=ax1, cmap="Greys")
    h = plotting.plot_connectome_strength(
        adj, node_coords=coordinates, cmap="YlGnBu", axes=ax2
    )

    return pval, adj, fig
Exemple #7
0
def parcellation_data():
    """Fixture for parcellations."""
    parcels_tmp = tempfile.NamedTemporaryFile(mode='w+', suffix='.nii.gz')
    labels = pd.DataFrame({"label":
                           list(map("label_{}".format,
                                    range(16)))})['label'].values.tolist()
    parcellation = data_gen.generate_labeled_regions((7, 6, 5), 16)
    parcels = parcellation.get_fdata()
    net_parcels_map_nifti_file = str(parcels_tmp.name)
    parcellation.to_filename(net_parcels_map_nifti_file)

    [coords, indices] = find_parcellation_cut_coords(parcellation,
                                                     0,
                                                     return_label_names=True)
    coords = list(tuple(x) for x in coords)

    yield {
        'net_parcels_map_nifti_file': net_parcels_map_nifti_file,
        'parcels': parcels,
        'labels': labels,
        'coords': coords,
        'indices': indices
    }
    parcels_tmp.close()
Exemple #8
0
                           memory='nilearn_cache')

# extract time series from all subjects and concatenate them
time_series = []
for func, confounds in zip(data.func, data.confounds):
    time_series.append(masker.fit_transform(func, confounds=confounds))

# calculate correlation matrices across subjects and display
correlation_matrices = connectome_measure.fit_transform(time_series)

# Mean correlation matrix across 10 subjects can be grabbed like this,
# using connectome measure object
mean_correlation_matrix = connectome_measure.mean_

# grab center coordinates for atlas labels
coordinates = plotting.find_parcellation_cut_coords(labels_img=yeo['thick_17'])

# plot connectome with 80% edge strength in the connectivity
plotting.plot_connectome(mean_correlation_matrix,
                         coordinates,
                         edge_threshold="80%",
                         title='Yeo Atlas 17 thick (func)')

##########################################################################
# Plot a directed connectome - asymmetric connectivity measure
# -----------------------------------------------------------------
# In this section, we use the lag-1 correlation as the connectivity
# measure, which leads to an asymmetric connectivity matrix.
# The plot_connectome function accepts both symmetric and asymmetric
# matrices, but plot the latter as a directed graph.
import numpy as np
    sig["Male students, post: {0}, phys retr".format(iq)] = np.max(p[0])

    p, t, _ = permuted_ols(
        all_data["delta{0}".format(iq)].values,
        all_data[conns].values,
        all_data[["Age", "Mod", "Strt.Level", "post phys retr fd"]].values,
    )
    sig["Male students, delta: {0}, phys retr".format(iq)] = np.max(p[0])
# -

for key in sig.keys():
    if sig[key] >= 1:
        print(key, sig[key])

coordinates = find_parcellation_cut_coords(
    labels_img=
    "/Users/Katie/Dropbox/Data/templates/shen2015/shen_triplenetwork.nii.gz")

# +
sig_f = {"PRI": ["pre rest", f_rest_pre]}

for key in sig_f.keys():
    f_conns = sig_f[key][1]
    iq = key
    task = sig_f[key][0]
    print(iq, task)
    all_data = pd.concat([big_df, f_conns], axis=1)
    all_data.dropna(how="any", axis=0, inplace=True)

    conns = list(set(f_conns.columns))
Exemple #10
0
                 '/*.nii.gz'))  #sort to irr0..19, pse0..19, reg0..19
        betas_per_roi = extract_region_values(
            files, cc200_path
        )  #get mean beta value per roi for each stimulus [200,60]
        subj = hf.create_group('/visit2/' + sub_id)
        subj.create_dataset('betas_rois', data=betas_per_roi)


if __name__ == '__main__':
    v1_path = '/usr/share/datasets/SCHOOLS/SCHBNOVO/BETAS_7s/'
    v2_path = '/usr/share/datasets/acerta_data/acerta_TASK/SCHOOLS_Betas/visit2/'
    v1_folders = glob(v1_path + 'betas*')
    v2_folders = glob(v2_path + '*')

    cc200_path = '/home/marcon/datasets/acerta_data/Masks/shen_1mm_268_resampled.nii.gz'
    cc200_coords = plotting.find_parcellation_cut_coords(labels_img=cc200_path)

    hf = h5py.File('betas_new_data.hdf5', 'w')
    hf.create_dataset('coordinates', data=cc200_coords)
    g1 = hf.create_group('visit1')
    g2 = hf.create_group('visit2')

    #store visit1 values
    for subject_folder in v1_folders:
        sub_id = subject_folder.split('_')[-1]
        print("Processing subject: ", sub_id)
        files = sorted(glob(subject_folder +
                            '/*.nii'))  #sort to irr0..19, pse0..19, reg0..19
        betas_per_roi = extract_region_values(
            files, cc200_path
        )  #get mean beta value per roi for each stimulus [200,60]
@author: Or Duek
Check Aging data connectivity
"""

import os
import pandas as pd
from nilearn import plotting
from connUtils import removeVars, timeSeriesSingle, createCorMat

## set atlas (Here I use Yeo, but can use Shen or any other)

atlas_filename = '/home/or/Downloads/1000subjects_reference_Yeo/Yeo_JNeurophysiol11_SplitLabels/MNI152/Yeo2011_17Networks_N1000.split_components.FSL_MNI152_1mm.nii.gz'
atlas_labes = pd.read_csv(
    '/home/or/Downloads/1000subjects_reference_Yeo/Yeo_JNeurophysiol11_SplitLabels/Yeo2011_17networks_N1000.split_components.glossary.csv'
)
coords = coords = plotting.find_parcellation_cut_coords(
    labels_img=atlas_filename)
# take one subjects file
# for this one I use the AROMA non aggresive one, as it is already "cleanded" (i.e. no need to remove confounds)
func_file = '/media/Data/Aging/Preprocessed_data/aging_output/fmriprep/sub-010/ses-1/func/sub-010_ses-1_task-rest_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz'
confound_file = '/media/Data/Aging/Preprocessed_data/aging_output/fmriprep/sub-010/ses-1/func/sub-010_ses-1_task-rest_desc-confounds_regressors.tsv'

timeSer = timeSeriesSingle(func_file, confound_file, atlas_filename)

from nilearn.connectome import ConnectivityMeasure
correlation_measure = ConnectivityMeasure(
    kind='correlation')  # can choose partial - it might be better
correlation_matrix = correlation_measure.fit_transform([timeSer])[0]

plotting.plot_matrix(correlation_matrix)

plotting.plot_connectome(correlation_matrix,
import pickle
import time
import re
import pandas as pd
import glob
from nilearn import plotting

# Import function
os.chdir(
    '/Users/senna/course/Mladen/project/pro3/BiometrikaRevision/simu/realdata')
# import label and coordinate
Lab = pd.read_csv(os.getcwd() + '/data/Output/labels.csv',
                  index_col=0)['0'].tolist()[1:]
f = open(os.getcwd() + '/data/atlas.txt', "r")
atlas = f.read().splitlines()[0]
Coor = plotting.find_parcellation_cut_coords(labels_img=atlas)
f.close()

# load our result
mySparse = pd.read_csv(os.getcwd() + '/mymethod/MyResult/mySparse.csv',
                       index_col=0).values

#################################
########### Plot     ############
#################################

# show brain

# plot connectome with 80% edge strength in the connectivity
fig = plotting.plot_connectome(mySparse,
                               Coor,
def AtlasParcellation(path, is_probabilistic=False):
    if is_probabilistic:
        return plotting.find_probabilistic_atlas_cut_coords(maps_img=path)
    else:
        return plotting.find_parcellation_cut_coords(labels_img=path)
Exemple #14
0
##########################################################################
# Iterate over fetched atlases to extract coordinates
# ---------------------------------------------------
for name, (atlas, threshold) in sorted(atlases_and_thresholds.items()):
    # create masker to extract functional data within atlas parcels
    masker = NiftiLabelsMasker(labels_img=atlas,
                               standardize=True,
                               memory='nilearn_cache')

    # extract time series from all subjects and concatenate them
    time_series = []
    for func, confounds in zip(data.func, data.confounds):
        time_series.append(masker.fit_transform(func, confounds=confounds))

    time_series = np.concatenate(time_series)

    # calculate correlation matrix and display
    correlation_matrix = np.corrcoef(time_series.T)

    # grab center coordinates for atlas labels
    coordinates = plotting.find_parcellation_cut_coords(atlas)

    # plot connectome
    plotting.plot_connectome(correlation_matrix,
                             coordinates,
                             edge_threshold=threshold,
                             title=name)

plotting.show()
    for jj in range(0,len(idlist)):
        allfd[jj] = allsubjdenoised.meanFD[np.where(allsubjdenoised.participant_id==idlist[jj])[0]]
    for jj in range(0, len(lowertri[0])):
        pearsonobj  = sp.stats.pearsonr(allfd,graphs[:,lowertri[0][jj],lowertri[1][jj]])
        qcfc_fdr[ii,lowertri[0][jj],lowertri[1][jj]] = pearsonobj[0]
        qcfc_fdp[ii,lowertri[0][jj],lowertri[1][jj]] = pearsonobj[1] 
    qcfc_fdr[ii,:,:] = qcfc_fdr[ii,:,:] + qcfc_fdr[ii,:,:].transpose()
    qcfc_fdp[ii,:,:] = qcfc_fdp[ii,:,:] + qcfc_fdp[ii,:,:].transpose()
    qcfc_fdm[ii]     = np.nanmedian(qcfc_fdr[ii,:,:])
    qcfc_fdq[ii]     = np.sum(qcfc_fdp[ii,]<pthr) / np.prod(qcfc_fdp[ii,].shape) * 100

    ##--- QC-FC distance-dependence (per Parkes et al., 2018; NeuroImage)
    if atlasis4d:
       atlas_region_coords = plotting.find_probabilistic_atlas_cut_coords(atlas)
    else:
       atlas_region_coords = plotting.find_parcellation_cut_coords(atlas)
    alldists = np.zeros((atlas_region_coords.shape[0],atlas_region_coords.shape[0]))
    for jj in range(0, len(atlas_region_coords)):
        for kk in range(0, len(atlas_region_coords)):
            alldists[jj,kk] = np.linalg.norm(atlas_region_coords[jj,]-atlas_region_coords[kk,])
    qcfc = np.tril(np.mean(graphs,axis=0),-1).ravel()
    dist = np.tril(              alldists,-1).ravel()
    qcfc = np.delete(qcfc, np.where(qcfc==0))
    dist = np.delete(dist, np.where(dist==0))
    spearmanobj = sp.stats.spearmanr(a=dist,b=qcfc,nan_policy='omit')
    qcfc_ddr[ii] = spearmanobj.correlation
    qcfc_ddp[ii] = spearmanobj.pvalue

    ##--- QC-FC association with temporal degrees of freedom loss
    tdof_lsm[ii] = np.mean(allsubjdenoised.PctDFlost) * 100
    tdof_lsv[ii] = np.std(allsubjdenoised.PctDFlost)  * 100 
    hf.close()
    print("Done.")


if __name__ == '__main__':
    data_path = '/home/marcon/datasets/acerta_data/'
    visit1_paths = glob(data_path + 'acerta_RST/SCHOOLS/visit1/' + '*nii.gz')
    visit2_paths = glob(data_path + 'acerta_RST/SCHOOLS/visit2/' + '*nii.gz')
    output_filename = 'RST_timeseries_pruned.hdf5'

    mask_path = data_path + 'Masks/HaskinsPeds_NL_template_3x3x3_maskRESAMPLED.nii'
    atlas_path = data_path + 'Masks/HaskinsPeds_NL_atlasRESAMPLED1.0.nii'
    shen268_path = data_path + 'Masks/shen_1mm_268_resampled.nii.gz'

    shen268_coords = plotting.find_parcellation_cut_coords(
        labels_img=shen268_path)

    ts1 = get_region_timeseries(visit1_paths, shen268_path)
    ts2 = get_region_timeseries(visit2_paths, shen268_path)

    pruned_ts1, pruned_ts2 = prune_timeseries(ts1, ts2)

    # print("Computing correlation matrices")
    # cn_mx1 = get_correlation_matrix(ts1)
    # cn_mx2 = get_correlation_matrix(ts2)

    create_hd5(visit1_paths, visit2_paths, pruned_ts1, pruned_ts2,
               shen268_coords, output_filename)
    # create_hd5(visit1_paths,visit2_paths,cn_mx1,cn_mx2,shen268_coords)
Exemple #17
0
import nilearn
import numpy as np
import pylab as plt
import scipy.io as sio
from nilearn import plotting

# load connectome hagmann 2008 data ---------------------------------
mat_cont = sio.loadmat("matfile/hagmann_998.mat")
C = mat_cont['CIJ_fbden_average']
L = mat_cont['CIJ_edgelength_average']
xyz = mat_cont['talairach']

# get atlas data ----------------------------------------------------
destrieux = nilearn.datasets.fetch_atlas_destrieux_2009()
coordinates, int_labels = plotting.find_parcellation_cut_coords(
    destrieux['maps'], return_label_names=True)

print(coordinates.shape)  # (148, 3)
print(len(int_labels))  # 143
np.savetxt("data/destrieux_2009_coordinates.txt", coordinates, fmt="%18.9f")

# extracting labels of each resion ----------------------------------
labels_int_string = [[
    destrieux.labels[i][0], destrieux.labels[i][1].decode('UTF-8')
] for i in range(1, len(destrieux.labels))]

ofile = open("data/destrieux_2009_labels.txt", "w")
int_labels_dest = [
    destrieux.labels[j][0] for j in range(len(destrieux.labels))
]
my_list = []
 def get_mni_node_coordinates(self):
     """Retrieve node coordinates in MNI space from MNI parcellated brain
     """
     image = nib.load(self.parcellated_image_path)
     self.coordinates = plotting.find_parcellation_cut_coords(image)
Exemple #19
0
def structural_plotting(conn_matrix,
                        uatlas,
                        streamlines_mni,
                        template_mask,
                        interactive=False):
    """

    :param conn_matrix:
    :param uatlas:
    :param streamlines_mni:
    :param template_mask:
    :param interactive:
    :return:
    """
    import nibabel as nib
    import numpy as np
    import networkx as nx
    import os
    import pkg_resources
    from nibabel.affines import apply_affine
    from fury import actor, window, colormap, ui
    from dipy.tracking.utils import streamline_near_roi
    from nilearn.plotting import find_parcellation_cut_coords
    from nilearn.image import resample_to_img
    from pynets.thresholding import normalize
    from pynets.nodemaker import mmToVox

    ch2better_loc = pkg_resources.resource_filename(
        "pynets", "templates/ch2better.nii.gz")

    # Instantiate scene
    r = window.Renderer()

    # Set camera
    r.set_camera(position=(-176.42, 118.52, 128.20),
                 focal_point=(113.30, 128.31, 76.56),
                 view_up=(0.18, 0.00, 0.98))

    # Load atlas rois
    atlas_img = nib.load(uatlas)
    atlas_img_data = atlas_img.get_data()

    # Collapse list of connected streamlines for visualization
    streamlines = nib.streamlines.load(streamlines_mni).streamlines
    parcels = []
    i = 0
    for roi in np.unique(atlas_img_data)[1:]:
        parcels.append(atlas_img_data == roi)
        i = i + 1

    # Add streamlines as cloud of 'white-matter'
    streamlines_actor = actor.line(streamlines,
                                   colormap.create_colormap(np.ones(
                                       [len(streamlines)]),
                                                            name='Greys_r',
                                                            auto=True),
                                   lod_points=10000,
                                   depth_cue=True,
                                   linewidth=0.2,
                                   fake_tube=True,
                                   opacity=1.0)
    r.add(streamlines_actor)

    # Creat palette of roi colors and add them to the scene as faint contours
    roi_colors = np.random.rand(int(np.max(atlas_img_data)), 3)
    parcel_contours = []
    i = 0
    for roi in np.unique(atlas_img_data)[1:]:
        include_roi_coords = np.array(np.where(atlas_img_data == roi)).T
        x_include_roi_coords = apply_affine(np.eye(4), include_roi_coords)
        bool_list = []
        for sl in streamlines:
            bool_list.append(
                streamline_near_roi(sl,
                                    x_include_roi_coords,
                                    tol=1.0,
                                    mode='either_end'))
        if sum(bool_list) > 0:
            print('ROI: ' + str(i))
            parcel_contours.append(
                actor.contour_from_roi(atlas_img_data == roi,
                                       color=roi_colors[i],
                                       opacity=0.2))
        else:
            pass
        i = i + 1

    for vol_actor in parcel_contours:
        r.add(vol_actor)

    # Get voxel coordinates of parcels and add them as 3d spherical centroid nodes
    [coords, labels] = find_parcellation_cut_coords(atlas_img,
                                                    background_label=0,
                                                    return_labels=True)

    coords_vox = []
    for i in coords:
        coords_vox.append(mmToVox(atlas_img.affine, i))
    coords_vox = list(set(list(tuple(x) for x in coords_vox)))

    # Build an edge list of 3d lines
    G = nx.from_numpy_array(normalize(conn_matrix))
    for i in G.nodes():
        nx.set_node_attributes(G, {i: coords_vox[i]}, labels[i])

    G.remove_nodes_from(list(nx.isolates(G)))
    G_filt = nx.Graph()
    fedges = filter(lambda x: G.degree()[x[0]] > 0 and G.degree()[x[1]] > 0,
                    G.edges())
    G_filt.add_edges_from(fedges)

    coord_nodes = []
    for i in range(len(G.edges())):
        edge = list(G.edges())[i]
        [x, y] = edge
        x_coord = list(G.nodes[x].values())[0]
        x_label = list(G.nodes[x].keys())[0]
        l_x = actor.label(text=str(x_label),
                          pos=x_coord,
                          scale=(1, 1, 1),
                          color=(50, 50, 50))
        r.add(l_x)
        y_coord = list(G.nodes[y].values())[0]
        y_label = list(G.nodes[y].keys())[0]
        l_y = actor.label(text=str(y_label),
                          pos=y_coord,
                          scale=(1, 1, 1),
                          color=(50, 50, 50))
        r.add(l_y)
        coord_nodes.append(x_coord)
        coord_nodes.append(y_coord)
        c = actor.line([(x_coord, y_coord)],
                       window.colors.coral,
                       linewidth=100 * (float(G.get_edge_data(x, y)['weight']))
                       ^ 2)
        r.add(c)

    point_actor = actor.point(list(set(coord_nodes)),
                              window.colors.grey,
                              point_radius=0.75)
    r.add(point_actor)

    # Load glass brain template and resample to MNI152_2mm brain
    template_img = nib.load(ch2better_loc)
    template_target_img = nib.load(template_mask)
    res_brain_img = resample_to_img(template_img, template_target_img)
    template_img_data = res_brain_img.get_data().astype('bool')
    template_actor = actor.contour_from_roi(template_img_data,
                                            color=(50, 50, 50),
                                            opacity=0.05)
    r.add(template_actor)

    # Show scene
    if interactive is True:
        window.show(r, size=(600, 600), reset_camera=False)
    else:
        fig_path = os.path.dirname(streamlines_mni) + '/3d_connectome_fig.png'
        window.record(r, out_path=fig_path, size=(600, 600))

    return
Exemple #20
0
    #     # vol_actor.AddObserver('LeftButtonPressEvent',
    #     #                       point_left_click_callback,
    #     #                       1.0)
    #     scene.add(vol_actor)

    # Load glass brain template and resample to MNI152_2mm brain
    template_img = nib.load(ch2bet)
    template_target_img = nib.load(ch2bet_target)
    res_brain_img = resample_to_img(template_img, template_target_img)
    template_img_data = res_brain_img.get_data().astype('bool')
    template_actor = actor.contour_from_roi(template_img_data, color=(50, 50, 50), opacity=0.05)
    scene.add(template_actor)
    visible_callback.brain_actor = template_actor

    # Get voxel coordinates of parcels and add them as 3d spherical centroid nodes
    [coords, label_names] = find_parcellation_cut_coords(atlas_img, background_label=0, return_label_names=True)

    coords_vox = []
    for i in coords:
        coords_vox.append(mmToVox(atlas_img, i))
    coords_vox = list(set(list(tuple(x) for x in coords_vox)))

    # Build an edge list of 3d lines
    df = pd.read_csv(graph_properties)
    node_cols = [s for s in list(df.columns) if isinstance(s, int) or any(c.isdigit() for c in s)]

    conn_matrix = np.load(conn_matrix_path)
    conn_matrix = normalize(conn_matrix)
    G = nx.from_numpy_array(conn_matrix)

    # Add adj. mat
                           memory='nilearn_cache')

# extract time series from all subjects and concatenate them
time_series = []
for func, confounds in zip(data.func, data.confounds):
    time_series.append(masker.fit_transform(func, confounds=confounds))

# calculate correlation matrices across subjects and display
correlation_matrices = connectome_measure.fit_transform(time_series)

# Mean correlation matrix across 10 subjects can be grabbed like this,
# using connectome measure object
mean_correlation_matrix = connectome_measure.mean_

# grab center coordinates for atlas labels
coordinates = plotting.find_parcellation_cut_coords(labels_img=yeo['thick_17'])

# plot connectome with 80% edge strength in the connectivity
plotting.plot_connectome(mean_correlation_matrix, coordinates,
                         edge_threshold="80%",
                         title='Yeo Atlas 17 thick (func)')

##########################################################################
# Load probabilistic atlases - extracting coordinates on brain maps
# -----------------------------------------------------------------

msdl = datasets.fetch_atlas_msdl()

##########################################################################
# Iterate over fetched atlases to extract coordinates - probabilistic
# -------------------------------------------------------------------
    "fd",
]
index = pd.MultiIndex.from_product([masks.keys(), tasks.keys(), variables])
sig = pd.DataFrame(index=index)

# running each permuted OLS regression this many times
n_perm = 10000
# creating figures automatically for regressions with significant edges
node_size = 10

# run all regressions for all task-IQ combos once for each parcellation
for mask in masks.keys():
    # for making connectome figures, read in the relevant parcellation
    mask_nii = masks[mask]
    # and extract coordinates per node/region
    coords = find_parcellation_cut_coords(labels_img=mask_nii)

    # run regressions per task, only reading in all subjects' corrmats
    # done separately for each task & condition and removing in between bc memory
    for task in tasks.keys():
        # only testing IQs associated with accuracy on this task
        iqs = tasks[task]["iqs"]

        # read in all subjects' correlation matrices and flatten into feature vectors
        conn_df = corrmat_to_samples_by_features(subjects, 1, task, "Physics",
                                                 mask, tau)
        conn_df.index = conn_df.index.astype(int)
        conns = list(set(conn_df.columns))

        # smush connectivity features and other variables into one big dataframe
        all_data = pd.concat([big_df, conn_df], axis=1)