Esempio n. 1
0
def cc_seg_mp(vol_path, streamlines_path, labels):
    """
    Make probabilistic map (pm)
    Parameters
    ----------
    vol_path: volume (T1w) data path
    streamlimes_path: streamlines path
    labels: label of each streamline

    Return
    ------
    pm: probabilisic map
    """
    img = nib.load(vol_path)
    dim4 = (len(set(labels)),)
    cc_mp = np.zeros(img.shape + dim4, dtype=float)
    fasciculus = Fasciculus(streamlines_path)
    streamlines = fasciculus.get_data()
    fibs_points = apply_affine(npl.inv(img.affine), fasciculus.xmin_nodes()).astype(int)
    for i in range(len(streamlines)):
        index_i = fibs_points == np.array([fibs_points[i][0], fibs_points[i][1], fibs_points[i][2]])
        index_i = index_i.sum(axis=1)
        inddex = index_i == 3
        voxel_counts = np.sum(index_i == 3)
        dim4_value = []
        for label in set(labels):
            index_lab = labels == label
            arr = np.vstack((inddex, index_lab)).sum(axis=0)
            dim4_value.append(np.sum(arr == 2) / voxel_counts)
        cc_mp[fibs_points[i][0], fibs_points[i][1], fibs_points[i][2]] = dim4_value

    return cc_mp
Esempio n. 2
0
def cc_seg_same_regions(vol_path, lr_region_path_suffix):
    """
    Segment cc according to lr same regions.
    Parameters
    ----------
    vol_path: volume (T1w) data path
    lr_region_path_suffix: same region streamlines of both hemispheres

    Return
    ------
    Density of lr-overlap streamlines mapping to the corpus callosum
    """
    img = nib.load(vol_path)
    counts = np.zeros(img.shape)
    roi_name_list = os.listdir(lr_region_path_suffix)
    roi_fib_path = os.path.join(lr_region_path_suffix, roi_name_list[0])
    fibs_points = apply_affine(npl.inv(img.affine), Fasciculus(roi_fib_path).xmin_nodes())
    for n in fibs_points:
        counts[int(n[0]), int(n[1]), int(n[2])] += 1

    if len(roi_name_list) == 2:
        roi_fib_path = os.path.join(lr_region_path_suffix, roi_name_list[1])
        fibs_points = apply_affine(npl.inv(img.affine), Fasciculus(roi_fib_path).xmin_nodes())
        for m in fibs_points:
            if counts[int(m[0]), int(m[1]), int(m[2])] != 0:
                counts[int(m[0]), int(m[1]), int(m[2])] += 1

    return counts
Esempio n. 3
0
def endpoints_axis2cc(vol_path, streamlines_path, axis='y', mode='max'):
    """
    Endpoints of streamlines mapping to cc.
    Parameters
    ----------
    vol_path: volume (T1w) data path
    streamlines_path: streamlines path
    axis: 'x', 'y', 'z'
        Choose which direction to project
    mode: 'max', 'min', 'mean'
        Choose which typ to project
    Return
    ------
    Density left and right endpoints, respectively
    """
    img = nib.load(vol_path)
    counts_l = np.zeros(img.shape)
    counts_r = np.zeros(img.shape)
    fibs_points = apply_affine(npl.inv(img.affine), Fasciculus(streamlines_path).xmin_nodes()).astype(int)
    streamlines = Fasciculus(streamlines_path).sort_streamlines()
    if axis == 'x':
        endpoints_l = np.array([fib[0][0] for fib in streamlines])
        endpoints_r = np.array([fib[-1][0] for fib in streamlines])
    elif axis == 'y':
        endpoints_l = np.array([fib[0][1] for fib in streamlines])
        endpoints_r = np.array([fib[-1][1] for fib in streamlines])
    else:
        endpoints_l = np.array([fib[0][2] for fib in streamlines])
        endpoints_r = np.array([fib[-1][2] for fib in streamlines])
    for i in range(len(streamlines)):
        index_i = fibs_points == np.array([fibs_points[i][0], fibs_points[i][1], fibs_points[i][2]])
        index_i = index_i.sum(axis=1)
        inddex = index_i == 3
        if mode == 'max':
            counts_l[fibs_points[i][0], fibs_points[i][1], fibs_points[i][2]] = endpoints_l[inddex].max()
            counts_r[fibs_points[i][0], fibs_points[i][1], fibs_points[i][2]] = endpoints_r[inddex].max()
        elif mode == 'min':
            counts_l[fibs_points[i][0], fibs_points[i][1], fibs_points[i][2]] = endpoints_l[inddex].min()
            counts_r[fibs_points[i][0], fibs_points[i][1], fibs_points[i][2]] = endpoints_r[inddex].min()
        else:
            counts_l[fibs_points[i][0], fibs_points[i][1], fibs_points[i][2]] = endpoints_l[inddex].mean()
            counts_r[fibs_points[i][0], fibs_points[i][1], fibs_points[i][2]] = endpoints_r[inddex].mean()

    return counts_l, counts_r
