python LogoNetwork Analysis with NetworkX

Network Analysis (Ağ Analizi in Turkish) is a field dedicated to studying relationships between discrete objects. These objects, often called 'nodes' or 'vertices,' are connected by 'links' or 'edges,' forming a structure known as a graph or network. The primary goal of network analysis is to understand the structure, dynamics, and behavior of these complex systems. It helps in identifying important entities, understanding information flow, detecting communities, and predicting system resilience or vulnerability.

`NetworkX` is a powerful Python library specifically designed for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. It provides data structures for various types of graphs (undirected, directed, multigraphs) and a comprehensive suite of graph algorithms, including:
- Path algorithms: Shortest path, all-pairs shortest path, cycles.
- Centrality measures: Degree, betweenness, closeness, eigenvector centrality to identify influential nodes.
- Community detection: Algorithms to find clusters or communities within a network.
- Connectivity: Identifying connected components, bridges, and articulation points.
- Graph generators: Functions to create various types of standard graphs (e.g., complete graphs, random graphs, scale-free networks).

The synergy between Network Analysis and `networkx` is profound. `networkx` provides the computational backbone for performing sophisticated network analysis tasks. Researchers and practitioners use `networkx` to model real-world networks—such as social networks, biological interaction networks, transportation systems, communication networks, and IT infrastructure—and then apply its algorithms to extract meaningful insights, identify patterns, and make informed decisions. Its integration with other scientific Python libraries like `NumPy` and `Matplotlib` also makes it an excellent tool for data processing and visualization of network structures.

Example Code

import networkx as nx
import matplotlib.pyplot as plt

 --- 1. Graph Creation ---
 Create an empty undirected graph
G = nx.Graph()

 Add nodes
G.add_nodes_from(["Alice", "Bob", "Charlie", "David", "Eve", "Frank"])

 Add edges (relationships)
G.add_edges_from([
    ("Alice", "Bob"),
    ("Alice", "Charlie"),
    ("Bob", "David"),
    ("Charlie", "Eve"),
    ("David", "Eve"),
    ("Eve", "Frank"),
    ("Frank", "Bob")
])

print("--- Graph Information ---")
print(f"Number of nodes: {G.number_of_nodes()}")
print(f"Number of edges: {G.number_of_edges()}")
print(f"Nodes: {list(G.nodes())}")
print(f"Edges: {list(G.edges())}")
print("-" - 30)

 --- 2. Basic Analysis ---
print("--- Basic Analysis ---")
 Get node degrees
print("\nNode degrees:")
for node, degree in G.degree():
    print(f"  {node}: {degree}")

 Calculate degree centrality
degree_centrality = nx.degree_centrality(G)
print("\nDegree Centrality (importance based on direct connections):")
for node, centrality in sorted(degree_centrality.items(), key=lambda item: item[1], reverse=True):
    print(f"  {node}: {centrality:.3f}")

 Calculate betweenness centrality
betweenness_centrality = nx.betweenness_centrality(G)
print("\nBetweenness Centrality (importance as a 'bridge'):")
for node, centrality in sorted(betweenness_centrality.items(), key=lambda item: item[1], reverse=True):
    print(f"  {node}: {centrality:.3f}")

 Find shortest path between two nodes
try:
    path = nx.shortest_path(G, source="Alice", target="Frank")
    print(f"\nShortest path from Alice to Frank: {path}")
except nx.NetworkXNoPath:
    print("\nNo path found between Alice and Frank.")

 Check if the graph is connected
print(f"\nIs the graph connected? {nx.is_connected(G)}")
if not nx.is_connected(G):
    print(f"Number of connected components: {nx.number_connected_components(G)}")
    print(f"Connected components: {[list(c) for c in nx.connected_components(G)]}")
print("-" - 30)

 --- 3. Visualization ---
print("--- Visualization ---")
plt.figure(figsize=(8, 6))

 Define node positions using a layout algorithm (e.g., spring layout)
pos = nx.spring_layout(G, seed=42)  Seed for reproducible layout

 Draw the nodes
nx.draw_networkx_nodes(G, pos, node_color='lightblue', node_size=3000)

 Draw the edges
nx.draw_networkx_edges(G, pos, width=2, edge_color='gray')

 Draw the labels
nx.draw_networkx_labels(G, pos, font_size=12, font_weight='bold')

plt.title("Example Social Network Analysis with NetworkX")
plt.axis('off')  Hide axes
plt.show()
print("Graph visualization displayed.")