egocentric_network_1.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import networkx as nx
  2. import matplotlib.pyplot as plt
  3. def EgocentricNetwork(G,v):
  4. egocentric_network_edge_list = []
  5. egocentric_network_node_list = [v]
  6. for i in G.neighbors(v):
  7. egocentric_network_node_list.append(i)
  8. egocentric_network_edge_list.append((v,i))
  9. return egocentric_network_edge_list,egocentric_network_node_list
  10. #takes input from the file and creates a graph
  11. def CreateGraph():
  12. G = nx.Graph()
  13. f = open('input.txt')
  14. n = int(f.readline())
  15. for i in range(n):
  16. G.add_node(i+1)
  17. no_of_edges = int(f.readline())
  18. for i in range(no_of_edges):
  19. graph_edge_list = f.readline().split()
  20. G.add_edge(int(graph_edge_list[0]), int(graph_edge_list[1]))
  21. vert = int(f.readline())
  22. return G, vert
  23. #draws the graph and displays the weights on the edges
  24. def DrawGraph(G,egocentric_network_edge_list,egocentric_network_node_list, vert):
  25. pos = nx.spring_layout(G)
  26. 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
  27. nx.draw_networkx_edges(G, pos, edgelist = egocentric_network_edge_list , width = 2.5, alpha = 0.8, edge_color = 'red')
  28. nx.draw_networkx_nodes(G,pos, nodelist = egocentric_network_node_list, node_color = 'red', alpha = 0.5)
  29. nx.draw_networkx_nodes(G,pos,nodelist=[vert],node_color='green',node_size=500,alpha=0.8)
  30. return pos
  31. def CentralityMeasures(G):
  32. # Betweenness centrality
  33. bet_cen = nx.betweenness_centrality(G)
  34. # Closeness centrality
  35. clo_cen = nx.closeness_centrality(G)
  36. # Eigenvector centrality
  37. eig_cen = nx.eigenvector_centrality(G)
  38. # Degree centrality
  39. deg_cen = nx.degree_centrality(G)
  40. #print bet_cen, clo_cen, eig_cen
  41. #main function
  42. if __name__== "__main__":
  43. G,vert = CreateGraph()
  44. egocentric_network_edge_list,egocentric_network_node_list = EgocentricNetwork(G,vert)
  45. DrawGraph(G,egocentric_network_edge_list,egocentric_network_node_list, vert)
  46. CentralityMeasures(G)
  47. plt.show()