Esempio n. 4
0
def cc_seg_region(vol_path, roi_fib_paths_suffix):
    """
    Segment cc according to roi fibs
    Parameters
    ----------
    vol_path: volume (T1w) data path
    roi_fib_paths_suffix: all streamlines selected by rois (the sum of same kinds of areas)

    Return
    ------
    Density of all streamlines mapping to the corpus callosum
    """
    img = nib.load(vol_path)
    counts = np.zeros(img.shape)
    roi_name_list = os.listdir(roi_fib_paths_suffix)
    for roi_i in range(len(roi_name_list)):
        roi_fib_path = os.path.join(roi_fib_paths_suffix, roi_name_list[roi_i])
        fibs = apply_affine(npl.inv(img.affine), Fasciculus(roi_fib_path).xmin_nodes())
        for n in fibs:
            counts[int(n[0]), int(n[1]), int(n[2])] = roi_i + 1

    return counts
Esempio n. 5
0
from pyfat.core.dataobject import Fasciculus
from dipy.tracking.utils import length
from pyfat.algorithm.fiber_clustering import FibClustering
from pyfat.viz.colormap import create_random_colormap
from pyfat.viz.fiber_simple_viz_advanced import fiber_simple_3d_show_advanced


fib = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
      'response_dhollander/101107/Diffusion/1M_20_01_20dynamic250_SD_Stream_rhemi_occipital5.tck'
# fib = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
#            'response_dhollander/101107/Diffusion/1M_20_01_20dynamic250_SD_Stream_occipital8_lr5.tck'
img_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
           'response_dhollander/101107/Structure/T1w_acpc_dc_restore_brain1.25.nii.gz'

img = nib.load(img_path)
fa = Fasciculus(fib)
streamlines = fa.get_data()
length_t = fa.get_lengths()
ind = length_t > 10
streamlines = streamlines[ind]
fa.set_data(streamlines)
fibcluster = FibClustering(fa)
print len(streamlines)

# 1
qb = QuickBundles(streamlines, 2)
clusters = qb.clusters()
print qb.clusters_sizes()
indexs = []
for i in range(len(clusters)):
    if clusters[i]['N'] >= 400:
Esempio n. 6
0
           'response_dhollander/100408/Native/100408.R.white.native.surf.gii'

geo_path = [lh_white, rh_white]

tck_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
           'response_dhollander/100408/result/result20vs45/cc_20fib_1.5lr_new_hierarchical_single_cc_splenium.tck'
# tck_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
#            'response_dhollander/100408/result/result20vs45/cc_20fib_only_node.tck'
# tck_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
#            'response_dhollander/100408/result/result20vs45/cc_20fib_step20_new_sample5000.tck'
# load data
data_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
             'response_dhollander/100408/Structure/T1w_acpc_dc_restore_brain.nii.gz'
img = nib.load(data_path)

fasciculus = Fasciculus(tck_path)
fibcluster = FibClustering(fasciculus)
# length_clusters = fibcluster.length_seg()
# streamlines = fasciculus.sort_streamlines()
# fasciculus.set_data(streamlines)
streamlines = fasciculus.get_data()
print len(streamlines)

# d = fibcluster.bundle_seg(streamlines, dist_thre=15)
# print len(d[1])
index_streams = fibcluster.bundle_thre_seg(streamlines)
print len(index_streams[1])
centroids = fibcluster.bundle_centroids(streamlines,
                                        cluster_thre=10,
                                        dist_thre=10)
