コード例 #1
0
def find_bad_nrigh(name, score):

    test_data = np.load(os.path.join('..', 'cci_clean_data', name))
    data_evl = test_data['arr_0']
    key = os.path.splitext(name)[0]
    cci_score = cci_dict[key]
    cci_score = np.array(cci_score)

    streamlines_evl = Streamlines()

    for i in range(np.shape(data_evl)[0]):
        tmp = data_evl[i]
        tmp = zero_remove(tmp)
        #tmp = tmp[~np.all(tmp == 0, axis=-1)]
        #tmp = np.around(tmp, decimals=0)
        streamlines_evl.append(tmp)

    lengths = np.array(list(length(streamlines_evl)))

    neighb = np.zeros((np.shape(data_evl)[0]))

    subsamp_sls = set_number_of_points(streamlines_evl, 64)
    for i in range(len(streamlines_evl)):

        mdf_mx = bundles_distances_mdf([subsamp_sls[i]], subsamp_sls)
        if (score[i] == 0):  # bad fiber

            thre = np.percentile(mdf_mx, 4)
            len_bad = lengths[i]
            bound = len_bad * 0.1
            len_limt = 1 * ((lengths > len_bad - bound) &
                            (lengths < len_bad + bound))
            label = 1 * (mdf_mx < thre).flatten()  # bad neighbour
            neighb = neighb + label * (cci_score < 10)
    return data_evl, neighb
コード例 #2
0
def cal_cov_sub(fiber_sub):

    streamlines_evl = Streamlines()

    for i in range(np.shape(fiber_sub)[0]):
        tmp = fiber_sub[i]
        tmp = zero_remove(tmp)
        streamlines_evl.append(tmp)

    #==============
    fiber_one = fiber_sub[0].transpose()
    fiber_one_std = preprocessing.scale(fiber_one)

    covarience = np.cov(fiber_one_std)
    result = np.array([
        covarience[0, 0], covarience[1, 1], covarience[2, 2], covarience[0, 1],
        covarience[0, 2], covarience[1, 2]
    ]).transpose()

    for i in range(1, np.shape(fiber_sub)[0]):
        fiber_one = fiber_sub[i].transpose()
        fiber_one_std = preprocessing.scale(fiber_one)

        covarience = np.cov(fiber_one_std)
        #tmp = np.array( [covarience[0,0], covarience[1,1], covarience[2,2]]).transpose()
        tmp = np.array([
            covarience[0, 0], covarience[1, 1], covarience[2, 2],
            covarience[0, 1], covarience[0, 2], covarience[1, 2]
        ]).transpose()
        result = np.vstack((result, tmp))
    return result
コード例 #3
0
ファイル: streamlinear.py プロジェクト: arokem/dipy
def remove_clusters_by_size(clusters, min_size=0):
    ob = filter(lambda c: len(c) >= min_size, clusters)

    centroids = Streamlines()
    for cluster in ob:
        centroids.append(cluster.centroid)

    return centroids
コード例 #4
0
def remove_clusters_by_size(clusters, min_size=0):
    ob = filter(lambda c: len(c) >= min_size, clusters)

    centroids = Streamlines()
    for cluster in ob:
        centroids.append(cluster.centroid)

    return centroids
コード例 #5
0
ファイル: remove_cci_outliers.py プロジェクト: HilaGast/FT
def remove_cci_outliers(streamlines):
    s = Streamlines(streamlines)
    cci = cluster_confidence(s,subsample=7)
    keep_streamlines = Streamlines()
    keep_streamlines_idx = list()
    for i, sl in enumerate(s):
        if cci[i] >= 1:
            keep_streamlines.append(sl)
            keep_streamlines_idx.append(i)

    return keep_streamlines,keep_streamlines_idx
