pythongraphnetworkxpower-law

In networkx python, how to connect a new bunch of nodes and edges to each node in a graph?


Currently I created a graph as follow:

import networkx as nx
edges = []
for i in range (10):
    edges.append((i,i+1))
edges += [(10,0), (1,10), (2,8), (3,7), (4,6), (4,10), (5,10)]
# create the graph
G = nx.Graph()
G.add_nodes_from([i for i in range (11)])
G.add_edges_from(edges)

Now what I need is to connect a random number of new nodes to each node of the above core network, according to a power law distribution with 𝛼=3. So I got a new graph with power law distribution (for example: of 15 nodes):

s1 = nx.utils.powerlaw_sequence(15, 3) #15 nodes, power-law exponent 3
G1 = nx.expected_degree_graph(s1, selfloops=False)

Now how can I connect this new graph to a certain node in my previous network? Tried add_nodes_from but they seem to overwrite previous nodes, which is odd; and I can't make sure they're connected to a certain node. Or is there any straightforward way to do this? Thanks for helping me out!


Solution

  • The problem is due to the fact that nx.expected_degree_graph creates a graph whose nodes have labels 0 ... 14. If you try to join G and G1, nodes with the same name are merged.

    You need G1 to have nodes with unique labels. You can achieve such result by using the relabel_nodes function:

    relabel_dict = {node: node+len(G.nodes) for node in G1.nodes}
    G1 = nx.relabel_nodes(G1, relabel_dict)
    

    Now you can safely join G and G1 by using the compose function:

    new_G = nx.compose(G, G1)