subject_id = "100408"
Esempio n. 7
0
import nibabel as nib
from pyfat.core.dataobject import Fasciculus
from pyfat.algorithm.fiber_clustering import FibClustering
from pyfat.viz.colormap import create_random_colormap
from pyfat.viz.fiber_simple_viz_advanced import fiber_simple_3d_show_advanced


fib = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
       'response_dhollander/101107/Diffusion/1M_20_01_20dynamic250_SD_Stream_occipital8_lr5.tck'
roi_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
           'response_dhollander/101107/lab_map/native1.25_wang_maxprob_vol_lh_mask_vis.nii.gz'
img_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
           'response_dhollander/101107/Structure/T1w_acpc_dc_restore_brain1.25.nii.gz'

img = nib.load(img_path)
fa = Fasciculus(fib)
streamlines = fa.get_data()
fibcluster = FibClustering(fa)

# 1
label_endpoints = fibcluster.endpoints_seg(temp_clusters=5000,
                                           mode='lh',
                                           thre=1)
# labels_rois = fibcluster.cluster_by_vol_rois(roi_path)
print set(label_endpoints)

colormap = create_random_colormap(len(set(label_endpoints)))
colormap_full = np.ones((len(streamlines), 3))
# print colormap_full
for label, color in zip(set(label_endpoints), colormap):
    colormap_full[label_endpoints == label] = color
Esempio n. 8
0
# !/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import division
from pyfat.io.load import load_tck, load_trk
from pyfat.viz.visualization import show
from pyfat.core.dataobject import Fasciculus

# tck
tck_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
           'response_dhollander/101107/Diffusion/1M_20_01_20dynamic250_SD_Stream_lh_occipital8.tck'
fas = Fasciculus(tck_path)
lengths = fas.get_lengths()
show(lengths)

R = fas.get_lr_ratio()
show(R, title='Rat histogram', xlabel='Rat')
Esempio n. 9
0
           'response_dhollander/100408/Native/100408.L.white.native.surf.gii'
rh_white = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
           'response_dhollander/100408/Native/100408.R.white.native.surf.gii'
# roi_vol_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
#                'response_dhollander/100408/Structure/MNI152_cytoMPM_thr25_2mm.nii.gz'
roi_vol_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
               'response_dhollander/100408/Structure/Wangliang_Atlas/native_mpm_lrh_thr10.nii.gz'

tck_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
           'response_dhollander/100408/result/result20vs45/cc_20fib_lr1.5_new_SD_Stream_hierarchical_single_cc_splenium.tck'

data_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
             'response_dhollander/100408/Structure/T1w_acpc_dc_restore_brain.nii.gz'
img = nib.load(data_path)

fasciculus = Fasciculus(tck_path)
streamlines = fasciculus.get_data()

subject_id = "100408"
subjects_dir = "/home/brain/workingdir/data/dwi/hcp/preprocessed/response_dhollander/100408"
hemi = 'both'
surf = 'inflated'
alpha = 1
geo_path = [lh_white, rh_white]

# lr_labels = roi_vol2surf(roi_vol_path, geo_path)
# lr_labels[0][lr_labels[0] != 6] = 0
# # lr_labels[0][lr_labels[0] > 93] = 0
# # lr_labels[1][lr_labels[1] < 84] = 0
# lr_labels[1][lr_labels[1] != 6] = 0
Esempio n. 10
0
# !/usr/bin/python
# -*- coding: utf-8 -*-

import nibabel as nib
from pyfat.io.load import load_tck
from pyfat.core.dataobject import Fasciculus
from pyfat.viz.visualization import show_slice_density

data_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
                'response_dhollander/100408/Structure/T1w_short.nii.gz'
img = nib.load(data_path)

tck_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
           'response_dhollander/100408/Diffusion/1M_20_002_dynamic250.tck'
fas = Fasciculus(tck_path)
Ls_temp = fas.xmin_nodes()
show_slice_density(img, Ls_temp)


Esempio n. 11
0
import nibabel.streamlines.array_sequence as nibas

import matplotlib.pyplot as plt

# load data
data_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
             'response_dhollander/100408/Structure/T1w_acpc_dc_restore_brain.nii.gz'
img = nib.load(data_path)
img_data = img.get_data()
# tck_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
#        'response_dhollander/100408/result/result20vs45/cc_20fib_step20_new_sample5000.tck'
tck_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
           'response_dhollander/100408/result/result20vs45/cc_20fib_lr1.5_01_new_correct.tck'