コード例 #6
0
ファイル: test_apps.py プロジェクト: neurodata/aloftus
def test_horizon():

    s1 = 10 * np.array([[0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0], [4, 0, 0]],
                       dtype='f8')

    s2 = 10 * np.array([[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [0, 4, 0]],
                       dtype='f8')

    s3 = 10 * np.array(
        [[0, 0, 0], [1, 0.2, 0], [2, 0.2, 0], [3, 0.2, 0], [4, 0.2, 0]],
        dtype='f8')

    print(s1.shape)
    print(s2.shape)
    print(s3.shape)

    streamlines = Streamlines()
    streamlines.append(s1)
    streamlines.append(s2)
    streamlines.append(s3)

    tractograms = [streamlines]
    images = None

    horizon(tractograms,
            images=images,
            cluster=True,
            cluster_thr=5,
            random_colors=False,
            length_lt=np.inf,
            length_gt=0,
            clusters_lt=np.inf,
            clusters_gt=0,
            world_coords=False,
            interactive=False)

    affine = np.diag([2., 1, 1, 1]).astype('f8')

    data = 255 * np.random.rand(150, 150, 150)

    images = [(data, affine)]

    horizon(tractograms,
            images=images,
            cluster=True,
            cluster_thr=5,
            random_colors=False,
            length_lt=np.inf,
            length_gt=0,
            clusters_lt=np.inf,
            clusters_gt=0,
            world_coords=True,
            interactive=False)
コード例 #7
0
ファイル: test_apps.py プロジェクト: arokem/dipy
def test_horizon():

    s1 = 10 * np.array([[0, 0, 0],
                        [1, 0, 0],
                        [2, 0, 0],
                        [3, 0, 0],
                        [4, 0, 0]], dtype='f8')

    s2 = 10 * np.array([[0, 0, 0],
                        [0, 1, 0],
                        [0, 2, 0],
                        [0, 3, 0],
                        [0, 4, 0]], dtype='f8')

    s3 = 10 * np.array([[0, 0, 0],
                        [1, 0.2, 0],
                        [2, 0.2, 0],
                        [3, 0.2, 0],
                        [4, 0.2, 0]], dtype='f8')

    print(s1.shape)
    print(s2.shape)
    print(s3.shape)

    streamlines = Streamlines()
    streamlines.append(s1)
    streamlines.append(s2)
    streamlines.append(s3)

    tractograms = [streamlines]
    images = None

    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=False, interactive=False)

    affine = np.diag([2., 1, 1, 1]).astype('f8')

    data = 255 * np.random.rand(150, 150, 150)

    images = [(data, affine)]

    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=False)

    tractograms = []
    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=False)
コード例 #8
0
ファイル: test_streamline.py プロジェクト: okjoh/dipy
def test_streamlines_generator():
    # Test generator
    streamlines_generator = Streamlines(generate_sl(streamlines))
    npt.assert_equal(len(streamlines_generator), len(streamlines))
    # Nothing should change
    streamlines_generator.append(np.array([]))
    npt.assert_equal(len(streamlines_generator), len(streamlines))

    # Test append error
    npt.assert_raises(ValueError, streamlines_generator.append, streamlines)

    # Test empty streamlines
    streamlines_generator = Streamlines(np.array([]))
    npt.assert_equal(len(streamlines_generator), 0)
コード例 #9
0
ファイル: test_streamline.py プロジェクト: mpaquette/dipy
def test_streamlines_generator():
    # Test generator
    streamlines_generator = Streamlines(generate_sl(streamlines))
    npt.assert_equal(len(streamlines_generator), len(streamlines))
    # Nothing should change
    streamlines_generator.append(np.array([]))
    npt.assert_equal(len(streamlines_generator), len(streamlines))

    # Test append error
    npt.assert_raises(ValueError, streamlines_generator.append, streamlines)

    # Test empty streamlines
    streamlines_generator = Streamlines(np.array([]))
    npt.assert_equal(len(streamlines_generator), 0)
コード例 #10
0
def visualize_streamline(darray,
                         score,
                         save_able=False,
                         save_name='default.png',
                         control_par=1,
                         hue=[0.5, 1]):

    data_evl = darray

    streamlines_evl = Streamlines()

    for i in range(np.shape(data_evl)[0]):
        tmp = data_evl[i]
        tmp = zero_remove(tmp)
        #tmp = tmp[~np.all(tmp == 0, axis=-1)]
        #tmp = np.around(tmp, decimals=0)
        streamlines_evl.append(tmp)

    mse_nor = score

    # Visualize the streamlines, colored by cci
    ren = window.Scene()

    saturation = [0.0, 1.0]

    lut_cmap = actor.colormap_lookup_table(
        scale_range=(min(mse_nor), max(mse_nor) / control_par),
        hue_range=hue,
        saturation_range=saturation)

    bar3 = actor.scalar_bar(lut_cmap)
    ren.add(bar3)

    stream_actor = actor.line(streamlines_evl,
                              mse_nor,
                              linewidth=0.1,
                              lookup_colormap=lut_cmap)
    ren.add(stream_actor)

    if not save_able:
        interactive = True
        if interactive:
            window.show(ren)

    if save_able:
        window.record(ren, n_frames=1, out_path=save_name, size=(800, 800))
コード例 #11
0
def clean_subject(ndata):
    cci = []
    streamlines_evl = Streamlines()
    for j in range(np.shape(ndata)[0]):
        tmp = ndata[j]
        tmp = zero_remove(tmp)
        streamlines_evl.append(tmp)

    lengths = list(utils.length(streamlines_evl))
    long_streamlines_evl = Streamlines()
    for i, sl in enumerate(streamlines_evl):
        if lengths[i] > 40:
            long_streamlines_evl.append(sl)

    streamlines_test = remove_indentical(10, long_streamlines_evl)
    cci_idv = cluster_confidence(streamlines_test, subsample=64)
    cci.append(cci_idv)
    return gen_array(streamlines_test), np.array(cci[0])
コード例 #12
0
def cal_cci(name_list, text):
    cci = []
    for i in range(len(name_list)):
        path = os.path.join('np_data', name_list[i])
        sample_data = np.load(path)
        ndata = sample_data['arr_0']

        streamlines_evl = Streamlines()
        for j in range(np.shape(ndata)[0]):
            tmp = ndata[j]
            tmp = zero_remove(tmp)
            streamlines_evl.append(tmp)
        streamlines_test = remove_indentical(10, streamlines_evl)
        cci_idv = cluster_confidence(streamlines_test, subsample=64)
        cci.append(cci_idv)
        print('the ' + str(i + 1) + ' finished')
    path_save = os.path.join('data_4_model', text)
    np.save(path_save, cci)
    return cci
コード例 #13
0
def remove_indentical(n, streamlines_ori):

    for i in range(n):

        error_index = []
        subsamp_sls = set_number_of_points(streamlines_ori, 64)
        mdf1 = np.zeros((1, len(subsamp_sls)))
        for i, sl in enumerate(subsamp_sls):
            mdf_mx = bundles_distances_mdf([subsamp_sls[i]], subsamp_sls)
            mdf1 = np.vstack((mdf1, mdf_mx))
            if (mdf_mx == 0).sum() > 1:
                if i - 1 not in error_index:
                    error_index.append(i)

        if error_index == []:
            return streamlines_ori
            print('number of detecting iteration is ' + str(2 * i + 1))
            break

        streamlines_evl_final1 = Streamlines()
        for i, sl in enumerate(streamlines_ori):
            if i not in error_index:
                streamlines_evl_final1.append(sl)

        error_index = []
        subsamp_sls = set_number_of_points(streamlines_evl_final1, 64)
        mdf1 = np.zeros((1, len(subsamp_sls)))
        for i, sl in enumerate(subsamp_sls):
            mdf_mx = bundles_distances_mdf([subsamp_sls[i]], subsamp_sls)
            mdf1 = np.vstack((mdf1, mdf_mx))
            if (mdf_mx == 0).sum() > 1:
                if i - 1 not in error_index:
                    error_index.append(i)
        if error_index == []:
            return streamlines_evl_final1
            print('number of detecting iteration is ' + str(2 * i + 2))
            break

        streamlines_ori = Streamlines()
        for i, sl in enumerate(streamlines_evl_final1):
            if i not in error_index:
                streamlines_ori.append(sl)
