File size: 13,244 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
#!/usr/bin/env python3
"""
method_split.py

Author: natelgrw
Last Edited: 11/04/2025

Splits the ReTiNA dataset into 5 folds based on LC-MS setup configurations 
(e.g., solvents, gradient, column, temperature, flow rate).
Each setup group is assigned to a single fold to avoid data leakage 
across similar chromatographic conditions.
"""

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
import umap
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.cluster import KMeans
from ast import literal_eval


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


INPUT_CSV = "../retina_dataset.csv"
METHOD_CSV = "../lcms_methods.csv"
OUTPUT_DIR = "../method_split"
N_FOLDS = 5
RANDOM_SEED = 42

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


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


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")
    if 'method_number' in df.columns:
        print(f"Unique methods: {df['method_number'].nunique():,}")
    print()


def assign_methods_to_folds(method_sizes, n_folds, method_features=None, method_ids=None):
    """
    Assigns methods to folds using KMeans clustering on UMAP coordinates.
    This creates compact, spatially-separated regions in the UMAP visualization.
    """
    fold_assignments = defaultdict(list)
    fold_counts = [0] * n_folds

    if method_features is not None and method_ids is not None:
        print(f"\nUsing KMeans to create {n_folds} spatially-separated regions...")
        
        kmeans = KMeans(n_clusters=n_folds, random_state=RANDOM_SEED, n_init=20)
        cluster_labels = kmeans.fit_predict(method_features)
        
        cluster_to_methods = defaultdict(list)
        for method_id, cluster_id in zip(method_ids, cluster_labels):
            cluster_to_methods[cluster_id].append(method_id)
        
        cluster_sizes = {}
        for cluster_id, methods in cluster_to_methods.items():
            cluster_sizes[cluster_id] = sum(method_sizes[m] for m in methods)
        
        total_size = sum(method_sizes.values())
        avg_size = total_size / n_folds
        
        print(f"Target size per fold: {avg_size:,.0f} datapoints")
        
        for cluster_id, methods in cluster_to_methods.items():
            cluster_size = cluster_sizes[cluster_id]
            method_size_list = [(m, method_sizes[m]) for m in methods]
            method_size_list.sort(key=lambda x: x[1], reverse=True)
            
            if len(method_size_list) > 0:
                largest_method, largest_size = method_size_list[0]
                if largest_size > cluster_size * 0.6 and largest_size > avg_size * 0.5:
                    print(f"Warning: Method {largest_method} has {largest_size:,} datapoints "
                          f"({100*largest_size/total_size:.1f}% of total dataset)")
        
        for cluster_id in range(n_folds):
            methods = cluster_to_methods[cluster_id]
            for method in methods:
                fold_assignments[cluster_id].append(method)
                fold_counts[cluster_id] += method_sizes[method]
        
        print("\nSpatial assignment complete!")
        print(f"Largest fold: {max(fold_counts):,} datapoints")
        print(f"Smallest fold: {min(fold_counts):,} datapoints")
        print(f"Fold size ratio: {max(fold_counts)/min(fold_counts):.2f}x")
        
    else:
        print("\nWarning: No method features provided, using greedy assignment")
        sorted_methods = sorted(method_sizes.items(), key=lambda x: x[1], reverse=True)
        for method, size in sorted_methods:
            min_fold = min(range(n_folds), key=lambda i: fold_counts[i])
            fold_assignments[min_fold].append(method)
            fold_counts[min_fold] += size

    return fold_assignments, fold_counts


# ===== Analyzer Class ===== #


