예제 #1
0
def alignment_as_graph_matching(T_A_filename, T_B_filename,
                                k, threshold_short_streamlines=10.0,
                                b=100, t=100, alpha=0.5, max_iter1=100,
                                max_iter2=100):
    # 1) load T_A and T_B
    T_A = load_tractogram(T_A_filename, threshold_short_streamlines=threshold_short_streamlines)
    T_B = load_tractogram(T_B_filename, threshold_short_streamlines=threshold_short_streamlines)
    
    # 2) Compute the dissimilarity representation of T_A and T_B
    print("Computing the dissimilarity representation of T_A")
    T_A_dr, prototypes_A = compute_dissimilarity(T_A)
    print("Computing the dissimilarity representation of T_B")
    T_B_dr, prototypes_B = compute_dissimilarity(T_B)

    # 3) Compute the k-means clustering of T_A and T_B
    b = 100  # mini-batch size
    t = 100  # number of iterations
    print("Computing the k-means clustering of T_A and T_B, k=%s" % k)
    print("mini-batch k-means on T_A")
    T_A_representatives_idx, T_A_cluster_labels = clustering(T_A_dr, k=k, b=b, t=t)
    print("mini-batch k-means on T_B")
    T_B_representatives_idx, T_B_cluster_labels = clustering(T_B_dr, k=k, b=b, t=t)

    # 4) Compute graph matching between T_A_representatives and T_B_representatives
    alpha = 0.5
    max_iter1 = 100
    max_iter2 = 100
    corresponding_clusters = graph_matching(T_A[T_A_representatives_idx],
                                            T_B[T_B_representatives_idx],
                                            alpha=alpha, max_iter1=max_iter1,
                                            max_iter2=max_iter2)
    distance_clusters = distance_corresponding(T_A[T_A_representatives_idx],
                                               T_B[T_B_representatives_idx],
                                               corresponding_clusters)
    print("Median distance between corresponding clusters: %s" % np.median(distance_clusters))

    # 5) For each pair corresponding cluster, compute graph matching
    # between their streamlines
    correspondence_gm = graph_matching_all_corresponding_pairs(T_A, T_B, k,
                                                               T_A_cluster_labels,
                                                               T_B_cluster_labels,
                                                               corresponding_clusters,
                                                               alpha=alpha,
                                                               max_iter1=max_iter1,
                                                               max_iter2=max_iter2)

    # 6) Filling the missing correspondences in T_A with the
    # correspondences of the nearest neighbors in T_A
    correspondence = fill_missing_correspondences(correspondence_gm, T_A_dr)

    # 7) Compute the mean distance of corresponding streamlines, to
    # check the quality of the result
    distances = distance_corresponding(T_A, T_B, correspondence)
    print("Median distance of corresponding streamlines: %s" % np.median(distances))

    return correspondence, distances
예제 #2
0
def compute_kdt_and_dr(tract, num_prototypes=None):
    """Compute the dissimilarity representation of the tract and
    build the kd-tree.
    """
    tract = np.array(tract, dtype=np.object)
    print("Computing dissimilarity matrices...")
    if num_prototypes is None:
        num_prototypes = 40
        print("Using %s prototypes as in Olivetti et al. 2012." %
              num_prototypes)
    else:
        print("Using %s prototypes" % num_prototypes)
    t0 = time()
    distance = partial(parallel_distance_computation,
                       distance=bundles_distances_mam)
    dm_tract, prototype_idx = compute_dissimilarity(tract,
                                                    distance,
                                                    num_prototypes,
                                                    prototype_policy='sff',
                                                    verbose=False)
    print("%s sec." % (time() - t0))
    prototypes = tract[prototype_idx]
    print("Building the KD-tree of tract.")
    kdt = KDTree(dm_tract)
    return kdt, prototypes, dm_tract