コード例 #14
0
def cal_cov_sub(sub_name):

    fiber_sub = np.load(os.path.join('..', 'cci_clean_data', sub_name))
    fiber_sub = fiber_sub['arr_0']
    cci = cci_dict[os.path.splitext(sub_name)[0]]
    mask_score = mask_score_dict[os.path.splitext(sub_name)[0]]

    streamlines_evl = Streamlines()

    for i in range(np.shape(fiber_sub)[0]):
        tmp = fiber_sub[i]
        tmp = zero_remove(tmp)
        streamlines_evl.append(tmp)

    lengths = np.array(list(length(streamlines_evl)))

    #==============
    fiber_one = fiber_sub[0].transpose()
    fiber_one_std = preprocessing.scale(fiber_one)

    covarience = np.cov(fiber_one_std)
    result = np.array([
        mask_score[0], cci[0], lengths[0], covarience[0, 0], covarience[1, 1],
        covarience[2, 2], covarience[0, 1], covarience[0, 2], covarience[1, 2]
    ]).transpose()

    for i in range(1, np.shape(fiber_sub)[0]):
        fiber_one = fiber_sub[i].transpose()
        fiber_one_std = preprocessing.scale(fiber_one)

        covarience = np.cov(fiber_one_std)
        #tmp = np.array( [covarience[0,0], covarience[1,1], covarience[2,2]]).transpose()
        tmp = np.array([
            mask_score[i], cci[i], lengths[i], covarience[0, 0],
            covarience[1, 1], covarience[2, 2], covarience[0, 1],
            covarience[0, 2], covarience[1, 2]
        ]).transpose()
        result = np.vstack((result, tmp))
    return result
コード例 #15
0
def gen_short_data(name_list):
    for i in range(len(name_list)):
        name = name_list[i]
        path = os.path.join('..', 'cci_clean_data', name)
        sample_data = np.load(path)
        ndata = sample_data['arr_0']

        streamlines_evl = Streamlines()
        for j in range(np.shape(ndata)[0]):
            tmp = ndata[j]
            tmp = zero_remove(tmp)
            streamlines_evl.append(tmp)

        subsamp_sls = set_number_of_points(streamlines_evl, sub_len)

        tt = np.array(subsamp_sls)
        path = os.path.join('..', 'subsample-data', str(sub_len))
        if not os.path.exists(path):
            os.makedirs(path)
        name_save = os.path.join(path, os.path.splitext(name)[0])

        np.savez_compressed(name_save, tt)
        print(str(i + 1) + '/141 finished')
コード例 #16
0
def test_cluster_confidence():
    mysl = np.array([np.arange(10)] * 3, 'float').T

    # a short streamline (<20 mm) should raise an error unless override=True
    test_streamlines = Streamlines()
    test_streamlines.append(mysl)
    assert_raises(ValueError, cluster_confidence, test_streamlines)
    cci = cluster_confidence(test_streamlines, override=True)

    # two identical streamlines should raise an error
    test_streamlines = Streamlines()
    test_streamlines.append(mysl, cache_build=True)
    test_streamlines.append(mysl)
    test_streamlines.finalize_append()
    assert_raises(ValueError, cluster_confidence, test_streamlines)

    # 3 offset collinear streamlines
    test_streamlines = Streamlines()
    test_streamlines.append(mysl, cache_build=True)
    test_streamlines.append(mysl + 1)
    test_streamlines.append(mysl + 2)
    test_streamlines.finalize_append()
    cci = cluster_confidence(test_streamlines, override=True)
    assert_equal(cci[0], cci[2])
    assert_true(cci[1] > cci[0])

    # 3 parallel streamlines
    mysl = np.zeros([10, 3])
    mysl[:, 0] = np.arange(10)
    mysl2 = mysl.copy()
    mysl2[:, 1] = 1
    mysl3 = mysl.copy()
    mysl3[:, 1] = 2
    mysl4 = mysl.copy()
    mysl4[:, 1] = 4
    mysl5 = mysl.copy()
    mysl5[:, 1] = 5000

    test_streamlines_p1 = Streamlines()
    test_streamlines_p1.append(mysl, cache_build=True)
    test_streamlines_p1.append(mysl2)
    test_streamlines_p1.append(mysl3)
    test_streamlines_p1.finalize_append()
    test_streamlines_p2 = Streamlines()
    test_streamlines_p2.append(mysl, cache_build=True)
    test_streamlines_p2.append(mysl3)
    test_streamlines_p2.append(mysl4)
    test_streamlines_p2.finalize_append()
    test_streamlines_p3 = Streamlines()
    test_streamlines_p3.append(mysl, cache_build=True)
    test_streamlines_p3.append(mysl2)
    test_streamlines_p3.append(mysl3)
    test_streamlines_p3.append(mysl5)
    test_streamlines_p3.finalize_append()

    cci_p1 = cluster_confidence(test_streamlines_p1, override=True)
    cci_p2 = cluster_confidence(test_streamlines_p2, override=True)

    # test relative distance
    assert_array_equal(cci_p1, cci_p2 * 2)

    # test simple cci calculation
    expected_p1 = np.array([1. / 1 + 1. / 2, 1. / 1 + 1. / 1, 1. / 1 + 1. / 2])
    expected_p2 = np.array([1. / 2 + 1. / 4, 1. / 2 + 1. / 2, 1. / 2 + 1. / 4])
    assert_array_equal(expected_p1, cci_p1)
    assert_array_equal(expected_p2, cci_p2)

    # test power variable calculation (dropoff with distance)
    cci_p1_pow2 = cluster_confidence(test_streamlines_p1,
                                     power=2,
                                     override=True)
    expected_p1_pow2 = np.array([
        np.power(1. / 1, 2) + np.power(1. / 2, 2),
        np.power(1. / 1, 2) + np.power(1. / 1, 2),
        np.power(1. / 1, 2) + np.power(1. / 2, 2)
    ])

    assert_array_equal(cci_p1_pow2, expected_p1_pow2)

    # test max distance (ignore distant sls)
    cci_dist = cluster_confidence(test_streamlines_p3,
                                  max_mdf=5,
                                  override=True)
    expected_cci_dist = np.concatenate([cci_p1, np.zeros(1)])
    assert_array_equal(cci_dist, expected_cci_dist)
