Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import networkx as nx
- import random
- def _random_subset(seq,m):
- """ Return m unique elements from seq.
- This differs from random.sample which can return repeated
- elements if seq holds repeated elements.
- """
- targets=set()
- while len(targets)<m:
- x=random.choice(seq)
- targets.add(x)
- return targets
- def barabasi_albert_graph(n, m, seed=None):
- """Return random graph using Barabási-Albert preferential attachment model.
- A graph of n nodes is grown by attaching new nodes each with m
- edges that are preferentially attached to existing nodes with high
- degree.
- """
- if seed is not None:
- random.seed(seed)
- # Add m initial nodes (m0 in barabasi-speak)
- G=nx.empty_graph(m)
- G.name="barabasi_albert_graph(%s,%s)"%(n,m)
- # Target nodes for new edges
- targets=list(range(m))
- # List of existing nodes, with nodes repeated once for each adjacent edge
- repeated_nodes=[]
- # Start adding the other n-m nodes. The first node is m.
- source=m
- while source<n:
- # Add edges to m nodes from the source.
- G.add_edges_from(zip([source]*m,targets))
- # Add one node to the list for each new edge just created.
- repeated_nodes.extend(targets)
- # And the new node "source" has m edges to add to the list.
- repeated_nodes.extend([source]*m)
- # Now choose m unique nodes from the existing nodes
- # Pick uniformly from repeated_nodes (preferential attachement)
- targets = _random_subset(repeated_nodes,m)
- source += 1
- return G
- G=nx.Graph()
- G= barabasi_albert_graph(10, 3)
- print("Nodes of graph: ")
- print(G.nodes())
- print("Edges of graph: ")
- print(G.edges())
- degree_sequence=sorted(nx.degree(G).values(),reverse=True) # degree sequence
- #print "Degree sequence", degree_sequence
- dmax=max(degree_sequence)
- print(dmax, degree_sequence)
Advertisement
Add Comment
Please, Sign In to add comment