imgtck = load_tck(tck_path)
fasciculus = Fasciculus(tck_path)
streamstck = fasciculus.get_data()
# print streamstck

# extract node according to x-value
Ls_temp = fasciculus.xmin_nodes()
print len(Ls_temp)
# show node or density
# show_2d_node(img, Ls_temp)
# show_slice_density(img, Ls_temp)

# knn_graph = kneighbors_graph(Ls_temp, 10, include_self=False)
Ls_temp_labels, Ls_temp_centers = NodeClustering(Ls_temp).k_means()
sdist = pdist(Ls_temp_centers)
knn_graph = linkage(sdist, method='single', metric='euclidean')
print knn_graph
Esempio n. 12
0
def cc_seg_pipeline(tck_path, mask, geo_path, thr=5., roi_id=None, step=0):
    """
    Extract occipital streamlines and separate hemisphere streamlines
    Parameters
    ----------
    tck_path: list; streamline file path (.tck)
    mask: surface mask (xh.aparc.annot)
    geo_path: geometry data path (subject_id.L.white.native.surf.gii)
    thr: distance of streamline terminus to surface

    Return
    ------
    occipital streamlines
    """
    # load data
    fasciculus = Fasciculus(tck_path)

    # extract streamlines from left to right hemisphere
    fibselection = FibSelection(fasciculus)
    L_temp_need0 = fibselection.endpoint_dissimilarity()
    fasciculus.set_data(L_temp_need0)
    L_temp_need1 = fibselection.single_point_mid_sag()
    fasciculus.set_data(L_temp_need1)
    del L_temp_need0, L_temp_need1
    gc.collect()

    # separation of lr_seed fib
    fib = fasciculus.hemi_fib_separation()

    # choose the mask: Occipital
    mask_fib = []
    for i in range(len(fib)):
        vertices, colortable, label = nib.freesurfer.read_annot(mask[i])
        gii_data = nib.load(geo_path[i]).darrays
        coords, faces = gii_data[0].data, gii_data[1].data

        label_value = np.array(len(coords) * [0])
        if not roi_id:
            label_value[vertices == 11] = 11  # lateraloccipital
            label_value[vertices == 13] = 13  # lingual
            label_value[vertices == 5] = 5  # cuneus
            label_value[vertices == 21] = 21  # pericalcarine
        else:
            for value in roi_id:
                label_value[vertices == value] = value

        # extract fib using mask
        streamlines = fib[i]
        streamlines = fasciculus.sort_streamlines(streamlines)

        if i == 0:
            s0 = [s[0] for s in streamlines]
        else:
            s0 = [s[-1] for s in streamlines]

        stream_terminus = np.array(s0)
        dist = cdist(coords[label_value > 0], stream_terminus)
        stream_index = np.array(len(streamlines) * [False])
        for j in range(len(dist[:])):
            temp_index = np.array(dist[j] <= thr)
            stream_index += temp_index

        rois_streamlines = streamlines[stream_index]
        mask_fib.append(rois_streamlines)

    # lr fib merge
    fib_merge = fasciculus.fib_merge(mask_fib[0], mask_fib[1])
    del mask_fib
    gc.collect()
    fib_hemi = fasciculus.separation_fib_to_hemi(fib_merge)
    del fib_merge
    gc.collect()

    return fib_hemi
Esempio n. 13
0
# !/usr/bin/python
# -*- coding: utf-8 -*-

from pyfat.core.dataobject import Fasciculus
from pyfat.algorithm.fiber_extract import FibSelection
# load data
# file = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
#        'response_dhollander/100206/Diffusion/100k_sift_1M45006_dynamic250.tck'
file = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
       'response_dhollander/100408/result/result20vs45/Prob01_plenium_fib_vis.tck'
fasciculus = Fasciculus(file)

# extract CC
fibselection = FibSelection(fasciculus)
L_temp_need0 = fibselection.endpoint_dissimilarity()
fasciculus.set_data(L_temp_need0)
L_temp_need1 = fibselection.single_point_mid_sag()
fasciculus.set_data(L_temp_need1)
L_temp_need2 = fibselection.lr_step()
fasciculus.set_data(L_temp_need2)