コード例 #17
0
        cc_uniques = np.unique(cc_int, axis=0)

        score_tmp = cal_dist_score(avg_dist, cc_uniques)
        scores.append(score_tmp)

    return np.array(scores)


result_dis = cal_score_subject(bundle)
#%%

streamlines_evl = Streamlines()
for j in range(np.shape(bundle)[0]):
    tmp = bundle[j]
    tmp = zero_remove(tmp)
    streamlines_evl.append(tmp)

result_cci = cluster_confidence(streamlines_evl, subsample=64)

#%%

preds_cci = 1 * (result_cci > results.cci_thre)
preds_dis = 1 * (result_dis < results.dis_thre)
pred_if = 1 * (pred_if > 0)

pred_1 = 1 * ((preds_cci + preds_dis + pred_if) > 2)

bundle_str = Streamlines()

for i in range(np.shape(bundle)[0]):
    tmp = bundle[i]
コード例 #18
0
denoise = model(bundle)
denoise = denoise.numpy()
mse_idv = cal_mse(bundle, denoise)



thre = np.percentile(mse_idv,thre_con)
pred_1 = 1*(mse_idv<thre)
bundle_str = Streamlines()

for i in range(np.shape(bundle)[0]):
    tmp = bundle[i]
    tmp = zero_remove(tmp)
    #tmp = tmp[~np.all(tmp == 0, axis=-1)]
    #tmp = np.around(tmp, decimals=0)
    bundle_str.append(tmp)
    
lengths = length(bundle_str)
len_thre = results.len_con
pred_2 = 1*(lengths > len_thre)

pred = 1*((pred_1 + pred_2)>1)



op_path = 'result'
if not os.path.exists(op_path):
    os.mkdir(op_path)

