import torch import numpy as np import os import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def get_or_generate_data_sphere(epoch, batch_size, n_samples, scale_rbf, k_nn, device, label_percent, context_size, k_feat, data_dir="./cached_data", force=False): """ Check for cached sphere data, or generate new data if it doesn't exist. Args: epoch: Current training epoch batch_size: Batch size n_samples: Number of points per sample scale_rbf: RBF kernel scaling parameter k_nn: K nearest neighbors parameter device: Computation device label_percent: Percentage of labeled points context_size: Size of context for in-context learning k_feat: Number of eigenvector features to use data_dir: Directory for data caching force: Whether to force regeneration of data Returns: Tuple of all data tensors and indices: (raw_data, real_lap, labels_tensor, real_adj, labeled_indices, context_indices, query_indices, real_ev) """ # Create cache directory if it doesn't exist os.makedirs(data_dir, exist_ok=True) # Build file path file_path = os.path.join(data_dir, f"sphere_data_epoch_{epoch}.pt") # import pdb # pdb.set_trace() try: if (not force) and os.path.exists(file_path): print(f"Loading cached sphere data for epoch {epoch}...") cached_data = torch.load(file_path) return ( cached_data['raw_data'], cached_data['real_lap'], cached_data['labels_tensor'], cached_data['real_adj'], cached_data['labeled_indices'], cached_data['context_indices'], cached_data['query_indices'], cached_data['real_ev'] ) print(f"Generating new sphere data for epoch {epoch}...") except: print(f"Re Generating new cone data for epoch {epoch}...") # Generate new data raw_data_batch = [] real_lap_batch = [] labels_batch = [] adjacency_batch = [] for b in range(batch_size): L_true, xyz, labels_np, adjacency = generate_small_sphere_in_3d( n_samples=n_samples, scale_rbf=scale_rbf, k_nn=k_nn, seed=epoch*batch_size+b, device=device ) raw_data_batch.append(torch.from_numpy(xyz).float()) real_lap_batch.append(L_true) labels_batch.append(torch.from_numpy(labels_np)) adjacency_batch.append(torch.from_numpy(adjacency).float()) raw_data = torch.stack(raw_data_batch, dim=0).to(device) real_lap = torch.stack(real_lap_batch, dim=0).to(device) labels_tensor = torch.stack(labels_batch, dim=0).to(device) real_adj = torch.stack(adjacency_batch, dim=0).to(device) # Build labeled and unlabeled sets n_labeled = int(n_samples * label_percent / 100) labeled_indices = torch.stack([torch.randperm(n_samples)[:n_labeled] for _ in range(batch_size)], dim=0).to(device) context_indices = torch.stack([torch.randperm(n_labeled)[:context_size] for _ in range(batch_size)], dim=0).to(device) all_indices = torch.arange(n_labeled).expand(batch_size, n_labeled).to(device) mask = torch.zeros(batch_size, n_labeled, dtype=torch.bool).to(device) # labels_tensor = labels_tensor.gather(-1, labeled_indices) # import pdb # pdb.set_trace() for i in range(batch_size): mask[i].scatter_(0, context_indices[i], True) query_indices = all_indices[~mask].view(batch_size, n_labeled - context_size).to(device) # Compute real eigenvectors real_eigs = [] for b in range(batch_size): _, vecs = torch.linalg.eigh(real_lap[b]) real_eigs.append(vecs[:, :k_feat]) real_ev = torch.stack(real_eigs, dim=0) # Save all data to disk cached_data = { 'raw_data': raw_data, 'real_lap': real_lap, 'labels_tensor': labels_tensor, 'real_adj': real_adj, 'labeled_indices': labeled_indices, 'context_indices': context_indices, 'query_indices': query_indices, 'real_ev': real_ev } torch.save(cached_data, file_path) print(f"Saved sphere data to {file_path}") return raw_data, real_lap, labels_tensor, real_adj, labeled_indices, context_indices, query_indices, real_ev def generate_in_context_sphere_graphs(Z, batch_size, n_samples, k_values, max_edges, noise=0.0, base_seed=0, k_feat=4, label_percent=100, context_size=0, model=None, use_exact_ev=False): """ Generate in-context learning data for sphere dataset. Similar to the Swiss roll version but using sphere data. This function stores: - Normalized Laplacian in Z[:, :, :n] - Adjacency in Z[:, :, n:2n] - Eigenvectors in Z[:, :, 2n:] Args: Z: Zero tensor to populate with data batch_size: Number of graphs to generate n_samples: Number of nodes per graph k_values: K nearest neighbors for graph construction max_edges: Maximum edges to consider noise: Amount of noise to add base_seed: Base random seed k_feat: Number of eigenvector features label_percent: Percentage of labeled nodes context_size: Size of context for in-context learning model: Optional model to predict eigenvectors use_exact_ev: Whether to use exact eigenvectors Returns: embedding, labeled_data, labeled_indices, context_indices, query_indices """ assert label_percent > 0 and label_percent <= 100 n_labeled = int(n_samples * label_percent / 100) assert context_size < n_labeled if isinstance(k_values, int): k_values = [k_values] if use_exact_ev: embedding = torch.zeros([batch_size, n_samples, k_feat], device=device) for i in range(batch_size): # Use the iteration number or base_seed + i as the seed seed = base_seed + i # Ensures different seeds for each graph adj, L_test, eigenvals, eigenvecs = generate_weighted_sphere_graph( n_samples=n_samples, scale=10, k=k_values[0] if isinstance(k_values, list) else k_values, seed=seed, return_extra=False, device=device ) # Use the normalized Laplacian directly lap = L_test.to(device) # Select and normalize eigenvectors eigenvecs_selected = eigenvecs[:, :k_feat] eigenvecs_selected /= (np.linalg.norm(eigenvecs_selected, axis=1, keepdims=True) + 1e-10) eigenvecs_selected = torch.from_numpy(eigenvecs_selected).float().to(device) # Fill Z Z[i, :, :n_samples] = lap # [n, n], normalized Laplacian Z[i, :, n_samples:2*n_samples] = adj.to(device) # [n, n], adjacency matrix Z[i, :, 2*n_samples:] = eigenvecs_selected # [n, k_feat], eigenvectors if use_exact_ev: actual_embedding = eigenvecs[:, :k_feat] # [n_samples, k_feat] embedding[i, :, :] = torch.from_numpy(actual_embedding / (np.linalg.norm(actual_embedding, axis=1, keepdims=True) + 1e-10)).float().to(device) if not use_exact_ev: # Make predictions with PE transformer model.eval() with torch.no_grad(): output = model(Z) # Shape: [batch_size, n_samples, n + (n+k)] # Extract predicted eigenvectors predicted_ev = output[:, :, -k_feat:].cpu().numpy() # [batch_size, n_samples, k_feat] # Predicted embedding embedding = predicted_ev / (np.linalg.norm(predicted_ev, axis=1, keepdims=True) + 1e-10) embedding = torch.from_numpy(embedding).float().to(device) # Assign labels based on geodesic distance for sphere dataset # For sphere we need to generate labels differently than Swiss roll # Generate one sample of sphere data to get point positions t, data = gen_random_data(batch_size, n_samples, type='sphere') data = data.to(device) # Generate labels based on geodesic distance labels = torch.zeros(batch_size, n_samples, device=device) for b in range(batch_size): # Choose a random point as center center_idx = torch.randint(0, n_samples, (1,)).item() center_point = data[b, center_idx] # Calculate dot products and geodesic distances dots = torch.clamp(torch.sum(data[b] * center_point, dim=1), -1.0, 1.0) geodesic_dist = torch.acos(dots) # Create binary labels: points closer than π/3 are class 1, others are class 0 labels[b] = (geodesic_dist < (torch.pi / 3)).long() # Get labeled indices labeled_indices = torch.stack([torch.randperm(n_samples)[:n_labeled] for _ in range(batch_size)]).to(device) labeled_data = labels.gather(1, labeled_indices) # Get context indices context_indices = torch.stack([torch.randperm(n_labeled)[:context_size] for _ in range(batch_size)]).to(device) all_indices = torch.arange(n_labeled).expand(batch_size, n_labeled).to(device) # Shape [B, n_labeled] # Create a mask for indices present in the input tensor mask = torch.zeros(batch_size, n_labeled, dtype=torch.bool).to(device) mask.scatter_(1, context_indices, True) # Invert the mask to get query indices query_indices = all_indices[~mask].view(batch_size, n_labeled - context_size).to(device) # Shape [B, n_labeled - context_size] return embedding, labeled_data, labeled_indices, context_indices, query_indices def gen_random_data(n_batch, n_samples, type='swissroll'): """ Generate random data of different types, including circles, swiss roll, line, and now sphere. Args: n_batch (int): Number of batches to generate n_samples (int): Number of samples per batch type (str): Type of data to generate ('circles', 'swissroll', 'line', or 'sphere') Returns: t (torch.Tensor): Parameter values used to generate the data. For 'swissroll', this is the 1D parameter. For 'sphere', this returns the polar angle theta. data (torch.Tensor): Generated data points. """ if type=='circles': n0 = int(n_samples/5) r0 = 0.1 r1 = 0.6 t0 = torch.rand(size=(n_batch, 2*n0)) t1 = torch.rand(size=(n_batch, n0)) t2 = torch.rand(size=(n_batch, 2*n0)) t0, _ = torch.sort(t0) t1, _ = torch.sort(t1) t2, _ = torch.sort(t2) t = torch.cat((t0, t1+1, t2+2), dim=1) x0 = r0*torch.cos(t0*2*torch.pi) y0 = r0*torch.sin(t0*2*torch.pi) x1 = torch.zeros_like(t1) y1 = r0 + t1 * (r1-r0) x2 = r1 * torch.cos(t2*2*torch.pi) y2 = r1 * torch.sin(t2*2*torch.pi) xs = torch.cat((x0, x1, x2), dim=1) ys = torch.cat((y0, y1, y2), dim=1) data = torch.cat((xs[:,:,None], ys[:,:,None]), dim=2) elif type=='swissroll': n0 = int(n_samples) t0 = torch.rand(size=(n_batch, n0)) t0, _ = torch.sort(t0) t = t0 x0 = t0**2*torch.cos(t0*4*torch.pi) y0 = t0**2*torch.sin(t0*4*torch.pi) data = torch.cat((x0[:,:,None], y0[:,:,None]), dim=2) elif type=='line': n0 = int(n_samples) t0 = torch.rand(size=(n_batch, n0)) t0, _ = torch.sort(t0) t = t0 x0 = torch.zeros_like(t0) y0 = t0 data = torch.cat((x0[:,:,None], y0[:,:,None]), dim=2) elif type=='sphere': # Sample uniformly on the unit sphere using spherical coordinates. # u, v ~ Uniform(0,1) u = torch.rand(n_batch, n_samples) v = torch.rand(n_batch, n_samples) # theta in [0, pi] via inverse transform of cos(theta) theta = torch.acos(2*u - 1) # phi in [0, 2pi] phi = 2 * torch.pi * v x = torch.sin(theta) * torch.cos(phi) y = torch.sin(theta) * torch.sin(phi) z = torch.cos(theta) # t will be theta (analogous to the 1D parameter for the swiss roll) t = theta data = torch.cat([x.unsqueeze(2), y.unsqueeze(2), z.unsqueeze(2)], dim=2) else: raise ValueError(f"Unknown data type: {type}") return t, data def random_data_to_adjacency(data, scale=4): """ Convert data points to an adjacency matrix using RBF kernel. Args: data (torch.Tensor): Data points of shape [B, n_sample, dim] scale (float): Scale parameter for RBF kernel Returns: torch.Tensor: Adjacency matrix with RBF weights """ B, n, d = data.shape # distance(vi, vj) = ||vi - vj||^2 = ||vi||^2 + ||vj||^2 - 2 norms = torch.norm(data, p=2, dim=2)**2 euclidean_distances = norms[:,:,None] + norms[:,None,:] - 2 * torch.einsum('Bni,Bmi->Bnm', (data, data)) inv_rbf_distances = torch.exp(-scale * euclidean_distances) return inv_rbf_distances def smallest_k_indices(inv_distance_matrix, k): """ Find the indices of the k largest values in each row of the inverse distance matrix. This corresponds to the k nearest neighbors in the original space. Args: inv_distance_matrix (torch.Tensor): Inverse distance matrix k (int): Number of nearest neighbors to find Returns: torch.Tensor: Indices of k-nearest neighbors for each node """ # Mask the diagonal to exclude self-loops n = inv_distance_matrix.size(0) inv_distance_matrix = inv_distance_matrix.clone() # Avoid modifying the original inv_distance_matrix.fill_diagonal_(float(-1)) # Set diagonal to a negative value # Find the indices of the k largest values in each row indices = torch.topk(inv_distance_matrix, k, dim=-1).indices return indices def generate_small_sphere_in_3d(n_samples=100, scale_rbf=10, k_nn=6, seed=0, device=None): """ Generate a 3D sphere with a normalized Laplacian. This function samples n_samples points uniformly from a sphere, computes the RBF adjacency based on Euclidean distances, builds a k-NN graph, and then computes the normalized Laplacian. Labels are assigned based on the geodesic (great-circle) distance on the sphere. A random point is chosen, and all points with geodesic distance (arccos(dot)) less than a threshold (here 0.5 radians) are labeled as one class. Args: n_samples (int): Number of samples to generate scale_rbf (float): Scale parameter for RBF kernel k_nn (int): Number of nearest neighbors for graph construction seed (int): Random seed for reproducibility device (torch.device): Device to create tensors on Returns: L (torch.Tensor): Normalized Laplacian matrix xyz (numpy.ndarray): 3D coordinates of the points labels (numpy.ndarray): Binary labels for the points (0 or 1) adjacency (torch.Tensor): Optional adjacency matrix """ if device is None: device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Set random seeds for reproducibility torch.manual_seed(seed) np.random.seed(seed) # Generate 3D sphere data using the new type. n_batch = 1 t, data3d = gen_random_data(n_batch, n_samples, type='sphere') data3d = data3d.to(device) # shape [1, n_samples, 3] # Compute RBF adjacency using Euclidean distances in 3D. dist_sq = torch.cdist(data3d[0], data3d[0], p=2)**2 A_rbf = torch.exp(-scale_rbf*dist_sq).to(device) # Build k-NN graph idx_topk = smallest_k_indices(A_rbf, k_nn) # shape [n_samples, k_nn] adjacency = torch.zeros((n_samples, n_samples), device=device) for i in range(n_samples): for j in idx_topk[i]: adjacency[i, j] = A_rbf[i, j] adjacency[j, i] = A_rbf[j, i] # Ensure symmetry # Compute normalized Laplacian: L = I - D^(-1/2) A D^(-1/2) deg = adjacency.sum(dim=1) deg[deg < 1e-10] = 1e-10 # Avoid division by zero D_inv_sqrt = torch.diag(deg.pow(-0.5)) L = torch.eye(n_samples, device=device) - D_inv_sqrt @ adjacency @ D_inv_sqrt # Create labels based on geodesic distance on the sphere. # Randomly choose one point from the dataset as the center. chosen_idx = np.random.randint(0, n_samples) chosen_point = data3d[0, chosen_idx] # shape [3] # Compute dot products between chosen_point and all points (they lie on the unit sphere) dots = torch.clamp(torch.matmul(data3d[0], chosen_point), -1.0, 1.0) # Geodesic distance on a sphere: arccos(dot) geodesic_distances = torch.acos(dots) # Use threshold = 0.5 (radians); points with geodesic distance less than 0.5 are class 1, else 0. labels = (geodesic_distances < 0.5).long().cpu().numpy() xyz = data3d[0].cpu().numpy() # shape [n_samples, 3] return L, xyz, labels, adjacency.cpu().numpy() def generate_weighted_sphere_graph(n_samples=100, scale=10, k=6, seed=5, return_extra=False, model=None, use_predicted_laplacian=False, k_feat=4, device=None): """ Generate a sphere dataset with a weighted graph and compute its Laplacian. Optionally use a model to predict the Laplacian instead of computing it directly. This function uses the sphere manifold (via gen_random_data with type 'sphere') and then applies a series of random transformations. Note that unlike the swiss roll version, here we: - Do not add an extra fixed z-dimension (since the data is already 3D) - Apply a uniform scaling to all dimensions (to preserve the spherical shape) - Use the same random rotation and translation (on x and y) as in the original code. Labels are assigned based on the geodesic distance on the sphere. Args: n_samples (int): Number of samples in the sphere scale (float): Scale parameter for the RBF kernel k (int): Number of nearest neighbors for graph construction seed (int): Random seed for reproducibility return_extra (bool): Whether to return additional data for visualization model: Optional model to predict the Laplacian use_predicted_laplacian (bool): Whether to use the model to predict Laplacian k_feat (int): Number of eigenvector features to select device: Device to create tensors on Returns: Multiple tensors depending on return_extra: - Always: adjacency, normalized Laplacian, eigenvalues, eigenvectors - If return_extra=True: Also t, a_translated (raw data) """ if device is None: device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Set seeds for reproducibility torch.manual_seed(seed) np.random.seed(seed) # Generate sphere data t, a = gen_random_data(1, n_samples, type='sphere') a = a.to(device) # shape [1, n_samples, 3] # Apply random scaling uniformly to all dimensions to mimic randomness in the swiss roll. scale_factor = np.random.uniform(0.02, 0.1) a_translated = a * scale_factor # Apply random rotation (using the same rotation around the z-axis as before) theta = np.random.uniform(0, 2 * np.pi) rotation_matrix = torch.tensor([ [np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1] ], dtype=torch.float32, device=device) a_rotated = torch.matmul(a_translated, rotation_matrix) # Apply random translation (only on x and y; leave z unchanged) translation_x = np.random.uniform(-1, 1) translation_y = np.random.uniform(-1, 1) translation = torch.tensor([[[translation_x, translation_y, 0]]], dtype=torch.float32, device=device) a_translated = a_rotated + translation # Compute RBF similarities. # For the sphere version, we use all three coordinates. inv_distances = random_data_to_adjacency(a_translated, scale=scale) # Construct k-NN adjacency matrix. knn_indices = smallest_k_indices(inv_distances[0, :, :], k) adj = torch.zeros((n_samples, n_samples), dtype=torch.float32, device=device) for i in range(knn_indices.shape[0]): for j in knn_indices[i, :]: if j < n_samples: weight = inv_distances[0, i, j].item() adj[i, j] = weight adj[j, i] = weight # Ensure symmetry # Either compute or predict the Laplacian. if use_predicted_laplacian and model is not None: # Prepare input for the model Z_input_for_model = torch.zeros(1, n_samples, 2 * n_samples + k_feat, device=device) for row_idx in range(n_samples): Z_input_for_model[0, row_idx, 0:3] = a_translated[0, row_idx, :] # Store (x, y, z) # Predict Laplacian rows using the model. model.eval() with torch.no_grad(): predicted_output = model(Z_input_for_model) predicted_laplacian_rows = predicted_output[:, :, n_samples:2*n_samples] # [1, n, n] L_test = predicted_laplacian_rows[0].to(device) # [n, n] else: # Compute normalized Laplacian directly. degree = torch.sum(adj, dim=1) degree[degree == 0] = 1.0 # Avoid division by zero D_inv_sqrt = torch.diag(degree.pow(-0.5)) L_test = torch.eye(adj.size(0), device=device) - D_inv_sqrt @ adj @ D_inv_sqrt # Compute eigenvalues and eigenvectors. target_eigenvals, target_ev_torch = torch.linalg.eigh(L_test) target_ev = target_ev_torch.cpu().numpy() if return_extra: # Additional plotting and visualization data. data = a_translated[0].cpu().numpy() # Assign labels based on geodesic distance on the sphere. chosen_idx = np.random.randint(0, n_samples) chosen_point = a_translated[0, chosen_idx] dots = torch.clamp(torch.matmul(a_translated[0], chosen_point), -1.0, 1.0) geodesic_distances = torch.acos(dots) labels = np.where(geodesic_distances.cpu().numpy() < 0.5, 1, -1) return t, a_translated, adj, L_test, target_eigenvals, target_ev else: return adj, L_test, target_eigenvals, target_ev def cache_or_compute_test_data(n_samples, scale_rbf, k_nn, test_seed, cache_dir="./cache", force_recompute=False, device=None): """ Cache test data to disk or retrieve it if it exists. Args: n_samples (int): Number of samples scale_rbf (float): Scale parameter for RBF kernel k_nn (int): Number of nearest neighbors test_seed (int): Random seed for test data cache_dir (str): Directory to store cached data force_recompute (bool): Whether to force recomputation even if cache exists device: Device to create tensors on Returns: tuple: (L_test, xyz_test, labels_test, adjacency) """ # Create cache directory if it doesn't exist os.makedirs(cache_dir, exist_ok=True) # Create a unique filename based on parameters (note "sphere" in the filename) cache_filename = f"{cache_dir}/sphere_n{n_samples}_s{scale_rbf}_k{k_nn}_seed{test_seed}.pt" if os.path.exists(cache_filename) and not force_recompute: # Load cached data print(f"Loading cached test data from {cache_filename}") cached_data = torch.load(cache_filename) L_test = cached_data["L_test"] xyz_test = cached_data["xyz_test"] labels_test = cached_data["labels_test"] adjacency = cached_data["adjacency"] if device is not None: L_test = L_test.to(device) return L_test, xyz_test, labels_test, adjacency else: # Generate new data print(f"Generating new test data with seed {test_seed}") L_test, xyz_test, labels_test, adjacency = generate_small_sphere_in_3d( n_samples=n_samples, scale_rbf=scale_rbf, k_nn=k_nn, seed=test_seed, device=device ) # Cache the data cached_data = { "L_test": L_test.cpu(), "xyz_test": xyz_test, "labels_test": labels_test, "adjacency": adjacency } torch.save(cached_data, cache_filename) print(f"Cached test data to {cache_filename}") return L_test, xyz_test, labels_test, adjacency def visualize_adjacency_matrix(adjacency_matrix, title="Adjacency Matrix"): """ Visualize an adjacency matrix as a heatmap. Args: adjacency_matrix: 2D tensor or array representing the adjacency matrix title (str): Title for the plot """ plt.figure(figsize=(8, 6)) plt.imshow(adjacency_matrix, cmap='viridis', interpolation='nearest') plt.colorbar(label="Edge Weight") plt.title(title) plt.xlabel("Node Index") plt.ylabel("Node Index") plt.grid(False) plt.show() def visualize_3d_points(xyz, labels=None, title="3D Points"): """ Visualize points in 3D space. Args: xyz: Array of shape [n_samples, 3] containing 3D coordinates labels: Optional array of labels for coloring the points title (str): Title for the plot """ fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111, projection='3d') if labels is not None: scatter = ax.scatter(xyz[:, 0], xyz[:, 1], xyz[:, 2], c=labels, cmap='bwr', s=40, alpha=0.8) legend = ax.legend(*scatter.legend_elements(), title="Classes") ax.add_artist(legend) else: ax.scatter(xyz[:, 0], xyz[:, 1], xyz[:, 2], s=40, alpha=0.8) ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") ax.set_title(title) plt.tight_layout() plt.show()