| |
| """ |
| cluster_split.py |
| |
| Author: natelgrw |
| Last Edited: 11/07/2025 |
| |
| Performs spatial KMeans cluster splitting for the AMAX dataset directly on |
| 2D UMAP coordinates. This ensures visual consistency between the UMAP |
| visualization and the actual fold assignments, and creates realistic chemical |
| neighborhoods for evaluation. |
| """ |
|
|
| import os |
| import random |
| import numpy as np |
| import pandas as pd |
| from collections import defaultdict |
| from rdkit import Chem |
| from rdkit.Chem import AllChem |
| from sklearn.cluster import KMeans |
| import matplotlib.pyplot as plt |
| import seaborn as sns |
| import umap |
|
|
|
|
| |
|
|
|
|
| INPUT_CSV = "../amax_dataset.csv" |
| OUTPUT_DIR = "../cluster_split" |
| N_REGIONS = 5 |
| RANDOM_SEED = 42 |
|
|
| random.seed(RANDOM_SEED) |
| np.random.seed(RANDOM_SEED) |
|
|
|
|
| |
|
|
|
|
| def compute_fingerprints(df, smiles_column="compound"): |
| """ |
| Compute Morgan fingerprints for all SMILES. |
| Returns array of fingerprints and list of valid indices. |
| """ |
| fps, valid_idx = [], [] |
| print("Computing Morgan fingerprints (radius=2, nBits=2048)...") |
| for i, smi in enumerate(df[smiles_column]): |
| mol = Chem.MolFromSmiles(smi) |
| if mol is None: |
| continue |
| fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=2048) |
| fps.append(fp) |
| valid_idx.append(i) |
| fps_array = np.array([list(fp) for fp in fps], dtype=np.float32) |
| print(f"Valid compounds: {len(fps_array):,}") |
| return fps_array, valid_idx |
|
|
|
|
| def compute_umap_embedding(fps_array): |
| """ |
| Compute 2D UMAP embedding of fingerprints using Jaccard metric. |
| Returns 2D coordinates for spatial clustering. |
| """ |
| print("\nComputing 2D UMAP embedding (Jaccard/Tanimoto metric)...") |
| fps_bin = (fps_array > 0).astype(float) |
| reducer = umap.UMAP( |
| n_neighbors=25, |
| min_dist=0.1, |
| metric="jaccard", |
| random_state=RANDOM_SEED, |
| ) |
| emb = reducer.fit_transform(fps_bin) |
| print(f" UMAP embedding computed: {emb.shape}") |
| return emb |
|
|
|
|
| def spatial_cluster_split(df, umap_coords, valid_indices, n_regions): |
| """ |
| Performs spatial KMeans clustering directly on UMAP 2D coordinates. |
| Each KMeans cluster becomes one fold - simple 1:1 mapping. |
| Creates visually consistent and chemically meaningful regions. |
| """ |
| print("=" * 65) |
| print("Performing Spatial KMeans Clustering on 2D UMAP Coordinates") |
| print("=" * 65) |
| |
| print(f"\nRunning KMeans with k={n_regions} on 2D UMAP coordinates...") |
| km = KMeans(n_clusters=n_regions, random_state=RANDOM_SEED, n_init=20) |
| labels = km.fit_predict(umap_coords) |
| |
| print(f"\nCluster centroids in 2D UMAP space:") |
| for i, centroid in enumerate(km.cluster_centers_): |
| print(f" Region {i+1}: ({centroid[0]:.2f}, {centroid[1]:.2f})") |
| |
| folds = defaultdict(list) |
| for local_idx, global_idx in enumerate(valid_indices): |
| region = labels[local_idx] |
| folds[region].append(global_idx) |
| |
| total = len(df) |
| print("\nRegion Summary:") |
| for r in sorted(folds.keys()): |
| n = len(folds[r]) |
| p = 100 * n / total |
| print(f"Region {r+1}: {n:,} compounds ({p:.2f}%)") |
| |
| return folds, labels |
|
|
|
|
| def save_cluster_assignments(df, folds, cluster_labels, umap_coords, valid_idx, output_dir): |
| """ |
| Saves cluster assignments with UMAP coordinates to CSV. |
| Format: compound,cluster,fold,umap_x,umap_y |
| """ |
| print("\nSaving cluster assignments...") |
| fig_dir = os.path.join(output_dir, "figures") |
| os.makedirs(fig_dir, exist_ok=True) |
| |
| assignments = [] |
| for fold_id, indices in folds.items(): |
| for global_idx in indices: |
| if global_idx in valid_idx: |
| local_idx = valid_idx.index(global_idx) |
| compound_smiles = df.loc[global_idx, 'compound'] |
| cluster = int(cluster_labels[local_idx]) |
| fold = fold_id + 1 |
| umap_x = umap_coords[local_idx, 0] |
| umap_y = umap_coords[local_idx, 1] |
| |
| assignments.append({ |
| 'compound': compound_smiles, |
| 'cluster': cluster, |
| 'fold': fold, |
| 'umap_x': umap_x, |
| 'umap_y': umap_y |
| }) |
| |
| assignments_df = pd.DataFrame(assignments) |
| output_file = os.path.join(fig_dir, "cluster_assignments.csv") |
| assignments_df.to_csv(output_file, index=False) |
| print(f"Saved figures/cluster_assignments.csv: {len(assignments_df):,} entries") |
|
|
|
|
| def visualize_lambda_max(df, folds, output_dir): |
| """ |
| Plots λmax distributions across regions. |
| """ |
| if "lambda_max" not in df.columns: |
| return |
| print("\nGenerating λmax distribution plot...") |
| os.makedirs(output_dir, exist_ok=True) |
|
|
| fig_dir = os.path.join(output_dir, "figures") |
| os.makedirs(fig_dir, exist_ok=True) |
|
|
| plt.figure(figsize=(12, 6)) |
| colors = sns.color_palette("husl", len(folds)) |
|
|
| for i, (r, idxs) in enumerate(sorted(folds.items())): |
| region_df = df.loc[idxs] |
| sns.kdeplot( |
| data=region_df, |
| x="lambda_max", |
| label=f"Cluster {r+1} (n={len(region_df):,})", |
| linewidth=2.2, |
| color=colors[i], |
| ) |
|
|
| sns.kdeplot( |
| data=df, |
| x="lambda_max", |
| label=f"Overall (n={len(df):,})", |
| linewidth=2.0, |
| linestyle="--", |
| color="black", |
| alpha=0.7, |
| ) |
|
|
| plt.title("Lambda Max Distribution Across Cluster Splits", fontsize=14, fontweight="bold") |
| plt.xlabel("λmax (nm)", fontsize=12, fontweight="bold") |
| plt.ylabel("Density", fontsize=12, fontweight="bold") |
| plt.legend(frameon=True, shadow=True) |
| plt.tight_layout() |
| plt.savefig(os.path.join(fig_dir, "cluster_lmax.png"), dpi=300) |
| plt.close() |
| print("Saved figures/cluster_lmax.png") |
|
|
|
|
| def visualize_umap(umap_coords, valid_idx, folds, output_dir): |
| """ |
| Generates 2D UMAP of chemical space colored by region. |
| """ |
| print("\nGenerating UMAP visualization...") |
| os.makedirs(output_dir, exist_ok=True) |
|
|
| colors = sns.color_palette("husl", len(folds)) |
| plt.figure(figsize=(12, 10)) |
| for i, (r, idxs) in enumerate(sorted(folds.items())): |
| local_idx = [j for j, g in enumerate(valid_idx) if g in idxs] |
| label = f"Cluster {r+1} (n={len(local_idx):,})" |
| plt.scatter( |
| umap_coords[local_idx, 0], |
| umap_coords[local_idx, 1], |
| s=10, |
| alpha=0.6, |
| label=label, |
| color=colors[i], |
| ) |
|
|
| plt.title( |
| "UMAP Projection of Compound Space (Colored by Cluster Split)", |
| fontsize=14, |
| fontweight="bold", |
| ) |
|
|
|
|
| plt.legend(markerscale=2, frameon=True, loc='best') |
| plt.tight_layout() |
| os.makedirs(os.path.join(output_dir, "figures"), exist_ok=True) |
| plt.savefig(os.path.join(output_dir, "figures/cluster_umap.png"), dpi=300) |
| plt.close() |
| print("Saved figures/cluster_umap.png") |
|
|
|
|
| |
|
|
|
|
| def main(): |
| """ |
| Main function to perform spatial cluster splitting. |
| """ |
| print("=" * 65) |
| print("SPATIAL CLUSTER SPLITTING PIPELINE") |
| print("=" * 65) |
| print(f"Configuration:") |
| print(f"- Number of regions: {N_REGIONS}") |
| print(f"- Clustering dimension: 2D (UMAP coordinates)") |
| print(f"- Random seed: {RANDOM_SEED}") |
| print(f"- Input: {INPUT_CSV}") |
| print(f"- Output: {OUTPUT_DIR}") |
| print() |
| |
| print("Loading dataset...") |
| df = pd.read_csv(INPUT_CSV) |
| print(f"Loaded {len(df):,} rows.") |
| |
| fps_array, valid_idx = compute_fingerprints(df) |
| |
| umap_coords = compute_umap_embedding(fps_array) |
| |
| folds, cluster_labels = spatial_cluster_split( |
| df, umap_coords, valid_idx, N_REGIONS |
| ) |
| |
| print("\nSaving cluster CSV files...") |
| os.makedirs(OUTPUT_DIR, exist_ok=True) |
| for r, idxs in folds.items(): |
| output_path = os.path.join(OUTPUT_DIR, f"cluster_{r+1}.csv") |
| df.loc[idxs].to_csv(output_path, index=False) |
| print(f" Saved cluster_{r+1}.csv") |
| |
| save_cluster_assignments(df, folds, cluster_labels, umap_coords, valid_idx, OUTPUT_DIR) |
| |
| visualize_lambda_max(df, folds, OUTPUT_DIR) |
| visualize_umap(umap_coords, valid_idx, folds, OUTPUT_DIR) |
| |
| print("\n" + "=" * 65) |
| print("CLUSTERING COMPLETE!") |
| print("=" * 65) |
| print(f"Output directory: {OUTPUT_DIR}") |
| print(f"- {len(folds)} region CSV files") |
| print(f"- figures/cluster_assignments.csv") |
| print(f"- figures/cluster_lmax.png") |
| print(f"- figures/cluster_umap.png") |
| print() |
| print("Note: Clustering performed in 2D UMAP space for visual consistency") |
|
|
|
|
| if __name__ == "__main__": |
| main() |