save_path = os.path.join(op_path,'Detection'+name.split('_')[0]+'_m'+str(results.model_type))
np.save(save_path,pred)
コード例 #19
0
def test_horizon_flow():

    s1 = 10 * np.array([[0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0], [4, 0, 0]],
                       dtype='f8')

    s2 = 10 * np.array([[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [0, 4, 0]],
                       dtype='f8')

    s3 = 10 * np.array(
        [[0, 0, 0], [1, 0.2, 0], [2, 0.2, 0], [3, 0.2, 0], [4, 0.2, 0]],
        dtype='f8')

    affine = np.array([[1., 0., 0., -98.], [0., 1., 0., -134.],
                       [0., 0., 1., -72.], [0., 0., 0., 1.]])

    data = 255 * np.random.rand(197, 233, 189)
    vox_size = (1., 1., 1.)

    streamlines = Streamlines()
    streamlines.append(s1)
    streamlines.append(s2)
    streamlines.append(s3)

    header = create_nifti_header(affine, data.shape, vox_size)
    sft = StatefulTractogram(streamlines, header, Space.RASMM)

    tractograms = [sft]
    images = None

    horizon(tractograms,
            images=images,
            cluster=True,
            cluster_thr=5,
            random_colors=False,
            length_lt=np.inf,
            length_gt=0,
            clusters_lt=np.inf,
            clusters_gt=0,
            world_coords=True,
            interactive=False)

    buan_colors = np.ones(streamlines.get_data().shape)

    horizon(tractograms,
            buan=True,
            buan_colors=buan_colors,
            world_coords=True,
            interactive=False)

    data = 255 * np.random.rand(197, 233, 189)

    images = [(data, affine)]

    horizon(tractograms,
            images=images,
            cluster=True,
            cluster_thr=5,
            random_colors=False,
            length_lt=np.inf,
            length_gt=0,
            clusters_lt=np.inf,
            clusters_gt=0,
            world_coords=True,
            interactive=False)

    with TemporaryDirectory() as out_dir:

        fimg = os.path.join(out_dir, 'test.nii.gz')
        ftrk = os.path.join(out_dir, 'test.trk')
        fnpy = os.path.join(out_dir, 'test.npy')

        save_nifti(fimg, data, affine)
        dimensions = data.shape
        nii_header = create_nifti_header(affine, dimensions, vox_size)
        sft = StatefulTractogram(streamlines, nii_header, space=Space.RASMM)
        save_tractogram(sft, ftrk, bbox_valid_check=False)

        pvalues = np.random.uniform(low=0, high=1, size=(10, ))
        np.save(fnpy, pvalues)

        input_files = [ftrk, fimg]

        npt.assert_equal(len(input_files), 2)

        hz_flow = HorizonFlow()

        hz_flow.run(input_files=input_files,
                    stealth=True,
                    out_dir=out_dir,
                    out_stealth_png='tmp_x.png')

        npt.assert_equal(os.path.exists(os.path.join(out_dir, 'tmp_x.png')),
                         True)
        npt.assert_raises(ValueError,
                          hz_flow.run,
                          input_files=input_files,
                          bg_color=(0.2, 0.2))

        hz_flow.run(input_files=input_files,
                    stealth=True,
                    bg_color=[
                        0.5,
                    ],
                    out_dir=out_dir,
                    out_stealth_png='tmp_x.png')
        npt.assert_equal(os.path.exists(os.path.join(out_dir, 'tmp_x.png')),
                         True)

        input_files = [ftrk, fnpy]

        npt.assert_equal(len(input_files), 2)

        hz_flow.run(input_files=input_files,
                    stealth=True,
                    bg_color=[
                        0.5,
                    ],
                    buan=True,
                    buan_thr=0.5,
                    buan_highlight=(1, 1, 0),
                    out_dir=out_dir,
                    out_stealth_png='tmp_x.png')
        npt.assert_equal(os.path.exists(os.path.join(out_dir, 'tmp_x.png')),
                         True)

        npt.assert_raises(ValueError,
                          hz_flow.run,
                          input_files=input_files,
                          roi_colors=(0.2, 0.2))

        hz_flow.run(input_files=input_files,
                    stealth=True,
                    roi_colors=[
                        0.5,
                    ],
                    out_dir=out_dir,
                    out_stealth_png='tmp_x.png')
        npt.assert_equal(os.path.exists(os.path.join(out_dir, 'tmp_x.png')),
                         True)
コード例 #20
0
mse_idv = cal_mse(bundle, denoise)


#%%
thre = np.percentile(mse_idv,85)
pred_1 = 1*(mse_idv<thre)


bundle_str = Streamlines()

for i in range(np.shape(bundle)[0]):
    tmp = bundle[i]
    tmp = zero_remove(tmp)
    #tmp = tmp[~np.all(tmp == 0, axis=-1)]
    #tmp = np.around(tmp, decimals=0)
    bundle_str.append(tmp)
    
lengths = length(bundle_str)
len_thre = 40
pred_2 = 1*(lengths > len_thre)

pred = 1*((pred_1 + pred_2)>1)



data_new = np.delete(bundle, np.where(pred == 0), axis=0)

npz2ply_cleaned(data_new,name)
#%%

import sys
コード例 #21
0
        all_sl = Streamlines(all_sl)

        lengths = list(length(all_sl))

        print('Removing small streamlines, DIPY. Number of streamlines: ' +
              str(len(lengths)))
        t1 = time.time()

        long_sl = Streamlines()
        #n_long= 0
        c_long = 0
        for i, sl in enumerate(all_sl):
            if i % 10000 == 0:
                print(i)
            if lengths[i] > min_stream_length:
                long_sl.append(sl)
                #n_long+= sl.shape[0]
                c_long += 1

        print(
            'Finished removing small streamlines, DIPY, time elapsed (minutes): '
            + str(int((time.time() - t1) / 60)) +
            '. Percentage of streamlines kept: ' +
            str(int(100 * c_long / len(lengths))))

        sft = StatefulTractogram(long_sl, FA_img_nii, Space.RASMM)
        save_trk(
            sft, dav_dir + "tractogram_dipy_deterministic_long_" +
            str(min_stream_length) + ".trk")

        ####################################################
コード例 #22
0
def test_horizon_flow():

    s1 = 10 * np.array([[0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0], [4, 0, 0]],
                       dtype='f8')

    s2 = 10 * np.array([[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [0, 4, 0]],
                       dtype='f8')

    s3 = 10 * np.array(
        [[0, 0, 0], [1, 0.2, 0], [2, 0.2, 0], [3, 0.2, 0], [4, 0.2, 0]],
        dtype='f8')

    print(s1.shape)
    print(s2.shape)
    print(s3.shape)

    streamlines = Streamlines()
    streamlines.append(s1)
    streamlines.append(s2)
    streamlines.append(s3)

    tractograms = [streamlines]
    images = None

    horizon(tractograms,
            images=images,
            cluster=True,
            cluster_thr=5,
            random_colors=False,
            length_lt=np.inf,
            length_gt=0,
            clusters_lt=np.inf,
            clusters_gt=0,
            world_coords=False,
            interactive=False)
    #
    affine = np.diag([2., 1, 1, 1]).astype('f8')
    #
    data = 255 * np.random.rand(150, 150, 150)
    #
    images = [(data, affine)]

    horizon(tractograms,
            images=images,
            cluster=True,
            cluster_thr=5,
            random_colors=False,
            length_lt=np.inf,
            length_gt=0,
            clusters_lt=np.inf,
            clusters_gt=0,
            world_coords=True,
            interactive=False)

    with TemporaryDirectory() as out_dir:

        fimg = os.path.join(out_dir, 'test.nii.gz')
        ftrk = os.path.join(out_dir, 'test.trk')

        save_nifti(fimg, data, affine)
        dimensions = data.shape
        voxel_sizes = np.array([2, 1.0, 1.0])
        nii_header = create_nifti_header(affine, dimensions, voxel_sizes)
        sft = StatefulTractogram(streamlines, nii_header, space=Space.RASMM)
        save_tractogram(sft, ftrk, bbox_valid_check=False)

        input_files = [ftrk, fimg]

        npt.assert_equal(len(input_files), 2)

        hz_flow = HorizonFlow()

        hz_flow.run(input_files=input_files,
                    stealth=True,
                    out_dir=out_dir,
                    out_stealth_png='tmp_x.png')

        npt.assert_equal(os.path.exists(os.path.join(out_dir, 'tmp_x.png')),
                         True)
コード例 #23
0
# Make a streamline bundle model of the corpus callosum ROI connectivity
streamlines = LocalTracking(csa_peaks, classifier, seeds, affine,
                            step_size=2)
streamlines = Streamlines(streamlines)


"""
We do not want our results inflated by short streamlines, so we remove
streamlines shorter than 40mm prior to calculating the CCI.
"""

lengths = list(length(streamlines))
long_streamlines = Streamlines()
for i, sl in enumerate(streamlines):
    if lengths[i] > 40:
        long_streamlines.append(sl)


"""
Now we calculate the Cluster Confidence Index using the corpus callosum
streamline bundle and visualize them.
"""


cci = cluster_confidence(long_streamlines)

# Visualize the streamlines, colored by cci
ren = window.Renderer()

hue = [0.5, 1]
saturation = [0.0, 1.0]
コード例 #24
0
def test_horizon():

    s1 = 10 * np.array([[0, 0, 0],
                        [1, 0, 0],
                        [2, 0, 0],
                        [3, 0, 0],
                        [4, 0, 0]], dtype='f8')

    s2 = 10 * np.array([[0, 0, 0],
                        [0, 1, 0],
                        [0, 2, 0],
                        [0, 3, 0],
                        [0, 4, 0]], dtype='f8')

    s3 = 10 * np.array([[0, 0, 0],
                        [1, 0.2, 0],
                        [2, 0.2, 0],
                        [3, 0.2, 0],
                        [4, 0.2, 0]], dtype='f8')

    streamlines = Streamlines()
    streamlines.append(s1)
    streamlines.append(s2)
    streamlines.append(s3)

    affine = np.array([[1., 0., 0., -98.],
                       [0., 1., 0., -134.],
                       [0., 0., 1., -72.],
                       [0., 0., 0., 1.]])

    data = 255 * np.random.rand(197, 233, 189)
    vox_size = (1., 1., 1.)

    streamlines._data += np.array([-98., -134., -72.])

    header = create_nifti_header(affine, data.shape, vox_size)
    sft = StatefulTractogram(streamlines, header, Space.RASMM)

    # only tractograms
    tractograms = [sft]
    images = None
    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=False)

    images = [(data, affine)]

    # tractograms in native coords (not supported for now)
    with npt.assert_raises(ValueError) as ve:
        horizon(tractograms, images=images, cluster=True, cluster_thr=5,
                random_colors=False, length_lt=np.inf, length_gt=0,
                clusters_lt=np.inf, clusters_gt=0,
                world_coords=False, interactive=False)

    msg = 'Currently native coordinates are not supported for streamlines'
    npt.assert_(msg in str(ve.exception))

    # only images
    tractograms = None
    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=False)

    # no clustering tractograms and images
    horizon(tractograms, images=images, cluster=False, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=False)
