File size: 8,782 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
#!/usr/bin/env python3
"""
cluster_split.py

Author: natelgrw
Last Edited: 11/07/2025

Performs spatial KMeans cluster splitting for the AMAX dataset directly on 
2D UMAP coordinates. This ensures visual consistency between the UMAP 
visualization and the actual fold assignments, and creates realistic chemical 
neighborhoods for evaluation.
"""

import os
import random
import numpy as np
import pandas as pd
from collections import defaultdict
from rdkit import Chem
from rdkit.Chem import AllChem
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import seaborn as sns
import umap


# ===== Configuration ===== #


INPUT_CSV = "../amax_dataset.csv"
OUTPUT_DIR = "../cluster_split"
N_REGIONS = 5
RANDOM_SEED = 42

random.seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)


# ===== Helper Functions ===== #


def compute_fingerprints(df, smiles_column="compound"):
    """
    Compute Morgan fingerprints for all SMILES.
    Returns array of fingerprints and list of valid indices.
    """
    fps, valid_idx = [], []
    print("Computing Morgan fingerprints (radius=2, nBits=2048)...")
    for i, smi in enumerate(df[smiles_column]):
        mol = Chem.MolFromSmiles(smi)
        if mol is None:
            continue
        fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=2048)
        fps.append(fp)
        valid_idx.append(i)
    fps_array = np.array([list(fp) for fp in fps], dtype=np.float32)
    print(f"Valid compounds: {len(fps_array):,}")
    return fps_array, valid_idx


def compute_umap_embedding(fps_array):
    """
    Compute 2D UMAP embedding of fingerprints using Jaccard metric.
    Returns 2D coordinates for spatial clustering.
    """
    print("\nComputing 2D UMAP embedding (Jaccard/Tanimoto metric)...")
    fps_bin = (fps_array > 0).astype(float)
    reducer = umap.UMAP(
        n_neighbors=25,
        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 spatial_cluster_split(df, umap_coords, valid_indices, n_regions):
    """
    Performs spatial KMeans clustering directly on UMAP 2D coordinates.
    Each KMeans cluster becomes one fold - simple 1:1 mapping.
    Creates visually consistent and chemically meaningful regions.
    """
    print("=" * 65)
    print("Performing Spatial KMeans Clustering on 2D UMAP Coordinates")
    print("=" * 65)
    
    print(f"\nRunning KMeans with k={n_regions} on 2D UMAP coordinates...")
    km = KMeans(n_clusters=n_regions, random_state=RANDOM_SEED, n_init=20)
    labels = km.fit_predict(umap_coords)
    
    print(f"\nCluster centroids in 2D UMAP space:")
    for i, centroid in enumerate(km.cluster_centers_):
        print(f"  Region {i+1}: ({centroid[0]:.2f}, {centroid[1]:.2f})")
    
    folds = defaultdict(list)
    for local_idx, global_idx in enumerate(valid_indices):
        region = labels[local_idx]
        folds[region].append(global_idx)
    
    total = len(df)
    print("\nRegion Summary:")
    for r in sorted(folds.keys()):
        n = len(folds[r])
        p = 100 * n / total
        print(f"Region {r+1}: {n:,} compounds ({p:.2f}%)")
    
    return folds, labels


def save_cluster_assignments(df, folds, cluster_labels, umap_coords, valid_idx, output_dir):
    """
    Saves cluster assignments with UMAP coordinates to CSV.
    Format: compound,cluster,fold,umap_x,umap_y
    """
    print("\nSaving cluster assignments...")
    fig_dir = os.path.join(output_dir, "figures")
    os.makedirs(fig_dir, exist_ok=True)
    
    assignments = []
    for fold_id, indices in folds.items():
        for global_idx in indices:
            if global_idx in valid_idx:
                local_idx = valid_idx.index(global_idx)
                compound_smiles = df.loc[global_idx, 'compound']
                cluster = int(cluster_labels[local_idx])
                fold = fold_id + 1
                umap_x = umap_coords[local_idx, 0]
                umap_y = umap_coords[local_idx, 1]
                
                assignments.append({
                    'compound': compound_smiles,
                    'cluster': cluster,
                    'fold': fold,
                    'umap_x': umap_x,
                    'umap_y': umap_y
                })
    
    assignments_df = pd.DataFrame(assignments)
    output_file = os.path.join(fig_dir, "cluster_assignments.csv")
    assignments_df.to_csv(output_file, index=False)
    print(f"Saved figures/cluster_assignments.csv: {len(assignments_df):,} entries")


def visualize_lambda_max(df, folds, output_dir):
    """
    Plots λmax distributions across regions.
    """
    if "lambda_max" not in df.columns:
        return
    print("\nGenerating λmax distribution plot...")
    os.makedirs(output_dir, exist_ok=True)

    fig_dir = os.path.join(output_dir, "figures")
    os.makedirs(fig_dir, exist_ok=True)

    plt.figure(figsize=(12, 6))
    colors = sns.color_palette("husl", len(folds))

    for i, (r, idxs) in enumerate(sorted(folds.items())):
        region_df = df.loc[idxs]
        sns.kdeplot(
            data=region_df,
            x="lambda_max",
            label=f"Cluster {r+1} (n={len(region_df):,})",
            linewidth=2.2,
            color=colors[i],
        )

    sns.kdeplot(
        data=df,
        x="lambda_max",
        label=f"Overall (n={len(df):,})",
        linewidth=2.0,
        linestyle="--",
        color="black",
        alpha=0.7,
    )

    plt.title("Lambda Max Distribution Across Cluster Splits", fontsize=14, fontweight="bold")
    plt.xlabel("λmax (nm)", fontsize=12, fontweight="bold")
    plt.ylabel("Density", fontsize=12, fontweight="bold")
    plt.legend(frameon=True, shadow=True)
    plt.tight_layout()
    plt.savefig(os.path.join(fig_dir, "cluster_lmax.png"), dpi=300)
    plt.close()
    print("Saved figures/cluster_lmax.png")


def visualize_umap(umap_coords, valid_idx, folds, output_dir):
    """
    Generates 2D UMAP of chemical space colored by region.
    """
    print("\nGenerating UMAP visualization...")
    os.makedirs(output_dir, exist_ok=True)

    colors = sns.color_palette("husl", len(folds))
    plt.figure(figsize=(12, 10))
    for i, (r, idxs) in enumerate(sorted(folds.items())):
        local_idx = [j for j, g in enumerate(valid_idx) if g in idxs]
        label = f"Cluster {r+1} (n={len(local_idx):,})"
        plt.scatter(
            umap_coords[local_idx, 0],
            umap_coords[local_idx, 1],
            s=10,
            alpha=0.6,
            label=label,
            color=colors[i],
        )

    plt.title(
        "UMAP Projection of Compound Space (Colored by Cluster Split)",
        fontsize=14,
        fontweight="bold",
    )


    plt.legend(markerscale=2, frameon=True, loc='best')
    plt.tight_layout()
    os.makedirs(os.path.join(output_dir, "figures"), exist_ok=True)
    plt.savefig(os.path.join(output_dir, "figures/cluster_umap.png"), dpi=300)
    plt.close()
    print("Saved figures/cluster_umap.png")


# ===== Main ===== #


def main():
    """
    Main function to perform spatial cluster splitting.
    """
    print("=" * 65)
    print("SPATIAL CLUSTER SPLITTING PIPELINE")
    print("=" * 65)
    print(f"Configuration:")
    print(f"- Number of regions: {N_REGIONS}")
    print(f"- Clustering dimension: 2D (UMAP coordinates)")
    print(f"- Random seed: {RANDOM_SEED}")
    print(f"- Input: {INPUT_CSV}")
    print(f"- Output: {OUTPUT_DIR}")
    print()
    
    print("Loading dataset...")
    df = pd.read_csv(INPUT_CSV)
    print(f"Loaded {len(df):,} rows.")
    
    fps_array, valid_idx = compute_fingerprints(df)
    
    umap_coords = compute_umap_embedding(fps_array)
    
    folds, cluster_labels = spatial_cluster_split(
        df, umap_coords, valid_idx, N_REGIONS
    )
    
    print("\nSaving cluster CSV files...")
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    for r, idxs in folds.items():
        output_path = os.path.join(OUTPUT_DIR, f"cluster_{r+1}.csv")
        df.loc[idxs].to_csv(output_path, index=False)
        print(f"  Saved cluster_{r+1}.csv")
    
    save_cluster_assignments(df, folds, cluster_labels, umap_coords, valid_idx, OUTPUT_DIR)
    
    visualize_lambda_max(df, folds, OUTPUT_DIR)
    visualize_umap(umap_coords, valid_idx, folds, OUTPUT_DIR)
    
    print("\n" + "=" * 65)
    print("CLUSTERING COMPLETE!")
    print("=" * 65)
    print(f"Output directory: {OUTPUT_DIR}")
    print(f"- {len(folds)} region CSV files")
    print(f"- figures/cluster_assignments.csv")
    print(f"- figures/cluster_lmax.png")
    print(f"- figures/cluster_umap.png")
    print()
    print("Note: Clustering performed in 2D UMAP space for visual consistency")


if __name__ == "__main__":
    main()