def compute_kdtree_and_dr_tractogram( tractogram, num_prototypes=None):
    """Compute the dissimilarity representation of the target tractogram and 
    build the kd-tree.
    """
    tractogram = np.array(tractogram, dtype=np.object)
   
    print("Computing dissimilarity matrices")
    if num_prototypes is None:
        num_prototypes = 40
        print("Using %s prototypes as in Olivetti et al. 2012"
              % num_prototypes)

    print("Using %s prototypes" % num_prototypes)
    dm_tractogram, prototype_idx = compute_dissimilarity(tractogram,
                                                         num_prototypes=num_prototypes,
                                                         distance= bundles_distances_mam,
                                                         prototype_policy='sff',
                                                         n_jobs=-1,
                                                         verbose=False)
    
    prototypes = tractogram[prototype_idx]
    

    print("Building the KD-tree of tractogram")
    kdt = KDTree(dm_tractogram)
    
    return kdt, prototypes    
예제 #4
0
def compute_kdtree_and_dr_tractogram(tractogram,
                                     num_prototypes=40,
                                     distance_func=bundles_distances_mam,
                                     nb_points=20):
    """Compute the dissimilarity representation of the target tractogram and 
    build the kd-tree.
    """
    t0 = time.time()
    if distance_func == bundles_distances_mdf:
        print("Resampling the tractogram with %s points" % nb_points)
        tractogram = set_number_of_points(tractogram, nb_points)
    distance = partial(parallel_distance_computation, distance=distance_func)
    tractogram = np.array(tractogram, dtype=np.object)

    print("Computing dissimilarity matrices using %s prototypes..." %
          num_prototypes)
    dm_tractogram, prototype_idx = compute_dissimilarity(
        tractogram,
        distance,
        num_prototypes,
        prototype_policy='sff',
        verbose=False)
    prototypes = tractogram[prototype_idx]
    print("Building the KD-tree of tractogram.")
    kdt = KDTree(dm_tractogram)
    print("Time spent to compute the DR of the tractogram: %s seconds" %
          (time.time() - t0))
    return kdt, prototypes
예제 #5
0
def dissimilarity_eval(s, original_dist_matrixes, idxs, exec_number, track):
    """
    function evaluates stress, correlation distance, distortion and embedding computation time
     given array of dissimilarity embedding of streamlines s
    :param s: input data
    :param original_dist_matrixes: array of matrixes of stress_samples dimensions
    :param idx: array of indexes of data used for calculation of original_dist_matrixes
    :return:
    """

    from dissimilarity import compute_dissimilarity

    results_dir = "../eval_results/dissimilarity/"
    if not os.path.exists(results_dir):
        os.makedirs(results_dir)

    distance = partial(parallel_distance_computation,
                       distance=bundles_distances_mam)

    num_prototypes = [2, 4, 8, 10, 12, 20, 30, 40]

    for n in num_prototypes:

        resFileName = "num_prototypes_{0}__exec_num_{1}__n_streamlines_{2}__track_{3}".format(
            n, exec_number, len(idxs[0]), track)

        if os.path.isfile(results_dir + resFileName):
            continue

        start_time = time.time()
        embeddings, _ = compute_dissimilarity(s,
                                              verbose=True,
                                              k=n,
                                              distance=distance)
        comp_time = time.time() - start_time

        for (idx, original_dist) in zip(idxs, original_dist_matrixes):

            embedded_dist = pdist(embeddings[idx], 'euclidean')

            emb_stress_norm = stress_normalized(dist_embedd=embedded_dist,
                                                dist_original=original_dist)
            emb_stress = stress(dist_embedd=embedded_dist,
                                dist_original=original_dist)
            emb_correlation = correlation(embedded_dist.flatten(),
                                          original_dist.flatten())
            emb_distortion = distortion(dist_embedd=embedded_dist,
                                        dist_original=original_dist)
            emb_rel_dist = relative_distance_error(dist_embedd=embedded_dist,
                                                   dist_original=original_dist)

            # write results to file
            with open(results_dir + resFileName, 'w') as f:
                f.write('rel_dist\t' + str(emb_rel_dist) + '\n')
                f.write('stress\t' + str(emb_stress) + '\n')
                f.write('stress_norm\t' + str(emb_stress_norm) + '\n')
                f.write('correlation\t' + str(emb_correlation) + '\n')
                f.write('distortion\t' + str(emb_distortion) + '\n')
                f.write('n_streamlines\t' + str(len(s)) + '\n')
                f.write('eval_streamlines\t' + str(len(idx)) + '\n')
                f.write('exec_time\t' + str(comp_time) + '\n')
                f.write('n_prototypes\t' + str(n) + '\n')