コード例 #25
0
streamlines = LocalTracking(csa_peaks,
                            stopping_criterion,
                            seeds,
                            affine,
                            step_size=2)
streamlines = Streamlines(streamlines)
"""
We do not want our results inflated by short streamlines, so we remove
streamlines shorter than 40mm prior to calculating the CCI.
"""

lengths = list(length(streamlines))
long_streamlines = Streamlines()
for i, sl in enumerate(streamlines):
    if lengths[i] > 40:
        long_streamlines.append(sl)
"""
Now we calculate the Cluster Confidence Index using the corpus callosum
streamline bundle and visualize them.
"""

cci = cluster_confidence(long_streamlines)

# Visualize the streamlines, colored by cci
ren = window.Renderer()

hue = [0.5, 1]
saturation = [0.0, 1.0]

lut_cmap = actor.colormap_lookup_table(scale_range=(cci.min(), cci.max() / 4),
                                       hue_range=hue,
コード例 #26
0
ファイル: test_viz.py プロジェクト: StongeEtienne/dipy
def test_horizon_flow():

    s1 = 10 * np.array([[0, 0, 0],
                        [1, 0, 0],
                        [2, 0, 0],
                        [3, 0, 0],
                        [4, 0, 0]], dtype='f8')

    s2 = 10 * np.array([[0, 0, 0],
                        [0, 1, 0],
                        [0, 2, 0],
                        [0, 3, 0],
                        [0, 4, 0]], dtype='f8')

    s3 = 10 * np.array([[0, 0, 0],
                        [1, 0.2, 0],
                        [2, 0.2, 0],
                        [3, 0.2, 0],
                        [4, 0.2, 0]], dtype='f8')

    print(s1.shape)
    print(s2.shape)
    print(s3.shape)

    streamlines = Streamlines()
    streamlines.append(s1)
    streamlines.append(s2)
    streamlines.append(s3)

    tractograms = [streamlines]
    images = None

    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=False, interactive=False)
#
    affine = np.diag([2., 1, 1, 1]).astype('f8')
#
    data = 255 * np.random.rand(150, 150, 150)
#
    images = [(data, affine)]

    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=False)

    with TemporaryDirectory() as out_dir:

        fimg = os.path.join(out_dir, 'test.nii.gz')
        ftrk = os.path.join(out_dir, 'test.trk')

        save_nifti(fimg, data, affine)
        save_tractogram(ftrk, streamlines, affine)

        input_files = [ftrk, fimg]

        npt.assert_equal(len(input_files), 2)

        hz_flow = HorizonFlow()

        hz_flow.run(input_files=input_files, stealth=True,
                    out_dir=out_dir, out_stealth_png='tmp_x.png')

        npt.assert_equal(os.path.exists(os.path.join(out_dir, 'tmp_x.png')),
                         True)