File size: 11,721 Bytes
155c363 |
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 |
#!/usr/bin/env python3
"""
solvent_split.py
Author: natelgrw
Last Edited: 11/05/2025
Performs spatial KMeans cluster splitting on AMAX solvent chemical space.
Clusters solvents in 5 groups by similarity using UMAP + KMeans, then assigns compounds
to folds based on their solvent's cluster membership.
This ensures compounds are split by solvent similarity rather than
individual solvent identity.
"""
import pandas as pd
import numpy as np
from rdkit import Chem
from rdkit.Chem import AllChem
import random
import os
from collections import defaultdict
import matplotlib.pyplot as plt
import seaborn as sns
import umap
from sklearn.cluster import KMeans
# ===== Configuration ===== #
INPUT_CSV = "../amax_dataset.csv"
OUTPUT_DIR = "../solvent_split"
N_SOLVENT_CLUSTERS = 5
RANDOM_SEED = 42
random.seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
# ===== Helper Functions ===== #
def compute_solvent_fingerprints(unique_solvents):
"""
Compute Morgan fingerprints for unique solvents.
"""
fps = []
valid_solvents = []
for solvent in unique_solvents:
try:
mol = Chem.MolFromSmiles(solvent)
if mol is not None:
fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=1024)
fps.append(fp)
valid_solvents.append(solvent)
except Exception:
print(f"Warning: Could not process solvent {solvent}")
continue
fps_array = np.array([list(fp) for fp in fps], dtype=np.float32)
solvent_to_idx = {solv: idx for idx, solv in enumerate(valid_solvents)}
print(f"Valid solvents: {len(fps_array)}")
print(f"Fingerprint dimension: {fps_array.shape[1]}")
return fps_array, valid_solvents, solvent_to_idx
def compute_solvent_umap(solvent_fps):
"""
Compute 2D UMAP embedding of solvent fingerprints using Jaccard metric.
Returns 2D coordinates for spatial clustering.
"""
print("\nComputing 2D UMAP embedding of solvent space...")
fps_bin = (solvent_fps > 0).astype(float)
reducer = umap.UMAP(
n_neighbors=min(15, len(solvent_fps) - 1),
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 cluster_solvents(solvent_umap_coords, valid_solvents, n_clusters):
"""
Performs spatial KMeans clustering directly on solvent UMAP 2D coordinates.
"""
print("\n" + "=" * 65)
print("Performing Spatial KMeans Clustering on Solvent UMAP Coordinates")
print("=" * 65)
print(f"\nRunning KMeans with k={n_clusters} on solvent 2D UMAP coordinates...")
km = KMeans(n_clusters=n_clusters, random_state=RANDOM_SEED, n_init=20)
labels = km.fit_predict(solvent_umap_coords)
print(f"\nSolvent cluster centroids:")
for i, centroid in enumerate(km.cluster_centers_):
print(f" Cluster {i+1}: ({centroid[0]:.2f}, {centroid[1]:.2f})")
solvent_to_cluster = {solvent: int(labels[idx])
for idx, solvent in enumerate(valid_solvents)}
print(f"\nSolvent cluster assignments:")
clusters = defaultdict(list)
for solvent, cluster in solvent_to_cluster.items():
clusters[cluster].append(solvent)
for cluster_id in sorted(clusters.keys()):
solvents_in_cluster = clusters[cluster_id]
print(f"Cluster {cluster_id+1}: {len(solvents_in_cluster)} solvents")
for solv in sorted(solvents_in_cluster):
print(f"- {solv}")
return solvent_to_cluster, labels, km
def create_visualizations(df, cluster_folds, solvent_umap_coords, valid_solvents,
solvent_cluster_labels, solvent_to_cluster, output_dir_path):
"""
Create visualizations for solvent cluster split analysis.
"""
print("\n" + "=" * 65)
print("Generating Visualizations")
print("=" * 65)
sns.set_style("whitegrid")
plt.rcParams['figure.dpi'] = 100
plt.rcParams['savefig.dpi'] = 300
fig_dir = os.path.join(output_dir_path, "figures")
os.makedirs(fig_dir, exist_ok=True)
n_clusters = len(cluster_folds)
colors = sns.color_palette("husl", n_clusters)
if 'lambda_max' in df.columns:
print("\n1. Creating lambda_max distribution plot...")
fig, ax = plt.subplots(figsize=(12, 6))
for cluster_id in sorted(cluster_folds.keys()):
group_df = cluster_folds[cluster_id]
fold_label = f"Cluster {cluster_id+1} (n={len(group_df):,})"
sns.kdeplot(data=group_df, x='lambda_max', label=fold_label,
ax=ax, linewidth=2.5, color=colors[cluster_id])
sns.kdeplot(data=df, x='lambda_max', label=f'Overall (n={len(df):,})',
ax=ax, linewidth=2, linestyle='--', color='black', alpha=0.7)
ax.set_xlabel('λmax (nm)', fontsize=12, fontweight='bold')
ax.set_ylabel('Density', fontsize=12, fontweight='bold')
ax.set_title('Lambda Max Distribution Across Solvent Splits',
fontsize=14, fontweight='bold')
ax.legend(loc='best', frameon=True, shadow=True)
ax.grid(alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(fig_dir, 'solvent_lmax.png'), bbox_inches='tight')
print(f"Saved: figures/solvent_lmax.png")
plt.close()
print("\n2. Creating solvent space UMAP visualization...")
solvent_counts = df['solvent'].value_counts().to_dict()
fig, ax = plt.subplots(figsize=(14, 10))
for cluster_id in range(n_clusters):
cluster_solvents = [solv for solv, cid in solvent_to_cluster.items() if cid == cluster_id]
cluster_indices = [valid_solvents.index(solv) for solv in cluster_solvents if solv in valid_solvents]
if len(cluster_indices) > 0:
cluster_coords = solvent_umap_coords[cluster_indices]
sizes = [np.log10(solvent_counts.get(valid_solvents[idx], 1) + 1) * 50 for idx in cluster_indices]
ax.scatter(cluster_coords[:, 0], cluster_coords[:, 1],
label=f'Cluster {cluster_id+1} ({len(cluster_solvents)} solvents)',
alpha=0.7, s=sizes, color=colors[cluster_id], edgecolors='black', linewidth=0.5)
ax.set_title('UMAP Projection of Chemical Solvent Space (Colored by Solvent Split)',
fontsize=14, fontweight='bold')
ax.legend(loc='best', frameon=True, shadow=True, fontsize=10)
ax.grid(alpha=0.3)
plt.tight_layout()
plt.savefig(os.path.join(fig_dir, 'solvent_umap.png'), bbox_inches='tight')
print(f"Saved: figures/solvent_umap.png")
plt.close()
print(f"\nAll visualizations saved to: {os.path.join(output_dir_path, 'figures')}")
# ===== Main ===== #
def main():
"""
Main function to perform spatial solvent cluster splitting.
"""
print("=" * 65)
print("SPATIAL SOLVENT CLUSTER SPLITTING PIPELINE")
print("=" * 65)
print(f"Configuration:")
print(f"- Number of solvent clusters: {N_SOLVENT_CLUSTERS}")
print(f"- Random seed: {RANDOM_SEED}")
print(f"- Input: {INPUT_CSV}")
print(f"- Output: {OUTPUT_DIR}")
print()
print("Step 1: Loading dataset...")
input_path = os.path.join(os.path.dirname(__file__), INPUT_CSV)
if not os.path.exists(input_path):
raise FileNotFoundError(f"Input file not found: {input_path}")
df = pd.read_csv(input_path)
if 'solvent' not in df.columns:
raise ValueError("Dataset must contain 'solvent' column")
print(f"Total compounds: {len(df):,}")
print(f"Columns: {df.columns.tolist()}")
print(f"\nStep 2: Analyzing solvent distribution...")
solvent_counts = df['solvent'].value_counts()
print(f"Unique solvents: {len(solvent_counts):,}")
distribution_data = []
for solvent, count in solvent_counts.items():
distribution_data.append({
'solvent': solvent,
'count': int(count),
'percentage': 100 * count / len(df)
})
distribution_df = pd.DataFrame(distribution_data)
distribution_df = distribution_df.sort_values('count', ascending=False)
print(f"\nTop 10 solvents by occurrence:")
for idx, row in distribution_df.head(10).iterrows():
print(f"{row['solvent']}: {row['count']:,} ({row['percentage']:.2f}%)")
unique_solvents = df['solvent'].unique().tolist()
solvent_fps, valid_solvents, solvent_to_idx = compute_solvent_fingerprints(unique_solvents)
print(f"\nStep 3: Computing UMAP on solvent space...")
solvent_umap_coords = compute_solvent_umap(solvent_fps)
print(f"\nStep 4: Clustering solvents...")
solvent_to_cluster, solvent_cluster_labels, km = cluster_solvents(
solvent_umap_coords, valid_solvents, N_SOLVENT_CLUSTERS
)
print(f"\nStep 5: Assigning compounds to solvent clusters...")
cluster_folds = defaultdict(list)
for idx, row in df.iterrows():
solvent = row['solvent']
if solvent in solvent_to_cluster:
cluster_id = solvent_to_cluster[solvent]
cluster_folds[cluster_id].append(idx)
else:
print(f"Warning: Solvent '{solvent}' not found in valid solvents")
cluster_dataframes = {}
for cluster_id, indices in cluster_folds.items():
cluster_dataframes[cluster_id] = df.loc[indices].copy()
print(f"\nCluster summary:")
for cluster_id in sorted(cluster_dataframes.keys()):
n = len(cluster_dataframes[cluster_id])
p = 100 * n / len(df)
print(f"Cluster {cluster_id+1}: {n:,} compounds ({p:.2f}%)")
output_dir_path = os.path.join(os.path.dirname(__file__), OUTPUT_DIR)
os.makedirs(output_dir_path, exist_ok=True)
print(f"\nStep 6: Saving solvent cluster CSV files to '{OUTPUT_DIR}'...")
for cluster_id in sorted(cluster_dataframes.keys()):
output_file = os.path.join(output_dir_path, f"solvents_{cluster_id+1}.csv")
cluster_dataframes[cluster_id].to_csv(output_file, index=False)
print(f"Saved solvents_{cluster_id+1}.csv: {len(cluster_dataframes[cluster_id]):,} compounds")
fig_dir = os.path.join(output_dir_path, "figures")
os.makedirs(fig_dir, exist_ok=True)
print(f"\nStep 7: Creating enhanced solvent_distribution.csv...")
distribution_df['solvent_cluster'] = distribution_df['solvent'].map(
lambda s: solvent_to_cluster.get(s, -1)
)
distribution_df['solvent_cluster'] = distribution_df['solvent_cluster'].apply(
lambda c: f"Cluster {c+1}" if c >= 0 else "Unknown"
)
distribution_file = os.path.join(fig_dir, "solvent_distribution.csv")
distribution_df.to_csv(distribution_file, index=False)
print(f"Saved figures/solvent_distribution.csv: {len(distribution_df):,} entries")
print(f"\nStep 8: Creating visualizations...")
create_visualizations(
df, cluster_dataframes, solvent_umap_coords, valid_solvents,
solvent_cluster_labels, solvent_to_cluster, output_dir_path
)
print("\n" + "=" * 65)
print("SOLVENT CLUSTERING COMPLETE!")
print("=" * 65)
print(f"Output directory: {OUTPUT_DIR}")
print(f"- {len(cluster_dataframes)} solvent cluster CSV files (solvents_1.csv, solvents_2.csv, etc.)")
print(f"- figures/solvent_distribution.csv")
print(f"- figures/solvent_lmax.png")
print(f"- figures/solvent_umap.png (shows solvent chemical space)")
if __name__ == "__main__":
main()
|