File size: 14,245 Bytes
0eb933d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 |
#!/usr/bin/env python3
"""
cluster_split.py
Author: natelgrw
Created: 11/05/2025
Splits dataset into folds based on compound structural clustering using
Morgan fingerprints. Uses UMAP for dimensionality reduction and clustering
in a higher-dimensional space to preserve chemical similarity while enabling
spatial separation.
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from pathlib import Path
from collections import defaultdict
import random
from tqdm import tqdm
import umap
from sklearn.cluster import KMeans
from rdkit import Chem
from rdkit.Chem import AllChem, DataStructs
# ===== Configuration ===== #
INPUT_CSV = "../retina_dataset.csv"
OUTPUT_DIR = "../cluster_split"
N_FOLDS = 5
RANDOM_SEED = 42
UMAP_NEIGHBORS = 15
UMAP_MIN_DIST = 0.1
UMAP_VIZ_DIM = 2
FP_RADIUS = 2
FP_N_BITS = 2048
random.seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
# ===== Helper Functions ===== #
def analyze_dataset(df):
"""
Prints dataset statistics.
"""
print("=" * 70)
print("Dataset Analysis")
print("=" * 70)
print(f"Total rows: {len(df):,}")
if "compound" in df.columns:
print(f"Unique compounds: {df['compound'].nunique():,}")
if 'rt' in df.columns:
print(f"\nRetention Time Stats:")
print(f"Mean: {df['rt'].mean():.2f} s | Median: {df['rt'].median():.2f} s")
print()
def assign_clusters_to_folds(compound_sizes, n_folds, cluster_assignments):
"""
Assign compound clusters to folds with balancing.
"""
fold_assignments = defaultdict(list)
fold_counts = [0] * n_folds
cluster_to_compounds = defaultdict(list)
for compound, cluster_id in cluster_assignments.items():
cluster_to_compounds[cluster_id].append(compound)
cluster_info = []
for cluster_id, compounds in cluster_to_compounds.items():
size = sum(compound_sizes.get(c, 0) for c in compounds)
cluster_info.append((cluster_id, size, compounds))
cluster_info.sort(key=lambda x: x[1], reverse=True)
total_size = sum(compound_sizes.values())
target_size = total_size / n_folds
print(f"\nAssigning {len(cluster_info)} clusters to {n_folds} folds...")
print(f"Target size per fold: {target_size:,.0f} datapoints")
for cluster_id, size, compounds in cluster_info:
min_fold = min(range(n_folds), key=lambda i: fold_counts[i])
for compound in compounds:
fold_assignments[min_fold].append(compound)
fold_counts[min_fold] += compound_sizes.get(compound, 0)
print("\nFold balance:")
for i, count in enumerate(fold_counts):
print(f"Fold {i+1}: {count:,} datapoints ({100*count/total_size:.2f}%)")
print(f"Balance ratio: {max(fold_counts)/min(fold_counts):.2f}x")
return fold_assignments, fold_counts
# ===== Analyzer Class ===== #
class ClusterAnalyzer:
"""
Analyzer for compound clustering-based splitting.
"""
def __init__(self, data_path, output_dir):
self.data_path = Path(data_path)
self.output_dir = Path(output_dir)
self.output_dir.mkdir(exist_ok=True, parents=True)
self.df = None
self.compounds_df = None
def load_data(self):
"""Load dataset."""
print("\nLOADING RETINA DATASET")
self.df = pd.read_csv(self.data_path)
unique_compounds = self.df['compound'].unique()
self.compounds_df = pd.DataFrame({'compound': unique_compounds})
print(f"Loaded {len(self.df):,} datapoints with {len(unique_compounds):,} unique compounds.")
def compute_morgan_fingerprints(self):
"""Compute Morgan fingerprints for all compounds."""
print("\nCOMPUTING MORGAN FINGERPRINTS")
fingerprints = []
valid_compounds = []
for smiles in tqdm(self.compounds_df['compound'], desc="Computing fingerprints"):
mol = Chem.MolFromSmiles(smiles)
if mol is not None:
fp = AllChem.GetMorganFingerprintAsBitVect(
mol, FP_RADIUS, nBits=FP_N_BITS
)
arr = np.zeros((FP_N_BITS,), dtype=np.int8)
DataStructs.ConvertToNumpyArray(fp, arr)
fingerprints.append(arr)
valid_compounds.append(smiles)
else:
print(f"Warning: Could not parse SMILES: {smiles}")
fingerprints = np.array(fingerprints)
self.compounds_df = self.compounds_df[self.compounds_df['compound'].isin(valid_compounds)].copy()
print(f"Computed {len(fingerprints)} fingerprints of dimension {FP_N_BITS}")
return fingerprints
def compute_umap_embedding(self, fingerprints):
"""
Compute 2D UMAP embedding for clustering and visualization.
Clustering will be done directly on these 2D coordinates.
"""
print(f"\nCOMPUTING 2D UMAP EMBEDDING")
print("(Clustering will be done on 2D UMAP coordinates)")
# 2d embedding for visualization only
reducer_viz = umap.UMAP(
n_neighbors=UMAP_NEIGHBORS,
min_dist=UMAP_MIN_DIST,
n_components=UMAP_VIZ_DIM,
metric='jaccard',
random_state=RANDOM_SEED,
verbose=False
)
embedding_viz = reducer_viz.fit_transform(fingerprints)
print(f"2D UMAP computed: {embedding_viz.shape}")
return embedding_viz
def cluster_compounds(self, embedding, n_clusters):
"""
Cluster compounds using KMeans in 2D UMAP space.
This creates spatially-separated, visually distinct regions.
"""
print(f"\nCLUSTERING COMPOUNDS IN 2D UMAP SPACE")
print(f"Using KMeans with k={n_clusters} clusters...")
print(f"Input shape: {embedding.shape}")
kmeans = KMeans(
n_clusters=n_clusters,
random_state=RANDOM_SEED,
n_init=20,
max_iter=300,
verbose=0
)
cluster_labels = kmeans.fit_predict(embedding)
self.compounds_df['cluster'] = cluster_labels
# print cluster distribution
cluster_counts = pd.Series(cluster_labels).value_counts().sort_index()
print(f"\nCluster distribution:")
for cluster_id, count in cluster_counts.items():
print(f"Cluster {cluster_id}: {count:,} compounds")
return cluster_labels
def create_cluster_splits(self, n_splits=5):
"""
Create folds based on compound clusters in 2D UMAP space.
"""
print("\nCREATING CLUSTER SPLITS")
print("=" * 60)
print("\nStrategy: Cluster in 2D UMAP space for spatial separation")
fingerprints = self.compute_morgan_fingerprints()
embedding_viz = self.compute_umap_embedding(fingerprints)
self.compounds_df['umap_x'] = embedding_viz[:, 0]
self.compounds_df['umap_y'] = embedding_viz[:, 1]
cluster_labels = self.cluster_compounds(embedding_viz, n_clusters=n_splits)
cluster_assignments = dict(zip(
self.compounds_df['compound'],
self.compounds_df['cluster']
))
compound_sizes = self.df['compound'].value_counts().to_dict()
print(f"\n{len(compound_sizes):,} unique compounds in dataset.")
fold_assignments = defaultdict(list)
for cluster_id in range(n_splits):
cluster_compounds = self.compounds_df[self.compounds_df['cluster'] == cluster_id]['compound'].tolist()
fold_assignments[cluster_id] = cluster_compounds
fold_counts = [sum(compound_sizes.get(c, 0) for c in compounds)
for compounds in fold_assignments.values()]
total_size = sum(compound_sizes.values())
print("\nFold balance (direct 1:1 cluster-to-fold mapping):")
for i, count in enumerate(fold_counts):
print(f"Fold {i+1}: {count:,} datapoints ({100*count/total_size:.2f}%)")
print(f"Balance ratio: {max(fold_counts)/min(fold_counts):.2f}x")
compound_to_fold = {}
for fold_idx, compounds in fold_assignments.items():
for compound in compounds:
compound_to_fold[compound] = fold_idx + 1
self.df['fold'] = self.df['compound'].map(compound_to_fold)
self.compounds_df['fold'] = self.compounds_df['compound'].map(compound_to_fold)
compound_to_umap = dict(zip(
self.compounds_df['compound'],
zip(self.compounds_df['umap_x'], self.compounds_df['umap_y'])
))
self.df['umap_x'] = self.df['compound'].map(lambda c: compound_to_umap.get(c, (None, None))[0])
self.df['umap_y'] = self.df['compound'].map(lambda c: compound_to_umap.get(c, (None, None))[1])
fold_dataframes = {}
for i in range(n_splits):
fold_df = self.df[self.df['fold'] == i + 1].copy()
out_file = self.output_dir / f"cluster_{i+1}.csv"
fold_df.to_csv(out_file, index=False)
fold_dataframes[i] = fold_df
print(f"Saved cluster_{i+1}.csv ({len(fold_df):,} rows, {fold_df['compound'].nunique():,} compounds)")
cluster_file = self.output_dir / "figures" / "cluster_assignments.csv"
cluster_file.parent.mkdir(exist_ok=True, parents=True)
self.compounds_df[['compound', 'cluster', 'fold', 'umap_x', 'umap_y']].to_csv(
cluster_file, index=False
)
print(f"\nSaved cluster assignments to figures/cluster_assignments.csv")
return fold_dataframes
def visualize_rt_distributions(self, fold_dataframes):
"""
Generates a KDE plot of the RT distribution per cluster split.
"""
print("\nPLOTTING RETENTION TIME DISTRIBUTIONS")
fig, ax = plt.subplots(figsize=(14, 6))
colors = sns.color_palette("husl", len(fold_dataframes))
if "rt" in self.df.columns:
overall_rt = self.df["rt"].dropna() / 60.0
if len(overall_rt) > 0:
sns.kdeplot(
overall_rt, ax=ax,
color='black', linewidth=2.5,
linestyle='--',
label=f"Overall (n={len(overall_rt):,})"
)
for i, fold_df in fold_dataframes.items():
if "rt" not in fold_df.columns:
continue
rt_min = fold_df["rt"].dropna() / 60.0
if len(rt_min) > 0:
sns.kdeplot(
rt_min, ax=ax,
label=f"Cluster {i+1} (n={len(rt_min):,})",
color=colors[i],
linewidth=2.5
)
ax.set_xlabel("Retention Time (min)", fontsize=12, fontweight='bold')
ax.set_ylabel("Density", fontsize=12, fontweight='bold')
ax.set_title("Retention Time Distribution Across Cluster Splits", fontsize=14, fontweight='bold')
ax.legend(fontsize=10, framealpha=0.9)
ax.grid(alpha=0.3, linestyle=':', linewidth=0.5)
ax.set_xlim(left=0)
fig_dir = self.output_dir / "figures"
fig_dir.mkdir(exist_ok=True)
plt.savefig(fig_dir / "cluster_rt.png", dpi=300, bbox_inches="tight")
plt.close()
print(f"Saved RT KDE plot to figures/cluster_rt.png")
def generate_umap_plot(self):
"""
Generates a UMAP visualization colored by fold, showing all datapoints.
"""
print("\nGENERATING UMAP VISUALIZATION")
print(f"Plotting all {len(self.df):,} datapoints (including duplicates)")
plt.figure(figsize=(10, 7))
if "fold" in self.df.columns and "umap_x" in self.df.columns:
colors = sns.color_palette("husl", N_FOLDS)
for fold_num in sorted(self.df["fold"].dropna().unique()):
fold_data = self.df[self.df["fold"] == fold_num]
n_datapoints = len(fold_data)
plt.scatter(
fold_data["umap_x"], fold_data["umap_y"],
label=f"Cluster {int(fold_num)} (n={n_datapoints:,})",
s=5, alpha=0.5, edgecolor='none',
color=colors[int(fold_num) - 1]
)
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=10)
plt.title("UMAP Projection of Compound Space (Colored by Cluster Split)", fontsize=14, fontweight='bold', pad=15)
else:
plt.scatter(
self.df["umap_x"], self.df["umap_y"],
s=5, alpha=0.5, color="steelblue", edgecolor='none'
)
plt.tight_layout()
fig_dir = self.output_dir / "figures"
fig_dir.mkdir(exist_ok=True)
plt.savefig(fig_dir / "cluster_umap.png", dpi=300, bbox_inches="tight")
plt.close()
print(f"Saved UMAP plot to figures/cluster_umap.png")
# ===== Main ===== #
def main():
"""
Main execution function.
"""
print("\n" + "=" * 80)
print(" " * 30 + "CLUSTER SPLIT PIPELINE")
print(f"=" * 80)
print(f"1. Compute 2D UMAP embedding from 2048D fingerprints")
print(f"2. Cluster directly in 2D UMAP space (k={N_FOLDS})")
print(f"3. Assign clusters to folds (1:1 mapping)")
print(f"4. Result: Spatially-separated regions in UMAP visualization")
print(f"=" * 80)
analyzer = ClusterAnalyzer(INPUT_CSV, OUTPUT_DIR)
analyzer.load_data()
analyze_dataset(analyzer.df)
fold_dataframes = analyzer.create_cluster_splits(n_splits=N_FOLDS)
analyzer.generate_umap_plot()
analyzer.visualize_rt_distributions(fold_dataframes)
print("\n" + "=" * 80)
print(" " * 30 + "CLUSTER SPLIT COMPLETE!")
print("=" * 80)
print(f"\nOutputs in: {OUTPUT_DIR}/")
print(f"- cluster_1.csv through cluster_{N_FOLDS}.csv")
print(f"- figures/cluster_umap.png")
print(f"- figures/cluster_rt.png")
print(f"- figures/cluster_assignments.csv")
if __name__ == "__main__":
main()
|