|
|
|
|
|
""" |
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)") |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
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") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|