예제 #6
0
    print("")
    print("Lipschitz embedding:")
    distance = euclidean_distance
    # distance = euclidean_distance_parallel
    t0 = time()
    Y_dissimilarity, R = compute_lipschitz(X, distance, k)
    print("%s sec." % (time() - t0))
    print_evaluation(X, distance, Y_dissimilarity)

    print("")
    print("Dissimilarity Representation:")
    distance = euclidean_distance
    # distance = euclidean_distance_parallel
    t0 = time()
    Y_dissimilarity, prototype_idx = compute_dissimilarity(X, distance, k)
    print("%s sec." % (time() - t0))
    print_evaluation(X, distance, Y_dissimilarity)

    print("")
    print("Fastmap:")
    distance = euclidean_distance
    # distance = euclidean_distance_parallel
    t0 = time()
    Y_fastmap = compute_fastmap(X, distance, k)
    print("%s sec." % (time() - t0))
    print_evaluation(X, distance, Y_fastmap)

    print("")
    print("lMDS:")
    distance = euclidean_distance
예제 #7
0
    k = 20
    
    print("Estimating the time and quality of embedded distances vs. original distances.")

    print("")
    print("Lipschitz embedding:")
    t0 = time()
    Y_dissimilarity, R = compute_lipschitz(X, distance, k)
    print("%s sec." % (time() - t0))
    print_evaluation(X, distance, Y_dissimilarity)

    print("")
    print("Dissimilarity Representation:")
    t0 = time()
    Y_dissimilarity, prototype_idx = compute_dissimilarity(X, distance, k,
                                                           prototype_policy='sff',
                                                           verbose=False)
    print("%s sec." % (time() - t0))
    print_evaluation(X, distance, Y_dissimilarity)

    print("")
    print("Fastmap:")
    t0 = time()
    Y_fastmap = compute_fastmap(X, distance, k)
    print("%s sec." % (time() - t0))
    print_evaluation(X, distance, Y_fastmap)

    print("")
    print("lMDS:")
    t0 = time()
    Y_lmds = compute_lmds(X, distance, k, nl=40,
예제 #8
0
import numpy as np
from numpy.random import uniform, randint
from dissimilarity import compute_dissimilarity

if __name__ == '__main__':

    n_streamlines = 10000
    len_min = 30
    len_max = 150
    print("Generating random tractography of %s streamlines." %
          n_streamlines)
    tracks = np.array([uniform(size=(randint(len_min, len_max), 3))
                       for i in range(n_streamlines)],
                      dtype=np.object)

    dissimilarity_matrix, prototype_idx = compute_dissimilarity(tracks,
                                                                verbose=True)
예제 #9
0
import numpy as np
from numpy.random import uniform, randint
from dissimilarity import compute_dissimilarity

if __name__ == '__main__':

    n_streamlines = 10000
    len_min = 30
    len_max = 150
    print("Generating random tractography of %s streamlines." % n_streamlines)
    tracks = np.array([
        uniform(size=(randint(len_min, len_max), 3))
        for i in range(n_streamlines)
    ],
                      dtype=np.object)

    dissimilarity_matrix, prototype_idx = compute_dissimilarity(tracks,
                                                                verbose=True)