# Start writing code here...
!pip install networkx==2.6.3
import csv
from operator import itemgetter
import networkx as nx
from networkx.algorithms import community
with open('node.csv', 'r') as nodecsv:
nodereader = csv.reader(nodecsv) # Read the node
nodes = [n for n in nodereader][1:]
node_id = [n[0] for n in nodes] # 节点id是唯一标识
with open('edge.csv', 'r') as edgecsv:
edgereader = csv.reader(edgecsv) # Read the edge
edges = [tuple(e) for e in edgereader][1:] # Retrieve the data
edges
print(len(node_id))
print(len(edges))
G = nx.Graph() # Initialize a Graph object
G.add_nodes_from(node_id) # Add nodes to the Graph
G.add_edges_from(edges) # Add edges to the Graph
print(nx.info(G)) # Print information about the Graph
# Create an empty dictionary for each attribute
cp_dict = {}
lb_dict = {}
for node in nodes: # Loop through the list of nodes, one row at a time
cp_dict[node[0]] = node[1]
lb_dict[node[0]] = node[2]
# Add each dictionary as a node attribute to the Graph object
nx.set_node_attributes(G, cp_dict, 'caipin')
nx.set_node_attributes(G, lb_dict, 'label')
# # Loop through each node, to access and print all the "birth_year" attributes
# for n in G.nodes():
# print(n, G.nodes[n]['caipin'])
for n in G.nodes():
print(n, G.nodes[n]['label'])
density = nx.density(G)#网络密度
print("Network density:", density)
shrimp_cabage_path = nx.shortest_path(G, source='6', target='83')# shrimp和Chinese carbage之间的最短路径
print("Shortest path between pork and wine:", shrimp_cabage_path)
print("Length of that path:", len(shrimp_cabage_path)-1)
print(nx.is_connected(G))
# 找到最大连通图
components = nx.connected_components(G)
largest_component = max(components, key=len)
# Create a "subgraph" of just the largest component
# Then calculate the diameter of the subgraph, just like you did with density.
#
subgraph = G.subgraph(largest_component)
diameter = nx.diameter(subgraph)
print("Network diameter of largest component:", diameter)
triadic_closure = nx.transitivity(G)
print("Triadic closure:", triadic_closure)
degree_dict = dict(G.degree(G.nodes()))
nx.set_node_attributes(G, degree_dict, 'degree')
print(G.nodes['20'])
sorted_degree = sorted(degree_dict.items(), key=itemgetter(1), reverse=True)
print("Top 20 nodes by degree:")
for d in sorted_degree[:20]:
print(d)
betweenness_dict = nx.betweenness_centrality(G) # Run betweenness centrality
eigenvector_dict = nx.eigenvector_centrality(G) # Run eigenvector centrality
# Assign each to an attribute in your network
nx.set_node_attributes(G, betweenness_dict, 'betweenness')
nx.set_node_attributes(G, eigenvector_dict, 'eigenvector')
sorted_betweenness = sorted(betweenness_dict.items(), key=itemgetter(1), reverse=True)
print("Top 20 nodes by betweenness centrality:")
for b in sorted_betweenness[:20]:
print(b)
#First get the top 20 nodes by betweenness as a list
top_betweenness = sorted_betweenness[:20]
#Then find and print their degree
for tb in top_betweenness: # Loop through top_betweenness (or eigenvector)
degree = degree_dict[tb[0]] # Use degree_dict to access a node's degree, see footnote 2
print("ID:", tb[0], "| Betweenness Centrality:", tb[1], "| Degree:", degree)
sorted_eigenvector = sorted(eigenvector_dict.items(), key=itemgetter(1), reverse=True)
print("Top 20 nodes by eigenvector centrality:")
for b in sorted_eigenvector[:20]:
print(b)
#First get the top 20 nodes by eigenvector as a list
top_eigenvector = sorted_eigenvector[:20]
#Then find and print their degree
for tb in top_eigenvector: # Loop through top_eigenvector
degree = degree_dict[tb[0]] # Use degree_dict to access a node's degree, see footnote 2
print("ID:", tb[0], "| Eigenvector Centrality:", tb[1], "| Degree:", degree)
communities = community.greedy_modularity_communities(G)#模块化!!!
modularity_dict = {} # Create a blank dictionary
for i,c in enumerate(communities): # Loop through the list of communities, keeping track of the number for the community
for name in c: # Loop through each person in a community
modularity_dict[name] = i # Create an entry in the dictionary for the person, where the value is which group they belong to.
# Now you can add modularity information like we did the other metrics
nx.set_node_attributes(G, modularity_dict, 'modularity')
# First get a list of just the nodes in that class
class0 = [n for n in G.nodes() if G.nodes[n]['modularity'] == 0]
# Then create a dictionary of the eigenvector centralities of those nodes
class0_eigenvector = {n:G.nodes[n]['eigenvector'] for n in class0}
# Then sort that dictionary and print the first 5 results
class0_sorted_by_eigenvector = sorted(class0_eigenvector.items(), key=itemgetter(1), reverse=True)
print("Modularity Class 0 Sorted by Eigenvector Centrality:")
for node in class0_sorted_by_eigenvector[:5]:
print("Name:", node[0], "| Eigenvector Centrality:", node[1])
for i,c in enumerate(communities): # Loop through the list of communities
if len(c) > 1: # Filter out modularity classes with 2 or fewer nodes
print('Class '+str(i)+':', list(c)) # Print out the classes and their members
nx.write_gexf(G, 'shicai_network.gexf')