File size: 16,801 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 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 |
#!/usr/bin/env python3
"""
scaffold_split.py
Author: natelgrw
Last Edited: 11/02/2025
Computes Bemis-Murcko scaffolds for the retina dataset using RDKit
and splits scaffolds into 5 distinct folds with approximately balanced
compound counts across folds. Computes UMAP, scaffold assignments, and
method length distributions for visualizing scaffold splits.
"""
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, Counter
import random
from tqdm import tqdm
from rdkit import Chem
from rdkit.Chem.Scaffolds import MurckoScaffold
from rdkit.Chem import AllChem
import umap
# ===== Configuration ===== #
INPUT_CSV = "../retina_dataset.csv"
OUTPUT_DIR = "../scaffold_split"
N_FOLDS = 5
RANDOM_SEED = 42
random.seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
# ===== Helper Functions ===== #
def get_murcko_scaffold(smiles):
"""
Compute Bemis-Murcko scaffold from SMILES string.
"""
try:
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return "INVALID"
scaffold = MurckoScaffold.MurckoScaffoldSmiles(mol=mol)
return scaffold if scaffold else "NO_SCAFFOLD"
except Exception as e:
return "INVALID"
def analyze_dataset(df):
"""
Prints dataset statistics.
"""
print("=" * 70)
print("Dataset Analysis")
print("=" * 70)
print(f"Total rows: {len(df):,}")
print(f"Columns: {df.columns.tolist()}")
print(f"\nUnique compounds: {df['compound'].nunique():,}")
if 'rt' in df.columns:
print(f"\nRetention time statistics:")
print(f"Min: {df['rt'].min():.2f} min")
print(f"Max: {df['rt'].max():.2f} min")
print(f"Mean: {df['rt'].mean():.2f} min")
print(f"Median: {df['rt'].median():.2f} min")
print()
def assign_scaffolds_to_folds(scaffold_sizes, n_folds):
"""
Assign scaffolds to folds using a greedy algorithm to balance compound counts.
"""
fold_assignments = defaultdict(list)
fold_counts = [0] * n_folds
sorted_scaffolds = sorted(scaffold_sizes.items(), key=lambda x: x[1], reverse=True)
# greedy scaffold assignment
for scaffold, size in sorted_scaffolds:
min_fold = min(range(n_folds), key=lambda i: fold_counts[i])
fold_assignments[min_fold].append(scaffold)
fold_counts[min_fold] += size
return fold_assignments, fold_counts
# ===== Analyzer Class ===== #
class ScaffoldAnalyzer:
"""
Analyzer for scaffold splitting and visualization.
"""
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.scaffold_dict = {}
self.scaffold_to_compounds = defaultdict(list)
def load_data(self, sample_size=None):
"""
Loads the retina dataset.
"""
print("\n" + "=" * 70)
print("LOADING DATA")
print("=" * 70)
if sample_size:
print(f"Loading {sample_size:,} rows (sample)...")
self.df = pd.read_csv(self.data_path, nrows=sample_size)
else:
print(f"Loading full dataset from {self.data_path}...")
chunks = []
chunk_size = 100000
for chunk in tqdm(pd.read_csv(self.data_path, chunksize=chunk_size),
desc="Reading chunks"):
chunks.append(chunk)
self.df = pd.concat(chunks, ignore_index=True)
print(f" Loaded {len(self.df):,} data points")
print(f" Columns: {list(self.df.columns)}")
return self.df
def extract_scaffolds(self):
"""
Extracts Bemis-Murcko scaffolds from SMILES.
"""
print("\n" + "=" * 70)
print("EXTRACTING BEMIS-MURCKO SCAFFOLDS")
print("=" * 70)
print("Computing scaffolds for all compounds...")
self.df['scaffold'] = self.df['compound'].apply(get_murcko_scaffold)
invalid_count = (self.df['scaffold'] == "INVALID").sum()
no_scaffold_count = (self.df['scaffold'] == "NO_SCAFFOLD").sum()
valid_count = len(self.df) - invalid_count - no_scaffold_count
if invalid_count > 0:
print(f"Warning: {invalid_count:,} rows have invalid SMILES")
if no_scaffold_count > 0:
print(f"Info: {no_scaffold_count:,} rows have no scaffold (single atoms)")
print(f"Successfully extracted scaffolds for {valid_count:,} rows")
scaffold_groups = self.df.groupby('scaffold')
scaffold_sizes = scaffold_groups.size().to_dict()
n_unique_scaffolds = len(scaffold_sizes)
sizes_array = np.array(list(scaffold_sizes.values()))
print(f"\nScaffold Statistics:")
print(f"Unique scaffolds: {n_unique_scaffolds:,}")
print(f"Scaffolds with 1 data point: {(sizes_array == 1).sum():,}")
print(f"Scaffolds with >10 data points: {(sizes_array > 10).sum():,}")
print(f"Scaffolds with >100 data points: {(sizes_array > 100).sum():,}")
print(f"Mean data points per scaffold: {sizes_array.mean():.2f}")
print(f"Median data points per scaffold: {np.median(sizes_array):.0f}")
print(f"Max data points in a scaffold: {sizes_array.max():,}")
return scaffold_sizes
def create_scaffold_splits(self, scaffold_sizes, n_splits=5):
"""
Creates scaffold-based cross-validation splits.
Splits are created by grouping scaffolds to balance the number of data points
in each fold while ensuring no scaffold appears in multiple folds.
"""
print("\n" + "=" * 70)
print(f"CREATING {n_splits}-FOLD SCAFFOLD SPLITS")
print("=" * 70)
print(f"Assigning {len(scaffold_sizes):,} scaffolds to {n_splits} folds...")
fold_assignments, fold_counts = assign_scaffolds_to_folds(scaffold_sizes, n_splits)
print("\nFold Statistics:")
print("-" * 70)
for fold_id in range(n_splits):
scaffolds = fold_assignments[fold_id]
count = fold_counts[fold_id]
percentage = 100 * count / len(self.df)
print(f"Fold {fold_id + 1}: {count:,} data points ({percentage:.2f}%) | "
f"{len(scaffolds):,} scaffolds")
print("-" * 70)
print(f"Total: {sum(fold_counts):,} data points")
scaffold_to_fold = {}
for fold_idx in range(n_splits):
for scaffold in fold_assignments[fold_idx]:
scaffold_to_fold[scaffold] = fold_idx + 1
self.df['fold'] = self.df['scaffold'].map(scaffold_to_fold)
print(f"\nSaving fold CSV files...")
fold_dataframes = {}
for fold_id in range(n_splits):
fold_df = self.df[self.df['fold'] == fold_id + 1].copy()
fold_df_output = fold_df.drop(columns=['scaffold', 'fold'])
output_file = self.output_dir / f"fold_{fold_id + 1}.csv"
fold_df_output.to_csv(output_file, index=False)
fold_dataframes[fold_id] = fold_df
print(f"Saved fold_{fold_id + 1}.csv: {len(fold_df):,} rows")
scaffold_assignments_data = []
for fold_id in range(n_splits):
for scaffold in fold_assignments[fold_id]:
scaffold_assignments_data.append({
'scaffold': scaffold,
'fold': fold_id + 1,
'datapoint_count': scaffold_sizes[scaffold]
})
scaffold_assignments_df = pd.DataFrame(scaffold_assignments_data)
scaffold_assignments_df = scaffold_assignments_df.sort_values(
['fold', 'datapoint_count'], ascending=[True, False]
)
scaffold_assignments_file = self.output_dir / "figures/scaffold_assignments.csv"
scaffold_assignments_df.to_csv(scaffold_assignments_file, index=False)
print(f"\nSaved scaffold assignments to: scaffold_assignments.csv")
print(f"Total scaffolds: {len(scaffold_assignments_df):,}")
print(f"Columns: scaffold, fold, datapoint_count")
print("\nVerifying scaffold separation...")
all_fold_scaffolds = [set(fold_assignments[i]) for i in range(n_splits)]
has_overlap = False
for i in range(n_splits):
for j in range(i + 1, n_splits):
overlap = all_fold_scaffolds[i] & all_fold_scaffolds[j]
if overlap:
print(f"ERROR: Overlap between fold {i+1} and fold {j+1}: {len(overlap)} scaffolds")
has_overlap = True
if not has_overlap:
print(f"No overlap - all scaffolds are uniquely assigned")
all_assigned = set()
for fold_id in range(n_splits):
all_assigned.update(fold_assignments[fold_id])
if len(all_assigned) == len(scaffold_sizes):
print(f"All {len(scaffold_sizes):,} scaffolds assigned to folds")
else:
missing = set(scaffold_sizes.keys()) - all_assigned
print(f"WARNING: {len(missing)} scaffolds not assigned to any fold")
return fold_assignments, scaffold_to_fold, fold_dataframes
def visualize_rt_distributions(self, fold_dataframes):
"""
Generates an RT (retention time) KDE plot across folds.
"""
print("\n" + "=" * 70)
print("GENERATING RT DISTRIBUTION VISUALIZATION")
print("=" * 70)
# converting RT from seconds to minutes
valid_rt = self.df['rt'].dropna() / 60.0
print(f"Data points with valid RT: {len(valid_rt):,}")
print(f"\nRT Statistics (in minutes):")
print(f" Mean: {valid_rt.mean():.2f} minutes")
print(f" Median: {valid_rt.median():.2f} minutes")
print(f" Min: {valid_rt.min():.2f} minutes")
print(f" Max: {valid_rt.max():.2f} minutes")
print(f" Std: {valid_rt.std():.2f} minutes")
fig, ax = plt.subplots(figsize=(12, 6))
if fold_dataframes:
colors = sns.color_palette("husl", len(fold_dataframes))
for fold_id in range(len(fold_dataframes)):
fold_df = fold_dataframes[fold_id]
fold_rt = fold_df['rt'].dropna() / 60.0
if len(fold_rt) > 0:
sns.kdeplot(data=fold_rt, ax=ax,
label=f'Fold {fold_id + 1} (n={len(fold_rt):,})',
linewidth=2.5, color=colors[fold_id])
sns.kdeplot(data=valid_rt, ax=ax,
label=f'Overall (n={len(valid_rt):,})',
linewidth=2, linestyle='--', color='black', alpha=0.7)
else:
sns.kdeplot(data=valid_rt, ax=ax, linewidth=2.5, color='blue')
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 Scaffold Splits', fontsize=14, fontweight='bold')
ax.set_xlim(0, 135)
ax.legend(loc='best', frameon=True, fancybox=True, shadow=True)
ax.grid(alpha=0.3)
plt.tight_layout()
# creating figures subdirectory
figures_dir = self.output_dir / 'figures'
figures_dir.mkdir(exist_ok=True)
output_file = figures_dir / 'scaffold_rt.png'
plt.savefig(output_file, dpi=300, bbox_inches='tight')
print(f"\nSaved RT distribution visualization to figures/scaffold_rt.png")
plt.close()
def generate_umap(self, n_samples=None):
"""
Generates a UMAP visualization of chemical space.
Uses Morgan fingerprints for molecular representation.
"""
print("\n" + "=" * 70)
print("GENERATING UMAP VISUALIZATION")
print("=" * 70)
if n_samples is not None and len(self.df) > n_samples:
print(f"Sampling {n_samples:,} datapoints for UMAP...")
df_sample = self.df.sample(n=n_samples, random_state=42)
else:
print(f"Using all {len(self.df):,} datapoints for UMAP...")
df_sample = self.df
print(f"Generating Morgan fingerprints for {len(df_sample):,} datapoints...")
fps = []
valid_indices = []
for idx, smiles in tqdm(enumerate(df_sample['compound']),
total=len(df_sample),
desc="Generating fingerprints"):
try:
mol = Chem.MolFromSmiles(smiles)
if mol is not None:
fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=2048)
fps.append(fp)
valid_indices.append(idx)
except:
pass
print(f"Generated {len(fps):,} valid fingerprints")
fp_array = np.array([list(fp) for fp in fps])
df_valid = df_sample.iloc[valid_indices].reset_index(drop=True)
print(f"\nFitting UMAP (this may take a while)...")
print(f"n_samples: {len(fp_array):,}")
print(f"n_features: {fp_array.shape[1]}")
reducer = umap.UMAP(
n_neighbors=15,
min_dist=0.1,
n_components=2,
metric='jaccard',
random_state=42,
verbose=True
)
embedding = reducer.fit_transform(fp_array)
print(f"UMAP embedding complete")
# create umap visualization
print("\nGenerating UMAP visualization...")
fig, ax = plt.subplots(figsize=(14, 10))
if 'fold' in df_valid.columns:
colors = sns.color_palette("husl", df_valid['fold'].nunique())
for fold_id in sorted(df_valid['fold'].unique()):
mask = df_valid['fold'] == fold_id
fold_data = embedding[mask]
n_compounds = mask.sum()
ax.scatter(fold_data[:, 0], fold_data[:, 1],
label=f'Fold {int(fold_id)} (n={n_compounds:,})',
alpha=0.6, s=20, c=[colors[int(fold_id)-1]])
else:
ax.scatter(embedding[:, 0], embedding[:, 1],
alpha=0.6, s=20, color='blue')
ax.set_title('UMAP Projection of Compound Space (Colored by Scaffold Split)',
fontsize=14, fontweight='bold')
ax.legend(loc='best', frameon=True, fancybox=True, shadow=True, fontsize=10)
ax.grid(alpha=0.3)
plt.tight_layout()
# saving results to figures subdirectory
figures_dir = self.output_dir / 'figures'
figures_dir.mkdir(exist_ok=True)
output_file = figures_dir / 'scaffold_umap.png'
plt.savefig(output_file, dpi=300, bbox_inches='tight')
print(f"Saved UMAP visualization to figures/scaffold_umap.png")
plt.close()
return embedding, df_valid
# ===== Main ===== #
def main():
"""
Main execution function.
"""
print("\n" + "=" * 80)
print(" " * 20 + "BEMIS-MURCKO SCAFFOLD SPLIT")
print(" " * 25 + "Retina Dataset Analysis")
print("=" * 80)
script_dir = Path(__file__).parent
data_path = script_dir / INPUT_CSV
output_dir = script_dir / OUTPUT_DIR
print(f"\nConfiguration:")
print(f"Script location: {script_dir}")
print(f"Data path: {data_path}")
print(f"Output directory: {output_dir}")
print(f"Number of folds: {N_FOLDS}")
print(f"Random seed: {RANDOM_SEED}")
if not data_path.exists():
raise FileNotFoundError(f"Input file not found: {data_path}")
analyzer = ScaffoldAnalyzer(data_path, output_dir)
print("\nLoading dataset...")
analyzer.load_data(sample_size=None)
analyze_dataset(analyzer.df)
scaffold_sizes = analyzer.extract_scaffolds()
fold_assignments, scaffold_to_fold, fold_dataframes = analyzer.create_scaffold_splits(
scaffold_sizes, n_splits=N_FOLDS
)
analyzer.visualize_rt_distributions(fold_dataframes)
analyzer.generate_umap(n_samples=None) # Use all datapoints
print("\n" + "=" * 80)
print(" " * 25 + "5-FOLD SCAFFOLD SPLIT COMPLETE!")
print("=" * 80)
if __name__ == "__main__":
main()
|