egocentric_network_1_5.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import networkx as nx
  2. import matplotlib.pyplot as plt
  3. import itertools
  4. def EgocentricNetwork(G,v):
  5. egocentric_network_edge_list = []
  6. egocentric_network_node_list = [v]
  7. for i in G.neighbors(v):
  8. egocentric_network_node_list.append(i)
  9. egocentric_network_edge_list.append((v,i))
  10. egocentric_network_node_list.sort()
  11. egocentric_network_edge_list = list(tuple(sorted(p)) for p in egocentric_network_edge_list)
  12. for i in list(itertools.combinations(egocentric_network_node_list, 2)): #generates all possible pairs of nodes
  13. if i in G.edges() and i not in egocentric_network_edge_list:
  14. egocentric_network_edge_list.append(i)
  15. return egocentric_network_edge_list,egocentric_network_node_list
  16. #takes input from the file and creates a graph
  17. def CreateGraph():
  18. G = nx.Graph()
  19. f = open('input.txt')
  20. n = int(f.readline())
  21. for i in range(n):
  22. G.add_node(i+1)
  23. no_of_edges = int(f.readline())
  24. for i in range(no_of_edges):
  25. graph_edge_list = f.readline().split()
  26. G.add_edge(int(graph_edge_list[0]), int(graph_edge_list[1]))
  27. vert = int(f.readline())
  28. return G, vert
  29. #draws the graph and displays the weights on the edges
  30. def DrawGraph(G, egocentric_network_edge_list, egocentric_network_node_list, vert):
  31. pos = nx.spring_layout(G)
  32. nx.draw(G, pos, with_labels = True, node_color = 'blue', alpha = 0.8) #with_labels=true is to show the node number in the output graph
  33. nx.draw_networkx_edges(G, pos, edgelist = egocentric_network_edge_list , width = 2.5, alpha = 0.8, edge_color = 'red')
  34. nx.draw_networkx_nodes(G,pos, nodelist = egocentric_network_node_list, node_color = 'red', alpha = 0.5)
  35. nx.draw_networkx_nodes(G,pos,nodelist=[vert],node_color='green',node_size=500,alpha=0.8)
  36. return pos
  37. def CentralityMeasures(G):
  38. # Betweenness centrality
  39. bet_cen = nx.betweenness_centrality(G)
  40. # Closeness centrality
  41. clo_cen = nx.closeness_centrality(G)
  42. # Eigenvector centrality
  43. eig_cen = nx.eigenvector_centrality(G)
  44. # Degree centrality
  45. deg_cen = nx.degree_centrality(G)
  46. #print bet_cen, clo_cen, eig_cen
  47. #main function
  48. if __name__== "__main__":
  49. G, vert = CreateGraph()
  50. egocentric_network_edge_list,egocentric_network_node_list = EgocentricNetwork(G, vert)
  51. DrawGraph(G,egocentric_network_edge_list, egocentric_network_node_list, vert)
  52. CentralityMeasures(G)
  53. plt.show()