proffreda

barabasi.py

Apr 17th, 2017
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. import networkx as nx
  2. import random
  3. def _random_subset(seq,m):
  4. """ Return m unique elements from seq.
  5.  
  6. This differs from random.sample which can return repeated
  7. elements if seq holds repeated elements.
  8. """
  9. targets=set()
  10. while len(targets)<m:
  11. x=random.choice(seq)
  12. targets.add(x)
  13. return targets
  14.  
  15. def barabasi_albert_graph(n, m, seed=None):
  16. """Return random graph using Barabási-Albert preferential attachment model.
  17.  
  18. A graph of n nodes is grown by attaching new nodes each with m
  19. edges that are preferentially attached to existing nodes with high
  20. degree.
  21.  
  22. """
  23.  
  24. if seed is not None:
  25. random.seed(seed)
  26.  
  27. # Add m initial nodes (m0 in barabasi-speak)
  28. G=nx.empty_graph(m)
  29. G.name="barabasi_albert_graph(%s,%s)"%(n,m)
  30. # Target nodes for new edges
  31. targets=list(range(m))
  32. # List of existing nodes, with nodes repeated once for each adjacent edge
  33. repeated_nodes=[]
  34. # Start adding the other n-m nodes. The first node is m.
  35. source=m
  36. while source<n:
  37. # Add edges to m nodes from the source.
  38. G.add_edges_from(zip([source]*m,targets))
  39. # Add one node to the list for each new edge just created.
  40. repeated_nodes.extend(targets)
  41. # And the new node "source" has m edges to add to the list.
  42. repeated_nodes.extend([source]*m)
  43. # Now choose m unique nodes from the existing nodes
  44. # Pick uniformly from repeated_nodes (preferential attachement)
  45. targets = _random_subset(repeated_nodes,m)
  46. source += 1
  47. return G
  48.  
  49. G=nx.Graph()
  50. G= barabasi_albert_graph(10, 3)
  51. print("Nodes of graph: ")
  52. print(G.nodes())
  53. print("Edges of graph: ")
  54. print(G.edges())
  55. degree_sequence=sorted(nx.degree(G).values(),reverse=True) # degree sequence
  56. #print "Degree sequence", degree_sequence
  57. dmax=max(degree_sequence)
  58. print(dmax, degree_sequence)
Advertisement
Add Comment
Please, Sign In to add comment