Example #1
0
def extended_barabasi_albert(graph: nx.Graph, path: str) -> None:
    nodes = len(graph.nodes())
    p = 0.837
    q = 0.002
    # this will take awhile-awhile-awhile
    ba = nx.extended_barabasi_albert_graph(n=int(nodes / 10), m=1, p=p, q=q)
    dump_graph(ba, path)
Example #2
0
def gen_exBA(n=50, m=1, p=0, q=0):
    if (DEBUG):
        nx_graph = nx.extended_barabasi_albert_graph(
            n, m, p, q, seed=0)  # Deterministic seed for debugging
    else:
        nx_graph = nx.extended_barabasi_albert_graph(
            n, m, p, q)  # Truly random graph construction
    print(nx.info(nx_graph))
    print(f"Avg. Clustering: {nx.average_clustering(nx_graph):.5f}")
    print(
        f"Avg. PathLength: {nx.average_shortest_path_length(nx_graph,method='unweighted'):.5f}"
    )
    print(
        f"Assortativity: {nx.degree_pearson_correlation_coefficient(nx_graph):.5f}"
    )

    degree_sequence = sorted([d for n, d in nx_graph.degree()],
                             reverse=True)  # degree sequence
    degreeCount = collections.Counter(degree_sequence)
    max_deg = max([d for n, d in nx_graph.degree()])
    # for i in range(0,max_deg+1):
    #   if (i not in degreeCount):
    #     degreeCount[i] = 0
    deg, cnt = zip(*sorted(list(degreeCount.items()), key=lambda x: x[0]))

    log_deg = np.log10(deg)
    log_cnt = np.log10(cnt)
    slope, intercept, r_val, p_val, std_err = scipy.stats.linregress(
        log_deg[4:40], log_cnt[4:40])

    print(f"Min Deg: {min(deg)} Max Deg: {max(deg)}")
    print(f"Powerlaw fit exponent: {abs(slope):.3f}")

    fit_x = np.linspace(0, 3, 100)
    fit_y = slope * fit_x + intercept

    plt.figure()
    plt.scatter(np.log10(deg), np.log10(cnt))
    plt.plot(fit_x, fit_y, '-r', label=r'$\alpha=${:.3f}'.format(abs(slope)))
    plt.xlim(-0.5, 2.5)
    plt.ylim(-0.5, 4)
    plt.legend(loc='upper right')
    plt.show()

    return nx_graph
Example #3
0
    def test_extended_barabasi_albert(self, m=2):
        """
        Tests that the extended BA random graph generated behaves consistently.

        Tests the exceptions are raised as expected.

        The graphs generation are repeated several times to prevent lucky-shots

        """
        seeds = [42, 314, 2718]

        for seed in seeds:
            BA_model = nx.barabasi_albert_graph(100, m, seed)
            BA_model_edges = BA_model.number_of_edges()

            # This behaves just like BA, the number of edges must be the same
            G1 = nx.extended_barabasi_albert_graph(100, m, 0, 0, seed)
            assert G1.size() == BA_model_edges

            # More than twice more edges should have been added
            G1 = nx.extended_barabasi_albert_graph(100, m, 0.8, 0, seed)
            assert G1.size() > BA_model_edges * 2

            # Only edge rewiring, so the number of edges less than original
            G2 = nx.extended_barabasi_albert_graph(100, m, 0, 0.8, seed)
            assert G2.size() == BA_model_edges

            # Mixed scenario: less edges than G1 and more edges than G2
            G3 = nx.extended_barabasi_albert_graph(100, m, 0.3, 0.3, seed)
            assert G3.size() > G2.size()
            assert G3.size() < G1.size()

        # Testing exceptions
        ebag = nx.extended_barabasi_albert_graph
        pytest.raises(nx.NetworkXError, ebag, m, m, 0, 0)
        pytest.raises(nx.NetworkXError, ebag, 1, 0.5, 0, 0)
        pytest.raises(nx.NetworkXError, ebag, 100, 2, 0.5, 0.5)
Example #4
0
 def get_edge_list():
     cn = extended_barabasi_albert_graph(GC.num_cn_nodes,
                                         GC.num_edges_from_new,
                                         GC.bae_p,
                                         GC.bae_q,
                                         seed=GC.random_number_seed)
     if GC.random_number_seed is not None:
         GC.random_number_seed += 1
     out = GC.nx2favites(cn, 'u')
     f = gopen(expanduser("%s/contact_network.txt.gz" % GC.out_dir), 'wb',
               9)
     f.write('\n'.join(out).encode())
     f.write(b'\n')
     f.close()
     return out