out_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
           'response_dhollander/100408/result/result20vs45/Prob01_plenium_fib_vis_pure.tck'
fasciculus.save2tck(out_path)

# if __name__ == '__main__':
#     fib_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
#                'response_dhollander/100408/result/result20vs45/Prob01_plenium_fib.tck'
#     out_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
#                'response_dhollander/100408/result/result20vs45/Prob01_plenium_fib_vis.tck'
#     fasciculus = Fasciculus(fib_path)
Esempio n. 14
0
# !/usr/bin/python
# -*- coding: utf-8 -*-

from pyfat.io.load import load_tck
from pyfat.core.dataobject import Fasciculus
from pyfat.algorithm.fiber_extract import FibSelection


source_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
              'response_dhollander/101107/Diffusion/1M_20_01_20dynamic250_SD_Stream_rh_occipital8.tck'

fasciculus = Fasciculus(source_path)
fibs = FibSelection(fasciculus)
fib = fibs.lr_rat(5)
fasciculus.set_data(fib)
out_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
              'response_dhollander/101107/Diffusion/1M_20_01_20dynamic250_SD_Stream_rh_occipital8_lr5.tck'
fasciculus.save2tck(out_path)


Esempio n. 15
0
# subject_id = "101107"
# subjects_dir = "/home/brain/workingdir/data/dwi/hcp/preprocessed/response_dhollander/101107"
# hemi = 'lh'
# surf = 'white'
# alpha = 1
# brain = Brain(subjects_dir=subjects_dir, subject_id=subject_id, hemi=hemi, surf=surf, alpha=alpha)
# brain.add_overlay(l_label_value, min=l_label_value[l_label_value > 0].min(),
#                   max=l_label_value.max(), sign='pos', hemi='lh', name='lh')
#
# mlab.show()

tck_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
           'response_dhollander/101107/Diffusion/1M_20_01_20dynamic250_SD_Stream_single.tck'

fasciculus = Fasciculus(tck_path)
streamlines = fasciculus.get_data()
print len(streamlines)
streamlines = fasciculus.sort_streamlines()
s0 = [s[0] for s in streamlines]
stream_terminus_lh = np.array(s0)
dist_lh = cdist(coords[l_label_value > 0], stream_terminus_lh)
lh_stream_index = np.array(len(streamlines) * [False])
for i in range(len(dist_lh[:])):
    temp_index = np.array(dist_lh[i] <= 3)
    lh_stream_index += temp_index

lh_rois_streamlines = streamlines[lh_stream_index]
fasciculus.set_data(lh_rois_streamlines)
out_path = '/home/brain/workingdir/data/dwi/hcp/preprocessed/' \
           'response_dhollander/101107/Diffusion/1M_20_01_20dynamic250_SD_Stream_lh_occipital3.tck'
Esempio n. 16
0
def muti_bundle_registration(paths_file, pts=12):
    """
    muti-bundle registration and consolidation
    Parameters
    ----------
    paths_file: list; muti_bundle file path
    pts: each streamline is divided into sections

    Return
    ------
    new header: include id of each streamline that comes from different subjects
    registration and consolidation bundle
    """
    fas = Fasciculus(paths_file[0])
    # print fas.get_header()
    bundle_header = {'fasciculus_id': None}
    sub1 = fas.get_data()
    bundle_header['fasciculus_id'] = len(sub1) * [
        int(paths_file[0].split('/')[9])
    ]
    sub2 = Fasciculus(paths_file[1]).get_data()
    subj2_aligned = bundle_registration(sub1, sub2, pts=pts)
    bundle = fas.fib_merge(sub1, subj2_aligned)
    bundle_header['fasciculus_id'] += (
        len(bundle) - len(sub1)) * [int(paths_file[1].split('/')[9])]
    # print bundle_header
    # print len(bundle)
    for index in range(len(paths_file))[2:]:
        # print paths_file[index]
        sub = Fasciculus(paths_file[index]).get_data()
        sub_aligned = bundle_registration(sub1, sub, pts=pts)
        lenth = len(bundle)
        bundle = fas.fib_merge(bundle, sub_aligned)
        bundle_header['fasciculus_id'] += (
            len(bundle) - lenth) * [int(paths_file[index].split('/')[9])]

    fas.update_header(bundle_header)
    fas.set_data(nibas.ArraySequence(bundle))

    return fas