简体   繁体   中英

How can I randomly permute the nodes of a graph with python in networkx?

I think this can be done with relabel_nodes, but how can I create a mapping that permutes the nodes? I want to permute the nodes of a graph while keeping the network structure intact. Currently I am rebuilding the graph with a shuffled set of nodes which doesn't seem the most efficient way to go about things:

import networkx as nx
import random

n=10
nodes=[]
for i in range(0,n):
  nodes.append(i)
G=nx.gnp_random_graph(n,.5)
newG=nx.empty_graph(n)
shufflenodes=nodes
random.shuffle(shufflenodes)
for i in range(0,n-1):
  for j in range(i+1,n):
    if(G.has_edge(i,j)):
      newG.add_edge(shufflenodes[i],shufflenodes[j])

Anyone have any ideas how to speed this up?

What you can do is to build a random mapping and use relabel_nodes .

Code:

# create a random mapping old label -> new label
node_mapping = dict(zip(G.nodes(), sorted(G.nodes(), key=lambda k: random.random())))
# build a new graph
G_new = nx.relabel_nodes(G, node_mapping)

Example:

>>> G.nodes()
NodeView((0, 1, 2, 3, 4))
>>> G.edges()
EdgeView([(0, 1), (0, 2), (0, 3), (1, 2), (3, 4)])
>>> node_mapping
{0: 2, 1: 0, 2: 3, 3: 4, 4: 1}
>>> G_new.nodes()
NodeView((2, 0, 3, 4, 1))
>>> G_new.edges()
EdgeView([(2, 0), (2, 3), (2, 4), (0, 3), (4, 1)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM