コード例 #1
0
ファイル: test_motifs.py プロジェクト: gialdetti/netsci
def test_counts():
    n = 100
    p = 0.1

    A = nsr.erdos_renyi(n, p)

    print("Motifs (fast):")
    f = nsm.motifs(A)
    print("\tf = %s" % f)

    # print "Motifs (v0):"
    # f_v0 = motifs_v0(A)
    # print "\tf_v0 =", f_v0
    # print "Comparison: ", zip(f, f_v0)
    # npt.assert_equal(f[3:], f_v0[3:], "Motif frequencies of different versions are not compatible")

    print("Motifs (naive):")
    f_naive = nsm.motifs(A, algorithm='brute-force')
    print("\tf_naive = %s" % f_naive)
    print("Comparison: %s" % list(zip(f, f_naive)))
    npt.assert_equal(
        f[3:], f_naive[3:],
        "Motif frequencies from optimized algorithm are not correct")

    C3n = comb(n, 3)
    npt.assert_equal(sum(f_naive), C3n)
コード例 #2
0
def test_a_single_pattern_permuations():
    tid = 6
    M = nsm.triad_patterns()[tid]
    # plot_a_triad(M, r=.5)

    A = np.zeros(shape=(5, 5), dtype=np.int64)
    A[1:4, 1:4] = M

    expected_f = np.eye(16, dtype=np.int64)[tid]
    for permutation in itertools.permutations(range(5), 5):
        print("# permutation:", permutation)
        perm_B = permute_array(A, permutation)
        print(perm_B)

        f = nsm.motifs(perm_B)
        f[0:3] = 0
        npt.assert_equal(f, expected_f)

        f, participation = nsm.motifs(perm_B, participation=True)
        f[0:3] = 0
        print(participation)
        npt.assert_equal(f, expected_f)
        npt.assert_equal(
            [len(p) for p in participation][3:], f[3:],
            "Frequency and participation lists are not consistent")

        r, g, b = [
            np.where(np.array(permutation) == i)[0][0] for i in [1, 2, 3]
        ]
        print("(R=%d, G=%d, B=%d) vs. participation=%s\n" %
              (r, g, b, participation[tid][0]))
        npt.assert_array_equal(participation[tid][0], [r, g, b])
コード例 #3
0
    def create_graph_motifs(self):
        """Creates the graph that contains only motifs of the type A->B<-C,
        using the results of the detected motifs.
        
        """
        motifs = nsm.motifs(
            self.binary_adjacency_matrix.astype(int),
            algorithm='louzoun', participation=True)

        G_only_motif = nx.DiGraph()

        for triplet in motifs[1][3]:
            G_only_motif.add_node(triplet[0])
            G_only_motif.add_node(triplet[1])
            G_only_motif.add_node(triplet[2])
            G_only_motif.add_edge(triplet[0], triplet[1])
            G_only_motif.add_edge(triplet[2], triplet[1])

        new_labels = {}
        for node in G_only_motif.nodes:
            new_labels[node] = self.channels[node]
        nx.relabel.relabel_nodes(G_only_motif, new_labels, copy=False)

        nodes = set(self.G.nodes)
        m_nodes = set(G_only_motif)
        nodes_diff = nodes.difference(m_nodes)

        G_only_motif.add_nodes_from(nodes_diff)
        print("Density:", nx.density(G_only_motif))

        plt.figure(figsize=(12, 10))
        nx.draw_networkx(G_only_motif, pos=self.channel_locations, arrowsize=1,
                         node_color='lightcyan', edge_color='silver')
コード例 #4
0
ファイル: test_motifs.py プロジェクト: gialdetti/netsci
def test_basic_patterns():
    print("Testing basic patterns..")
    M = nsm.triad_patterns()
    for i in np.arange(len(M)):
        motif = M[i].copy()
        print("Motif #%d\n%s" % (i, motif))
        f_naive = nsm.motifs(motif, algorithm='brute-force')
        npt.assert_equal(motif, M[i],
                         "Argument array was altered during execution")
        print("\t%s %s" % (f_naive[0:3], f_naive[3:]))
        npt.assert_equal(np.where(f_naive == 1)[0], np.array([i]))

        if i >= 3:
            f = nsm.motifs(motif)
            npt.assert_equal(motif, M[i],
                             "Argument array was altered during execution")
            print("\t%s %s" % (f[0:3], f[3:]))
            npt.assert_equal(np.where(f == 1)[0], np.array([i]))
