jasonfan's picture
2026-03-19: ICL code
64bce2a verified
import torch
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
def adjacency_to_incidence(A, n_nodes, max_edges):
"""
Converts an adjacency matrix A to an incidence matrix B.
Pads the incidence matrix to have max_edges columns.
Args:
A (torch.Tensor): Adjacency matrix
n_nodes (int): Number of nodes
max_edges (int): Maximum number of edges to include
Returns:
B (torch.Tensor): Incidence matrix
n_edges (int): Actual number of edges
"""
edges = []
for i in range(n_nodes):
for j in range(i+1, n_nodes):
if A[i, j] != 0:
edges.append((i, j))
n_edges = len(edges)
B = torch.zeros(n_nodes, max_edges)
for idx, (i, j) in enumerate(edges):
if idx < max_edges:
B[i, idx] = 1
B[j, idx] = -1
return B, n_edges
def get_laplacian(B):
"""
Compute Laplacian matrix from incidence matrix B.
Args:
B (torch.Tensor): Incidence matrix [batch_size, n_nodes, n_edges]
Returns:
L (torch.Tensor): Laplacian matrix [batch_size, n_nodes, n_nodes]
"""
return torch.einsum('ijk,ilk->ijl', B, B)
def compute_normalized_laplacian(adj):
"""
Compute normalized Laplacian from adjacency matrix.
Args:
adj (torch.Tensor): Adjacency matrix [n_nodes, n_nodes]
Returns:
L (torch.Tensor): Normalized Laplacian matrix [n_nodes, n_nodes]
"""
# Get degree matrix
deg = adj.sum(dim=-1)
# Avoid division by zero
deg = torch.clamp(deg, min=1e-10)
# Compute D^(-1/2)
D_inv_sqrt = torch.diag(deg.pow(-0.5))
# Compute normalized Laplacian: L = I - D^(-1/2) A D^(-1/2)
I = torch.eye(adj.size(0), device=adj.device)
L = I - D_inv_sqrt @ adj @ D_inv_sqrt
return L
def compute_unnormalized_laplacian(adj):
"""
Compute unnormalized Laplacian from adjacency matrix.
Args:
adj (torch.Tensor): Adjacency matrix [n_nodes, n_nodes]
Returns:
L (torch.Tensor): Unnormalized Laplacian matrix [n_nodes, n_nodes]
"""
# Get degree matrix
deg = adj.sum(dim=-1)
D = torch.diag(deg)
# Compute L = D - A
L = D - adj
return L
def visualize_graph(adj, pos=None, node_color=None, title="Graph Visualization"):
"""
Visualize a graph from its adjacency matrix.
Args:
adj (np.ndarray or torch.Tensor): Adjacency matrix
pos (dict, optional): Node positions for visualization
node_color (list, optional): Node colors
title (str): Title for the plot
"""
# Convert to numpy if tensor
if isinstance(adj, torch.Tensor):
adj = adj.cpu().numpy()
# Create networkx graph
G = nx.from_numpy_array(adj)
# Set up figure
plt.figure(figsize=(10, 8))
# Compute positions if not provided
if pos is None:
pos = nx.spring_layout(G)
# Set default node colors if not provided
if node_color is None:
node_color = 'skyblue'
# Draw the graph
nx.draw(G, pos=pos, with_labels=True, node_color=node_color,
node_size=300, font_size=10, font_weight='bold',
edge_color='gray', width=[G[u][v]['weight']*5 for u,v in G.edges()])
plt.title(title)
plt.tight_layout()
plt.show()
def visualize_laplacian_eigenvectors(L, k=4, title="Laplacian Eigenvectors"):
"""
Compute and visualize the first k eigenvectors of a Laplacian matrix.
Args:
L (torch.Tensor): Laplacian matrix
k (int): Number of eigenvectors to visualize
title (str): Title for the plot
"""
# Convert to numpy if tensor
if isinstance(L, torch.Tensor):
L = L.cpu().numpy()
# Compute eigendecomposition
eigenvals, eigenvecs = np.linalg.eigh(L)
# Sort by eigenvalues
idx = eigenvals.argsort()
eigenvals = eigenvals[idx]
eigenvecs = eigenvecs[:, idx]
# Plot the first k eigenvectors
n_rows = (k + 1) // 2
n_cols = 2
plt.figure(figsize=(12, 3 * n_rows))
for i in range(min(k, eigenvecs.shape[1])):
plt.subplot(n_rows, n_cols, i+1)
plt.plot(eigenvecs[:, i], 'o-')
plt.grid(True)
plt.title(f"Eigenvector {i+1}, λ = {eigenvals[i]:.6f}")
plt.suptitle(title)
plt.tight_layout(rect=[0, 0, 1, 0.95]) # Adjust for the super title
plt.show()
def compare_eigenvectors(eigenvecs1, eigenvecs2, k=4, labels=None, title="Eigenvector Comparison"):
"""
Compare two sets of eigenvectors side by side.
Args:
eigenvecs1 (numpy.ndarray): First set of eigenvectors [n_nodes, n_evecs]
eigenvecs2 (numpy.ndarray): Second set of eigenvectors [n_nodes, n_evecs]
k (int): Number of eigenvectors to compare
labels (list): Optional labels for the legend
title (str): Title for the plot
"""
# Convert to numpy if tensor
if isinstance(eigenvecs1, torch.Tensor):
eigenvecs1 = eigenvecs1.cpu().numpy()
if isinstance(eigenvecs2, torch.Tensor):
eigenvecs2 = eigenvecs2.cpu().numpy()
# Normalize eigenvectors
eigenvecs1_norm = eigenvecs1 / np.linalg.norm(eigenvecs1, axis=0, keepdims=True)
eigenvecs2_norm = eigenvecs2 / np.linalg.norm(eigenvecs2, axis=0, keepdims=True)
# Set default labels
if labels is None:
labels = ["Eigenvector Set 1", "Eigenvector Set 2"]
# Plot comparisons
n_rows = (k + 1) // 2
n_cols = 2
plt.figure(figsize=(14, 3 * n_rows))
for i in range(min(k, eigenvecs1.shape[1], eigenvecs2.shape[1])):
plt.subplot(n_rows, n_cols, i+1)
# Handle sign ambiguity: flip eigenvector if it better matches the flipped version
flipped = np.linalg.norm(eigenvecs1_norm[:, i] + eigenvecs2_norm[:, i]) < np.linalg.norm(eigenvecs1_norm[:, i] - eigenvecs2_norm[:, i])
ev2_to_use = -eigenvecs2_norm[:, i] if flipped else eigenvecs2_norm[:, i]
plt.plot(eigenvecs1_norm[:, i], 'o-', label=labels[0])
plt.plot(ev2_to_use, 's-', label=labels[1])
plt.grid(True)
plt.title(f"Eigenvector {i+1}")
plt.legend()
plt.suptitle(title)
plt.tight_layout(rect=[0, 0, 1, 0.95]) # Adjust for the super title
plt.show()