SAN Code
Importing Libraries
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms.community import girvan_newman
Creating a DataFrame
data = pd.DataFrame([
{'source': 'Alice', 'target': 'Bob'},
{'source': 'Alice', 'target': 'Charlie'},
{'source': 'Bob', 'target': 'Charlie'},
{'source': 'Bob', 'target': 'Dave'},
{'source': 'Charlie', 'target': 'Dave'},
{'source': 'Dave', 'target': 'Eve'},
{'source': 'Eve', 'target': 'Frank'},
{'source': 'Frank', 'target': 'Gina'},
{'source': 'Gina', 'target': 'Henry'},
{'source': 'Henry', 'target': 'Alice'},
{'source': 'Alice', 'target': 'Frank'},
{'source': 'Charlie', 'target': 'Gina'}
])
Creating and Drawing the Graph
G = nx.from_pandas_edgelist(data, 'source', 'target')
plt.figure(figsize=(10, 8))
nx.draw(G, with_labels=True, node_color='skyblue', node_size=2000, edge_color='gray')
plt.title("Social Network")
plt.show()
Calculating Degree Centrality
degree_centrality = nx.degree_centrality(G)
print("Degree Centrality:")
for node, centrality in degree_centrality.items():
print(f"{node}: {centrality:.2f}")
Visualizing Degree Centrality
plt.figure(figsize=(10, 8))
pos = nx.spring_layout(G)
nodes = nx.draw_networkx_nodes(G, pos, node_color='skyblue', node_size=[v * 5000 for v in degree_centrality.values()])
edges = nx.draw_networkx_edges(G, pos, edge_color='gray')
labels = nx.draw_networkx_labels(G, pos)
plt.title("Degree Centrality")
plt.show()
Calculating Betweenness Centrality
betweenness_centrality = nx.betweenness_centrality(G)
print("Betweenness Centrality:")
for node, centrality in betweenness_centrality.items():
print(f"{node}: {centrality:.2f}")
Visualizing Betweenness Centrality
plt.figure(figsize=(10, 8))
nodes = nx.draw_networkx_nodes(G, pos, node_color='lightgreen', node_size=[v * 5000 for v in betweenness_centrality.values()])
edges = nx.draw_networkx_edges(G, pos, edge_color='gray')
labels = nx.draw_networkx_labels(G, pos)
plt.title("Betweenness Centrality")
plt.show()
Detecting Communities
communities = next(girvan_newman(G))
print("Communities:")
for i, community in enumerate(communities):
print(f"Community {i + 1}: {community}")
Visualizing Communities
plt.figure(figsize=(10, 8))
colors = ['skyblue', 'lightgreen', 'lightcoral']
for i, community in enumerate(communities):
nx.draw_networkx_nodes(G, pos, nodelist=community, node_color=colors[i], node_size=2000)
nx.draw_networkx_edges(G, pos, edge_color='gray')
nx.draw_networkx_labels(G, pos)
plt.title("Communities")
plt.show()
Calculating Clustering Coefficient
clustering_coefficient = nx.clustering(G)
print("Clustering Coefficient:")
for node, coeff in clustering_coefficient.items():
print(f"{node}: {coeff:.2f}")
Visualizing Clustering Coefficient
plt.figure(figsize=(10, 8))
nodes = nx.draw_networkx_nodes(G, pos, node_color='lightblue', node_size=[v * 5000 for v in clustering_coefficient.values()])
edges = nx.draw_networkx_edges(G, pos, edge_color='gray')
labels = nx.draw_networkx_labels(G, pos)
plt.title("Clustering Coefficient")
plt.show()
Shortest Path Lengths
shortest_path_length = dict(nx.all_pairs_shortest_path_length(G))
print("Shortest Path Lengths:")
for source, paths in shortest_path_length.items():
for target, length in paths.items():
print(f"Shortest path from {source} to {target}: {length}")
Visualizing Shortest Path
shortest_path = nx.shortest_path(G, source='Alice', target='Gina')
print(f"Shortest path from Alice to Gina: {shortest_path}")
plt.figure(figsize=(10, 8))
path_edges = list(zip(shortest_path, shortest_path[1:]))
nx.draw(G, pos, with_labels=True, node_color='skyblue', node_size=2000, edge_color='gray')
nx.draw_networkx_edges(G, pos, edgelist=path_edges, edge_color='red', width=2)
plt.title("Shortest Path from Alice to Gina")
plt.show()
Directed Graph and Centrality Measures
G = nx.from_pandas_edgelist(data, source='source', target='target', create_using=nx.DiGraph())
degree_centrality = nx.degree_centrality(G)
betweenness_centrality = nx.betweenness_centrality(G)
closeness_centrality = nx.closeness_centrality(G)
print("Degree Centrality:", degree_centrality)
print("Betweenness Centrality:", betweenness_centrality)
print("Closeness Centrality:", closeness_centrality)
Visualizing Directed Graph with Degree Centrality
plt.figure(figsize=(10, 8))
pos = nx.spring_layout(G)
node_size = [v * 3000 for v in degree_centrality.values()]
node_color = [v for v in degree_centrality.values()]
nx.draw_networkx_nodes(G, pos, node_size=node_size, node_color=node_color, cmap=plt.cm.viridis, alpha=0.8)
nx.draw_networkx_edges(G, pos, arrowstyle='-|>', arrowsize=10, edge_color='gray')
nx.draw_networkx_labels(G, pos, font_size=12, font_color='black')
sm = plt.cm.ScalarMappable(cmap=plt.cm.viridis, norm=plt.Normalize(vmin=min(degree_centrality.values()), vmax=max(degree_centrality.values())))
sm.set_array([])
cbar = plt.colorbar(sm, ax=plt.gca(), label='Degree Centrality')
plt.title('Network Graph with Degree Centrality')
plt.show()
Slide 17: Circle of Influence for a Specific Node
specific_node = 'Charlie'
if specific_node in pos:
x, y = pos[specific_node]
radius = degree_centrality[specific_node]
circle = plt.Circle((x, y), radius, color='red', fill=False, linestyle='dashed', alpha=0.4)
plt.gca().add_patch(circle)
plt.title('Network Graph with Degree Centrality and Circle of Influence for Charlie')
plt.show()