コード例 #5
0
 def compute_motifs(self, algorithm):
     """Compute motifs of a given graph with netsci package, 
     using the specified algorithm.
     Args:
     ----------
     algorithm : string
         2 options:
             - 'brute-force' : the naive implementation using brute force algorithm.
             The complexity is high $(O(|V|^3))$, counts all 16 triplets.
             - 'louzoun' : an efficient algorithm for sparse networks.
             The complexity is low $(O(|E|))$, but it counts only the 13 connected
             triplets (the first 3 entries will be -1).
     """
     motifs = nsm.motifs(
         self.binary_adjacency_matrix.astype(int), algorithm=algorithm)
     print(motifs)
     nsv.bar_motifs(motifs)
コード例 #6
0
def test_geometrical_network():
    n = 10
    Ys = np.random.rand(n)
    Is, Js = np.mgrid[0:n, 0:n]
    P = (Ys[Is] < Ys[Js]).astype(np.int8)

    A = np.random.binomial(1, P)
    f, participation = nsm.motifs(A, participation=True)
    npt.assert_equal([len(p) for p in participation][3:], f[3:],
                     "Frequency and participation lists are not consistent")

    part6 = participation[6]
    assert np.all([(Ys[r] < Ys[g] < Ys[b]) for (r, g, b) in part6])

    fy = Ys[np.array(part6)]
    plt.plot([1, 2, 3], fy.T, '-o', zorder=1, alpha=.25, lw=1)
    plt.errorbar([1, 2, 3],
                 fy.mean(axis=0),
                 fy.std(axis=0),
                 lw=2,
                 color='k',
                 zorder=2)
コード例 #7
0
ファイル: test_motifs.py プロジェクト: gialdetti/netsci
    print("Comparison: %s" % list(zip(f, f_naive)))
    npt.assert_equal(
        f[3:], f_naive[3:],
        "Motif frequencies from optimized algorithm are not correct")

    C3n = comb(n, 3)
    npt.assert_equal(sum(f_naive), C3n)


if False:
    import netsci.visualization.motifs as nsv

    n, p = 250, 0.2
    A = nsr.er(n, p)

    C3n = comb(n, 3)
    f_analytic = C3n * triads_mean(p)

    print("Counting motifs..")
    f = nsm.motifs(A)

    print("Plotting..")
    nsv.bar_motifs(f,
                   f_analytic,
                   triad_order=triad_order_nn4576,
                   title="nn4576 triad order")
    nsv.bar_motifs(f,
                   f_analytic,
                   triad_order=triad_order_bct,
                   title="BCT triad order")
コード例 #8
0
ファイル: test_motifs_gpu.py プロジェクト: gialdetti/netsci
import logging
logging.basicConfig()
logging.getLogger('netsci').setLevel(logging.DEBUG)

import numpy as np
import numpy.testing as npt

from netsci.models.random import erdos_renyi
import netsci.metrics.motifs as nsm

A = erdos_renyi(100, p=0.01)
f = nsm.motifs(A, algorithm='matmul')
print(f"f (matmul) = {f}")

f_expected = nsm.motifs(A)
print(f"f_expected = {f_expected}")
npt.assert_equal(f[3:], f_expected[3:])

f_expected_bf = nsm.motifs(A, algorithm='brute-force')
print(f"f_expected_bf = {f_expected_bf}")
npt.assert_equal(f, f_expected_bf)
コード例 #9
0
from tensorflow.python.client import device_lib

print(
    'devices:',
    {d.name: d.physical_device_desc
     for d in device_lib.list_local_devices()})

A = erdos_renyi(n=2000, p=0.1, random_state=71070)
print(f'A: {A.shape}, p = {nsm.sparsity(A):.4f}')

configurations = [('matmul', 'GPU'), ('matmul', 'CPU'), ('louzoun', 'CPU')]

for algorithm, device in configurations:
    with tf.device(f'/{device}:0'):
        with Timer(logger=print, desc=f'{algorithm}:{device}'):
            print(nsm.motifs(A, algorithm=algorithm))
"""Colab
devices = {
  '/device:CPU:0': '', 
  '/device:GPU:0': 'device: 0, name: Tesla K80, pci bus id: 0000:00:04.0, compute capability: 3.7'
}

A: (2000, 2000), p = 0.1001

matmul:GPU took 0.680 sec.
matmul:CPU took 18.909 sec.
louzoun:CPU took 149.726 sec.
"""
"""MBP M1 Max
devices: {
  '/device:CPU:0': '',