class MethodAnalyzer:
    """
    Analyzer for LC-MS setup-based splitting.
    """

    def __init__(self, data_path, method_path, output_dir):
        self.data_path = Path(data_path)
        self.method_path = Path(method_path)
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True, parents=True)
        self.df = None
        self.methods = None

    def load_data(self):
        """
        Loads the datasets.
        """
        print("\nLOADING RETINA + METHOD DATA")
        self.df = pd.read_csv(self.data_path)
        self.methods = pd.read_csv(self.method_path)

        for col in ["gradient", "column"]:
            if col in self.methods.columns:
                self.methods[col] = self.methods[col].apply(lambda x: literal_eval(x) if isinstance(x, str) else x)
        print(f"Loaded {len(self.df):,} datapoints and {len(self.methods):,} methods.")

    def extract_method_features(self):
        """
        Converts LC-MS setups into numerical feature vectors.
        """
        if hasattr(self, 'method_features_X'):
            return self.method_features_X
            
        df = self.methods.copy()
        df["phase"] = df["column"].apply(lambda x: x[0] if isinstance(x, list) else "UNK")
        df["col_diam"] = df["column"].apply(lambda x: float(x[1]) if isinstance(x, list) else 0)
        df["col_len"] = df["column"].apply(lambda x: float(x[2]) if isinstance(x, list) else 0)
        df["col_part"] = df["column"].apply(lambda x: float(x[3]) if isinstance(x, list) else 0)
        df["grad_len"] = df["gradient"].apply(lambda x: x[-1][0] if isinstance(x, list) and len(x) > 0 else 0)
        df["grad_range"] = df["gradient"].apply(
            lambda x: max([p[1] for p in x]) - min([p[1] for p in x]) if isinstance(x, list) and len(x) > 0 else 0
        )

        feat_cols = ["phase", "col_diam", "col_len", "col_part", "grad_len", "grad_range", "flow_rate", "temp"]
        cat_cols = ["phase"]
        num_cols = [c for c in feat_cols if c not in cat_cols]

        preprocessor = ColumnTransformer([
            ("cat", OneHotEncoder(), cat_cols),
            ("num", StandardScaler(), num_cols)
        ])

        X = preprocessor.fit_transform(df[feat_cols])
        df["vector"] = list(X.toarray() if hasattr(X, "toarray") else X)
        print(f"Extracted {X.shape[1]} features per method.")
        self.methods = df
        self.method_features_X = X
        return X

    def create_method_splits(self, n_splits=5):
        """
        Splits the dataset by LC-MS setup groups into folds.
        """
        print("\nCREATING METHOD SPLITS")
        print("=" * 60)

        print("Extracting method features and computing UMAP...")
        X = self.extract_method_features()
        
        # compute UMAP embedding
        reducer = umap.UMAP(
            n_neighbors=8,
            min_dist=0.1,
            metric="euclidean",
            random_state=RANDOM_SEED
        )
        umap_embedding = reducer.fit_transform(X)
        self.methods["umap_x"], self.methods["umap_y"] = umap_embedding[:, 0], umap_embedding[:, 1]
        print("UMAP embedding computed.")
        
        method_ids = self.methods["method_number"].values
        
        method_sizes = self.df["method_number"].value_counts().to_dict()
        print(f"{len(method_sizes):,} unique methods in dataset.")

        fold_assignments, fold_counts = assign_methods_to_folds(
            method_sizes, n_splits, 
            method_features=umap_embedding,
            method_ids=method_ids
        )
        
        print("\nFold balance summary:")
        for i, count in enumerate(fold_counts):
            print(f"  Fold {i+1}: {count:,} datapoints ({100*count/len(self.df):.2f}%)")

        method_to_fold = {}
        for i, methods in fold_assignments.items():
            for m in methods:
                method_to_fold[m] = i + 1

        self.df["fold"] = self.df["method_number"].map(method_to_fold)
        
        self.methods["fold"] = self.methods["method_number"].map(method_to_fold)

        fold_dataframes = {}
        for i in range(n_splits):
            fold_df = self.df[self.df["fold"] == i + 1].copy()
            out_file = self.output_dir / f"methods_{i+1}.csv"
            fold_df.to_csv(out_file, index=False)
            fold_dataframes[i] = fold_df
            print(f"Saved setup_{i+1}.csv ({len(fold_df):,} rows)")

        return fold_dataframes

    def visualize_rt_distributions(self, fold_dataframes):
        """
        Generates a KDE plot of the RT distribution per setup 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"Setup {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 Method 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 / "methods_rt.png", dpi=300, bbox_inches="tight")
        plt.close()
        print(f"Saved RT KDE plot to figures/method_rt.png")

    def generate_umap_plot(self):
        """
        Generates a UMAP visualization plot (embedding already computed).
        """
        print("\nGENERATING UMAP VISUALIZATION")
        
        if "umap_x" not in self.methods.columns or "umap_y" not in self.methods.columns:
            print("Warning: UMAP coordinates not found, computing now...")
            X = self.extract_method_features()
            reducer = umap.UMAP(
                n_neighbors=8,
                min_dist=0.1,
                metric="euclidean",
                random_state=RANDOM_SEED
            )
            embedding = reducer.fit_transform(X)
            self.methods["umap_x"], self.methods["umap_y"] = embedding[:, 0], embedding[:, 1]
        
        plt.figure(figsize=(10, 7))
        
        if "fold" in self.methods.columns:
            colors = sns.color_palette("husl", N_FOLDS)
            for fold_num in sorted(self.methods["fold"].dropna().unique()):
                fold_data = self.methods[self.methods["fold"] == fold_num]
                n_methods = len(fold_data)
                plt.scatter(
                    fold_data["umap_x"], fold_data["umap_y"],
                    label=f"Cluster {int(fold_num)} (n={n_methods} methods)",
                    s=100, alpha=0.7, edgecolor="k", linewidth=0.5,
                    color=colors[int(fold_num) - 1]
                )
            plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=10)
            plt.title("UMAP Projection of LC-MS Method Space (Colored by Method Split)", fontsize=14, pad=15, fontweight='bold')
        else:
            sns.scatterplot(
                x="umap_x", y="umap_y", data=self.methods,
                s=70, color="steelblue", edgecolor="k"
            )
            plt.title("2D UMAP Visualization of LC-MS Method Space", fontsize=14, pad=15)

        plt.tight_layout()

        fig_dir = self.output_dir / "figures"
        fig_dir.mkdir(exist_ok=True)
        plt.savefig(fig_dir / "methods_umap.png", dpi=300, bbox_inches="tight")
        plt.close()
        print(f"Saved UMAP plot to figures/method_umap.png")


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


def main():
    """
    Main execution function.
    """
    print("\n" + "=" * 80)
    print(" " * 30 + "METHOD SPLIT PIPELINE")
    print("=" * 80)

    analyzer = MethodAnalyzer(INPUT_CSV, METHOD_CSV, OUTPUT_DIR)
    analyzer.load_data()
    analyze_dataset(analyzer.df)
    
    fold_dataframes = analyzer.create_method_splits(n_splits=N_FOLDS)
    
    analyzer.generate_umap_plot()
    
    analyzer.visualize_rt_distributions(fold_dataframes)

    print("\n" + "=" * 80)
    print(" " * 30 + "METHOD SPLIT COMPLETE!")
    print("=" * 80)


if __name__ == "__main__":
    main()