Example #5
0
 def generate(self, size=None):
     num_nodes = self._get_size(size)
     max_m = int(2 * np.log2(num_nodes))
     found = False
     m = np.random.choice(max_m) + 1
     p = np.min([np.random.exponential(20), self.max_p])
     q = np.min([np.random.exponential(20), self.max_q])
     while not found:
         graph = nx.extended_barabasi_albert_graph(num_nodes, m, p, q)
         if nx.is_connected(graph):
             found = True
     logging.debug(
         'Generated {}-node extended B-A graph with max m: {}'.format(
             num_nodes, max_m))
     return graph
Example #6
0
 def createExtendedBarabasiAlbert(self,
                                  algorithm,
                                  num_nodes=100,
                                  m=3,
                                  p=0.3,
                                  q=0.1,
                                  seed=None):
     # type: (Union[AlgorithmCtorFactory,collections.abc.Sequence,Callable[[],pg.algorithm]], int, int, float, float, int) -> Topology
     '''
     Creates a topology based on the extended Barabási-Albert method.
     '''
     seed = self.getSeed(seed)
     return self._assignHub(
         self._processTopology(
             nx.extended_barabasi_albert_graph(num_nodes, m, p, q, seed),
             algorithm, Topology))
Example #7
0
In this iteration of a Barabasi Albert graphs, we run experiments to see how BA 
graph characteristics change as the various parameters in the graph increase/ decrease. 
Check README.txt for code documentation. 
'''

#Param combinations to be tested
n = [10, 20, 30, 40, 50]
m = [5, 10, 15, 20, 25]
p = [0.1, 0.3, 0.5, 0.7, 0.9]
q = [0.8, 0.6, 0.4, 0.2, 0.05]

#make graphs
graphs = []

for param1,param2,param3,param4 in zip(n, m, p, q):
    graphs.append(nx.extended_barabasi_albert_graph(param1,param2,param3,param4))

#Function to obtain graphs' average degree and expected average degree

def graph_statistics(g,p):
    
    k = 0
    
    for i in range(0, len(g.nodes())):
        k = k + g.degree(i)
    print("The average degree, <k> = " + str(k/len(g.nodes())))
    print("The expected average degree is " + str(p*(len(g.nodes())-1)))
    
    return

#Obtain statistics for all generated graphs
Example #8
0
    def test_random_graph(self):
        seed = 42
        G = nx.gnp_random_graph(100, 0.25, seed)
        G = nx.gnp_random_graph(100, 0.25, seed, directed=True)
        G = nx.binomial_graph(100, 0.25, seed)
        G = nx.erdos_renyi_graph(100, 0.25, seed)
        G = nx.fast_gnp_random_graph(100, 0.25, seed)
        G = nx.fast_gnp_random_graph(100, 0.25, seed, directed=True)
        G = nx.gnm_random_graph(100, 20, seed)
        G = nx.gnm_random_graph(100, 20, seed, directed=True)
        G = nx.dense_gnm_random_graph(100, 20, seed)

        G = nx.watts_strogatz_graph(10, 2, 0.25, seed)
        assert len(G) == 10
        assert G.number_of_edges() == 10

        G = nx.connected_watts_strogatz_graph(10, 2, 0.1, tries=10, seed=seed)
        assert len(G) == 10
        assert G.number_of_edges() == 10
        pytest.raises(nx.NetworkXError,
                      nx.connected_watts_strogatz_graph,
                      10,
                      2,
                      0.1,
                      tries=0)

        G = nx.watts_strogatz_graph(10, 4, 0.25, seed)
        assert len(G) == 10
        assert G.number_of_edges() == 20

        G = nx.newman_watts_strogatz_graph(10, 2, 0.0, seed)
        assert len(G) == 10
        assert G.number_of_edges() == 10

        G = nx.newman_watts_strogatz_graph(10, 4, 0.25, seed)
        assert len(G) == 10
        assert G.number_of_edges() >= 20

        G = nx.barabasi_albert_graph(100, 1, seed)
        G = nx.barabasi_albert_graph(100, 3, seed)
        assert G.number_of_edges() == (97 * 3)

        G = nx.barabasi_albert_graph(100, 3, seed, nx.complete_graph(5))
        assert G.number_of_edges() == (10 + 95 * 3)

        G = nx.extended_barabasi_albert_graph(100, 1, 0, 0, seed)
        assert G.number_of_edges() == 99
        G = nx.extended_barabasi_albert_graph(100, 3, 0, 0, seed)
        assert G.number_of_edges() == 97 * 3
        G = nx.extended_barabasi_albert_graph(100, 1, 0, 0.5, seed)
        assert G.number_of_edges() == 99
        G = nx.extended_barabasi_albert_graph(100, 2, 0.5, 0, seed)
        assert G.number_of_edges() > 100 * 3
        assert G.number_of_edges() < 100 * 4

        G = nx.extended_barabasi_albert_graph(100, 2, 0.3, 0.3, seed)
        assert G.number_of_edges() > 100 * 2
        assert G.number_of_edges() < 100 * 4

        G = nx.powerlaw_cluster_graph(100, 1, 1.0, seed)
        G = nx.powerlaw_cluster_graph(100, 3, 0.0, seed)
        assert G.number_of_edges() == (97 * 3)

        G = nx.random_regular_graph(10, 20, seed)

        pytest.raises(nx.NetworkXError, nx.random_regular_graph, 3, 21)
        pytest.raises(nx.NetworkXError, nx.random_regular_graph, 33, 21)

        constructor = [(10, 20, 0.8), (20, 40, 0.8)]
        G = nx.random_shell_graph(constructor, seed)

        def is_caterpillar(g):
            """
            A tree is a caterpillar iff all nodes of degree >=3 are surrounded
            by at most two nodes of degree two or greater.
            ref: http://mathworld.wolfram.com/CaterpillarGraph.html
            """
            deg_over_3 = [n for n in g if g.degree(n) >= 3]
            for n in deg_over_3:
                nbh_deg_over_2 = [
                    nbh for nbh in g.neighbors(n) if g.degree(nbh) >= 2
                ]
                if not len(nbh_deg_over_2) <= 2:
                    return False
            return True

        def is_lobster(g):
            """
            A tree is a lobster if it has the property that the removal of leaf
            nodes leaves a caterpillar graph (Gallian 2007)
            ref: http://mathworld.wolfram.com/LobsterGraph.html
            """
            non_leafs = [n for n in g if g.degree(n) > 1]
            return is_caterpillar(g.subgraph(non_leafs))

        G = nx.random_lobster(10, 0.1, 0.5, seed)
        assert max([G.degree(n) for n in G.nodes()]) > 3
        assert is_lobster(G)
        pytest.raises(nx.NetworkXError, nx.random_lobster, 10, 0.1, 1, seed)
        pytest.raises(nx.NetworkXError, nx.random_lobster, 10, 1, 1, seed)
        pytest.raises(nx.NetworkXError, nx.random_lobster, 10, 1, 0.5, seed)

        # docstring says this should be a caterpillar
        G = nx.random_lobster(10, 0.1, 0.0, seed)
        assert is_caterpillar(G)

        # difficult to find seed that requires few tries
        seq = nx.random_powerlaw_tree_sequence(10, 3, seed=14, tries=1)
        G = nx.random_powerlaw_tree(10, 3, seed=14, tries=1)
Example #9
0
    def get_scale_free_graph(nb_nodes: int,
                             nb_initial_nodes: int,
                             nb_seeds: int,
                             nb_to_select: int,
                             p_prob: float,
                             q_prob: float,
                             rng: Random = None) -> nx.Graph:
        """
        nb_nodes: number of nodes
        nb_initial_nodes: number of initial nodes
        nb_seeds: umber of seed nodes
        nb_to_select: number of selected nodes in a group
        p_prob: probability to add an edge between existing nodes
        q_prob: Probability value of rewiring of existing edges
        """

        MODULE_SIZE = nb_to_select
        min_espace_between_cluster = 1

        G = nx.extended_barabasi_albert_graph(nb_nodes, nb_initial_nodes,
                                              p_prob, q_prob, rng)
        G = Datasets.connect_graph(G, rng)

        selected = list(G.nodes())
        no_select = []
        # n: is the seed vertex. If we have more than one group (nb_seeds > 1) we use most_distance() selection.
        # cluster: is all the vertices selected at the end of the execution
        # group: is each group selected in each interaction (each module).
        cluster = set()
        for i in range(nb_seeds):
            if i > 0:
                # most_distance() tries to identify a distant seed based on the other vertices already selected
                n = Datasets.most_distance(G, selected, cluster)
            else:
                n = rng.sample(selected, 1)[0]
            group = set()
            group.add(n)
            print("seed:" + str(n))

            while group.__len__() < MODULE_SIZE:
                # get_order() returns the next neighborhood level after the vertices selected in the module
                # if the neighborhood level 'nb_to_select' still contains vertices already selected previously
                # the function returns -1
                order = Datasets.get_order(G, n, nb_to_select, no_select)

                if order < 0:
                    print(
                        "ERRO [1]! The density and size of the network prevent you from creating a network with "
                        + str(nb_seeds) + " modules of size " +
                        str(MODULE_SIZE) + " each.\n")
                    print("The modules need to be far away on the network!\n")
                    sys.exit(1)

                rnd = rng.random()
                # checks to neighborhood order according with the function 1/pow(10, dist)

                if 1 >= rnd > 0.1:
                    order = order + 1
                elif 0.01 < rnd <= 0.1:
                    order = order + 2
                elif 0.001 < rnd <= 0.01:
                    order = order + 3
                elif 0.0001 < rnd <= 0.001:
                    order = order + 4

                # neighbors_order returns all neighbors of the node n of a specific order
                population = Datasets.neighbors_order(G, n, order)

                # Removes neighbors and nodes from other groups already identified
                # besides the nodes of this same group that have already been chosen.
                population = population - set(no_select)

                ## Erro! When a neighborhood level 'order' is composed only of vertices already selected.
                if population.__len__() == 0:
                    print(
                        "ERRO [2]! The density and size of the network prevent you from creating a network with "
                        + str(nb_seeds) + " modules of size " +
                        str(MODULE_SIZE) + " each.\n")
                    print("The modules need to be far away on the network!\n")
                    sys.exit(1)
                    # order = Datasets.get_order(G, n, nb_to_select, no_select)
                    # population = Datasets.neighbors_order(G, n, order)

                else:
                    # one node is chosen randomly in the population
                    sel = rng.sample(list(population), 1)[0]
                    group.add(sel)
                    no_select = list(set(no_select).union(group))
                    #nb_selected += 1

            print("group " + str(i + 1) + ":")
            print(group)

            cluster.update(group)
            no_select = set()
            for j in cluster:
                no_select = no_select.union(
                    Datasets.neighborhood(G, j, min_espace_between_cluster))
            selected = list(set(selected) - set(no_select))

        # assign a uniform distribution for all nodes
        low, up = 0, 1
        for node in G.nodes:
            G.nodes[node]['weight'] = rng.uniform(low, up)
            G.nodes[node]['truehit'] = 0

        # assign a truncated normal distribution for each node in cluster
        mean, std = 0, 0.05
        a, b = (low - mean) / std, (up - mean) / std
        for x in cluster:
            G.nodes[x]['weight'] = 1 - truncnorm.rvs(
                loc=mean, scale=std, a=a, b=b)
            G.nodes[x]['truehit'] = 1

        return Datasets.init_graph(G,
                                   edge_weight=None,
                                   default_groups='truehit')
Example #10
0
import sys,json
import networkx as nx

if len(sys.argv) != 6:
    print(f"Usage: python {sys.argv[0]} <N> <m> <p> <q> <seed>", file=sys.stderr)
    raise Exception("invalid number of arguments")

g = nx.extended_barabasi_albert_graph( int(sys.argv[1]), int(sys.argv[2]), float(sys.argv[3]), float(sys.argv[4]), int(sys.argv[5]))

import analyze_pk

alpha, xmin = analyze_pk.analyze_pk(g, 'pk.png')
with open('_output.json', 'w') as f:
    json.dump({"alpha": alpha, "x_min": xmin}, f)

Example #11
0
# G = nx.complete_graph(population_size)

# regular random graph
# degree = 3
# G = nx.random_regular_graph(degree, population_size)

# small-world
# t_k = 10
# t_p = 0.3
# G = nx.connected_watts_strogatz_graph(population_size, t_k, t_p)

# Barabasi_albert scale-free
t_p = 0.1
t_q = 0.1
t_m = 3
G = nx.extended_barabasi_albert_graph(population_size, t_m, t_p, t_q)

print(nx.info(G))

#Creating random seedset with k length
k = 10

# new_seedset = random.sample(s.graph.nodes, k)
new_infected = []

p = 0.1  #parameter of system
# s = Simulation(G, new_seedset,p)
s = Simulation(G, [], p)

initial_seedset = random.sample(s.graph.nodes, k)