| 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] |
| """ |
| |
| deg = adj.sum(dim=-1) |
| |
| |
| deg = torch.clamp(deg, min=1e-10) |
| |
| |
| D_inv_sqrt = torch.diag(deg.pow(-0.5)) |
| |
| |
| 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] |
| """ |
| |
| deg = adj.sum(dim=-1) |
| D = torch.diag(deg) |
| |
| |
| 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 |
| """ |
| |
| if isinstance(adj, torch.Tensor): |
| adj = adj.cpu().numpy() |
| |
| |
| G = nx.from_numpy_array(adj) |
| |
| |
| plt.figure(figsize=(10, 8)) |
| |
| |
| if pos is None: |
| pos = nx.spring_layout(G) |
| |
| |
| if node_color is None: |
| node_color = 'skyblue' |
| |
| |
| 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 |
| """ |
| |
| if isinstance(L, torch.Tensor): |
| L = L.cpu().numpy() |
| |
| |
| eigenvals, eigenvecs = np.linalg.eigh(L) |
| |
| |
| idx = eigenvals.argsort() |
| eigenvals = eigenvals[idx] |
| eigenvecs = eigenvecs[:, idx] |
| |
| |
| 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]) |
| 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 |
| """ |
| |
| if isinstance(eigenvecs1, torch.Tensor): |
| eigenvecs1 = eigenvecs1.cpu().numpy() |
| if isinstance(eigenvecs2, torch.Tensor): |
| eigenvecs2 = eigenvecs2.cpu().numpy() |
| |
| |
| eigenvecs1_norm = eigenvecs1 / np.linalg.norm(eigenvecs1, axis=0, keepdims=True) |
| eigenvecs2_norm = eigenvecs2 / np.linalg.norm(eigenvecs2, axis=0, keepdims=True) |
| |
| |
| if labels is None: |
| labels = ["Eigenvector Set 1", "Eigenvector Set 2"] |
| |
| |
| 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) |
| |
| |
| 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]) |
| plt.show() |