Esempio n. 1
0
def test_randmio_und_seed():
    x = load_sample(thres=0.4)
    swaps = 5
    ref, _ = bct.randmio_und(x, swaps, seed=SEED)
    test_same, _ = bct.randmio_und(x, swaps, seed=SEED)
    test_diff, _ = bct.randmio_und(x, swaps, seed=SEED * 2)

    assert np.allclose(ref, test_same)
    assert not np.allclose(ref, test_diff)
Esempio n. 2
0
def omega_sigma(matrix):
    """Returns the small-world coefficients (omega & sigma) of a graph.
    Omega ranges between -1 and 1. Values close to 0 mean the matrix
    features small-world characteristics.
    Values close to -1 mean the network has a lattice structure and values
    close to 1 mean G is a random network.

    A network is commonly classified as small-world if sigma > 1.

    Parameters
    ----------
    matrix : numpy.ndarray
        A weighted undirected graph.
    Returns
    -------
    smallworld : tuple of float
        The small-work coefficients (omega & sigma).
    Notes
    -----
    The implementation is adapted from the algorithm by Telesford et al. [1]_.
    References
    ----------
    .. [1] Telesford, Joyce, Hayasaka, Burdette, and Laurienti (2011).
           "The Ubiquity of Small-World Networks".
           Brain Connectivity. 1 (0038): 367-75.  PMC 3604768. PMID 22432451.
           doi:10.1089/brain.2011.0038.
    """
    transitivity_rand_list = []
    transitivity_latt_list = []
    path_length_rand_list = []
    for i in range(10):
        logging.debug('Generating random and lattice matrices, '
                      'iteration #{}.'.format(i))
        random = bct.randmio_und(matrix, 10)[0]
        lattice = bct.latmio_und(matrix, 10)[1]

        transitivity_rand_list.append(bct.transitivity_wu(random))
        transitivity_latt_list.append(bct.transitivity_wu(lattice))
        path_length_rand_list.append(avg_cast(bct.distance_wei(random)[0]))

    transitivity = bct.transitivity_wu(matrix)
    path_length = avg_cast(bct.distance_wei(matrix)[0])
    transitivity_rand = np.mean(transitivity_rand_list)
    transitivity_latt = np.mean(transitivity_latt_list)
    path_length_rand = np.mean(path_length_rand_list)

    omega = (path_length_rand / path_length) - \
        (transitivity / transitivity_latt)
    sigma = (transitivity / transitivity_rand) / \
        (path_length / path_length_rand)

    return float(omega), float(sigma)
def calculate_network_metrics_bin_und(binarized_matrix, random_network_n=100):
    """
    Calculate the network metrics for the original and the randomized network
    """
    assert len(np.unique(binarized_matrix)) == 2  #binarized matrix
    assert np.allclose(binarized_matrix, binarized_matrix.T)  #undirected

    original_network_metrics = calculate_path_and_efficiency_bin(
        binarized_matrix)

    random_network = (bct.randmio_und(binarized_matrix, 2)[0]
                      for _ in range(random_network_n))

    random_network_metrics = np.zeros(4, )
    for _ in range(random_network_n):
        random_network_metrics += np.asarray(
            calculate_path_and_efficiency_bin(
                next(random_network)))  #sum up all the randomizations.

    random_network_metrics = random_network_metrics / random_network_n  #get the average values

    return np.array(original_network_metrics), random_network_metrics
def gen_null_matrices(num_rand, study_ids, dest_dir):

    for study_id in study_ids:
        t1 = time.time()

        mat = get_data_matrices()[study_id]
        num_rois = np.shape(mat)[1]

        null_matrix = np.zeros((num_rois, num_rois, num_rand))

        for r in xrange(0, num_rand):
            n_l = bct.randmio_und(mat, 3)
            null_matrix[:, :, r] = n_l[0]
            del n_l

        pik_name = os.path.join(dest_dir, "null_" + study_id + ".dat")
        with open(pik_name, "wb") as f:
            pickle.dump(null_matrix, f)

        del null_matrix

        t2 = time.time() - t1
        print "Elapsed individual time, subject = %s: %f" % (study_id, t2)
        node_state_mod_resample = signal.resample(node_state_mod, spreadMod_state.shape[0])
        #sns.heatmap(node_state_mod_resample.T, cbar=False)
        #sns.heatmap(spreadMod_state.T, cbar=False)
        if (node_state_mod_resample == 0).all():#if entire prediction is zero, make the correlation zero
            corrs[r] = 0
        else:
            corrs[r] = spearmanr(node_state_mod_resample.flatten(), spreadMod_state.flatten())[0]
        print (corrs[r])
    return corrs

corrs = get_LTM(SC_hat)
Nnull = 2
corrs_null = np.zeros(shape = (Nnull, len(corrs)))
for nu in range(Nnull):
    print(nu)
    SC_null = bct.randmio_und(SC, 30)[0]
    dm_data = DM.diffusionModels(SC, SC_regions, spread, spread_regions, electrodeLocalization)
    SC_hat = dm_data.preprocess_SC(SC_null, 0.4)
    corrs_null[nu,:] = get_LTM(SC_hat)




ind = np.argsort(corrs)[::-1]

corrs_order = corrs[ind]
corrs_null_order = corrs_null[:,ind]
corrs_order_null_df = pd.DataFrame(corrs_null_order).melt()

fig, ax = plt.subplots(1,1, figsize = (5,5), dpi = 300)
sns.lineplot(x = range(len(corrs_order)), y = corrs_order, ax = ax)