|
|
|
|
|
""" |
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
INPUT_CSV = "../retina_dataset.csv" |
|
|
OUTPUT_DIR = "../scaffold_split" |
|
|
N_FOLDS = 5 |
|
|
RANDOM_SEED = 42 |
|
|
|
|
|
random.seed(RANDOM_SEED) |
|
|
np.random.seed(RANDOM_SEED) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
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") |
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
print("\n" + "=" * 80) |
|
|
print(" " * 25 + "5-FOLD SCAFFOLD SPLIT COMPLETE!") |
|
|
print("=" * 80) |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |
|
|
|
|
|
|