HarriziSaad commited on
Commit
2d60d37
·
verified ·
1 Parent(s): f07511a

Upload models_comparaison.py

Browse files
Files changed (1) hide show
  1. scripts/models_comparaison.py +268 -0
scripts/models_comparaison.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import requests
4
+ import time
5
+ import json
6
+ from pathlib import Path
7
+ import matplotlib.pyplot as plt
8
+ from sklearn.metrics import (roc_auc_score, average_precision_score,
9
+ roc_curve, precision_recall_curve)
10
+ from sklearn.preprocessing import StandardScaler
11
+ from sklearn.decomposition import PCA
12
+ import torch
13
+ import torch.nn as nn
14
+ import warnings
15
+ warnings.filterwarnings('ignore')
16
+
17
+ BASE_PATH = Path('/content/IDP')
18
+ PATHS = {
19
+ 'features': BASE_PATH / 'features',
20
+ 'embeddings': BASE_PATH / 'embeddings',
21
+ 'benchmark': BASE_PATH / 'results' / 'benchmark',
22
+ 'figures': BASE_PATH / 'results' / 'figures',
23
+ }
24
+ PATHS['benchmark'].mkdir(parents=True, exist_ok=True)
25
+ PATHS['figures'].mkdir(parents=True, exist_ok=True)
26
+
27
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
28
+
29
+ df = pd.read_parquet(PATHS['features'] / 'features_classical_full.parquet')
30
+ id_cols = ['mutation_idx', 'uniprot_acc', 'gene_symbol', 'position',
31
+ 'wt_aa', 'mut_aa', 'label']
32
+ feature_cols = [c for c in df.columns if c not in id_cols]
33
+ X_features = np.nan_to_num(df[feature_cols].values.astype(np.float32),
34
+ nan=0.0, posinf=0.0, neginf=0.0)
35
+ X_emb_raw = np.load(PATHS['embeddings'] / 'embeddings_combined_full.npy').astype(np.float32)
36
+ y = df['label'].values
37
+ proteins = df['uniprot_acc'].values
38
+
39
+ print(f" Variants: {len(df)} | Proteins: {df['uniprot_acc'].nunique()}")
40
+
41
+
42
+ PP_SIFT_CACHE = PATHS['benchmark'] / 'polyphen_sift_filtered.parquet'
43
+
44
+ if PP_SIFT_CACHE.exists():
45
+ print(" ✓ PolyPhen-2/SIFT cache found — loading")
46
+ df_pp_sift = pd.read_parquet(PP_SIFT_CACHE)
47
+
48
+ else:
49
+
50
+ our_variants = {}
51
+ for _, row in df.iterrows():
52
+ acc = row['uniprot_acc'].split('-')[0]
53
+ key = (acc, int(row['position']) + 1, row['wt_aa'], row['mut_aa'])
54
+ our_variants[key] = row['uniprot_acc']
55
+
56
+ print(f" Lookup: {len(our_variants)} variants across "
57
+ f"{df['uniprot_acc'].nunique()} proteins\n")
58
+
59
+ session = requests.Session()
60
+ session.headers.update({
61
+ "Accept": "application/json",
62
+ "User-Agent": "research-query/1.0"
63
+ })
64
+
65
+ collected = []
66
+ unique_accs = df['uniprot_acc'].unique()
67
+
68
+ PARTIAL = PATHS['benchmark'] / 'pp_sift_partial.parquet'
69
+ if PARTIAL.exists():
70
+ done_df = pd.read_parquet(PARTIAL)
71
+ done_accs = set(done_df['uniprot_acc'].str.split('-').str[0])
72
+ print(f" Resuming — {len(done_accs)} proteins already fetched, "
73
+ f"{done_df['polyphen2_score'].notna().sum()} PP2 hits so far")
74
+ collected = done_df.to_dict('records')
75
+ else:
76
+ done_accs = set()
77
+
78
+ todo_accs = [a for a in unique_accs if a.split('-')[0] not in done_accs]
79
+ print(f" Fetching {len(todo_accs)} proteins from UniProt variation API …")
80
+
81
+ for i, acc in enumerate(todo_accs):
82
+ acc_bare = acc.split('-')[0]
83
+ url = f"https://www.ebi.ac.uk/proteins/api/variation/{acc_bare}"
84
+
85
+ pp2_hits = sift_hits = 0
86
+ for attempt in range(4):
87
+ try:
88
+ r = session.get(url, timeout=30)
89
+ if r.status_code == 200:
90
+ data = r.json()
91
+ for feat in data.get('features', []):
92
+
93
+ if feat.get('type') != 'VARIANT':
94
+ continue
95
+
96
+ pos_begin = feat.get('begin')
97
+ wt_aa = feat.get('wildType', '')
98
+ mut_aa = feat.get('alternativeSequence', '')
99
+
100
+ if not pos_begin or not wt_aa or not mut_aa:
101
+ continue
102
+ if len(wt_aa) != 1 or len(mut_aa) != 1:
103
+ continue
104
+
105
+ try:
106
+ pos_1 = int(pos_begin)
107
+ except (ValueError, TypeError):
108
+ continue
109
+
110
+ key = (acc_bare, pos_1, wt_aa, mut_aa)
111
+ if key not in our_variants:
112
+ continue
113
+
114
+
115
+ pp2_score = None
116
+ sift_score = None
117
+ for pred in feat.get('predictions', []):
118
+ algo = pred.get('predAlgorithmNameType', '')
119
+ score = pred.get('score')
120
+ if score is None:
121
+ continue
122
+ if 'PolyPhen' in algo or 'polyphen' in algo.lower():
123
+ pp2_score = float(score)
124
+ pp2_hits += 1
125
+ elif 'SIFT' in algo or 'sift' in algo.lower():
126
+ sift_score = float(score)
127
+ sift_hits += 1
128
+
129
+ collected.append({
130
+ 'uniprot_acc': our_variants[key],
131
+ 'position': pos_1 - 1,
132
+ 'wt_aa': wt_aa,
133
+ 'mut_aa': mut_aa,
134
+ 'polyphen2_score': pp2_score,
135
+ 'sift_score': sift_score,
136
+ })
137
+ break
138
+
139
+ elif r.status_code == 404:
140
+ break
141
+ elif r.status_code == 429:
142
+ time.sleep(5 * (attempt + 1))
143
+ else:
144
+ time.sleep(2 ** attempt)
145
+
146
+ except requests.exceptions.Timeout:
147
+ time.sleep(3)
148
+ except Exception as e:
149
+ time.sleep(2)
150
+
151
+ time.sleep(0.2)
152
+
153
+ if (i + 1) % 50 == 0:
154
+ partial_df = pd.DataFrame(collected).drop_duplicates(
155
+ subset=['uniprot_acc', 'position', 'wt_aa', 'mut_aa'])
156
+ partial_df.to_parquet(PARTIAL, index=False)
157
+ n_pp = partial_df['polyphen2_score'].notna().sum()
158
+ n_sift = partial_df['sift_score'].notna().sum()
159
+ print(f" … {i+1}/{len(todo_accs)} proteins | "
160
+ f"variants matched: {len(partial_df)} | "
161
+ f"PP2: {n_pp} | SIFT: {n_sift}")
162
+
163
+ df_pp_sift = pd.DataFrame(collected).drop_duplicates(
164
+ subset=['uniprot_acc', 'position', 'wt_aa', 'mut_aa'])
165
+ df_pp_sift.to_parquet(PP_SIFT_CACHE, index=False)
166
+ print(f"\n Matched variants: {len(df_pp_sift)}")
167
+ print(f" PolyPhen-2: {df_pp_sift['polyphen2_score'].notna().sum()}")
168
+ print(f" SIFT: {df_pp_sift['sift_score'].notna().sum()}")
169
+
170
+
171
+ print("\n" + "=" * 60)
172
+ print(" MERGING SCORES")
173
+ print("=" * 60)
174
+
175
+ df_am = pd.read_parquet(PATHS['benchmark'] / 'alphamissense_filtered.parquet')
176
+
177
+ df_bench = df[id_cols].copy()
178
+ df_bench = df_bench.merge(
179
+ df_am[['uniprot_acc','position','wt_aa','mut_aa','am_pathogenicity']],
180
+ on=['uniprot_acc','position','wt_aa','mut_aa'], how='left')
181
+ df_bench = df_bench.merge(
182
+ df_pp_sift[['uniprot_acc','position','wt_aa','mut_aa',
183
+ 'polyphen2_score','sift_score']],
184
+ on=['uniprot_acc','position','wt_aa','mut_aa'], how='left')
185
+
186
+ df_bench['sift_score_inv'] = 1 - df_bench['sift_score']
187
+
188
+ print(f" AlphaMissense: {df_bench['am_pathogenicity'].notna().sum()} "
189
+ f"({100*df_bench['am_pathogenicity'].notna().mean():.1f}%)")
190
+ print(f" PolyPhen-2: {df_bench['polyphen2_score'].notna().sum()} "
191
+ f"({100*df_bench['polyphen2_score'].notna().mean():.1f}%)")
192
+ print(f" SIFT: {df_bench['sift_score_inv'].notna().sum()} "
193
+ f"({100*df_bench['sift_score_inv'].notna().mean():.1f}%)")
194
+
195
+ df_bench.to_parquet(PATHS['benchmark'] / 'benchmark_merged.parquet', index=False)
196
+
197
+ class SimpleMLP(nn.Module):
198
+ def __init__(self, d, h=256):
199
+ super().__init__()
200
+ self.net = nn.Sequential(
201
+ nn.Linear(d,h), nn.ReLU(), nn.Dropout(0.3),
202
+ nn.Linear(h,h//2), nn.ReLU(), nn.Dropout(0.2),
203
+ nn.Linear(h//2,1), nn.Sigmoid())
204
+ def forward(self, x): return self.net(x).squeeze()
205
+
206
+ def prepare(Xf, Xe, tr, te, n=128):
207
+ sf = StandardScaler()
208
+ Xf_tr = sf.fit_transform(Xf[tr]); Xf_te = sf.transform(Xf[te])
209
+ pca = PCA(n_components=min(n, Xe[tr].shape[0]-1), random_state=42)
210
+ Xp_tr = pca.fit_transform(Xe[tr]); Xp_te = pca.transform(Xe[te])
211
+ se = StandardScaler()
212
+ Xe_tr = se.fit_transform(Xp_tr); Xe_te = se.transform(Xp_te)
213
+ return (np.c_[Xf_tr,Xe_tr].astype(np.float32),
214
+ np.c_[Xf_te,Xe_te].astype(np.float32))
215
+
216
+ def train_pred(Xtr, ytr, Xte, epochs=50):
217
+ m = SimpleMLP(Xtr.shape[1]).to(device)
218
+ opt = torch.optim.Adam(m.parameters(), lr=0.001, weight_decay=1e-4)
219
+ crit = nn.BCELoss()
220
+ Xt = torch.FloatTensor(Xtr).to(device)
221
+ yt = torch.FloatTensor(ytr).to(device)
222
+ Xv = torch.FloatTensor(Xte).to(device)
223
+ m.train()
224
+ for _ in range(epochs):
225
+ opt.zero_grad(); crit(m(Xt), yt).backward(); opt.step()
226
+ m.eval()
227
+ with torch.no_grad(): return m(Xv).cpu().numpy()
228
+
229
+ OUR_CACHE = PATHS['benchmark'] / 'our_model_lpocv_preds.npy'
230
+ if OUR_CACHE.exists():
231
+ print("\n ✓ Model predictions cache found")
232
+ our_preds = np.load(OUR_CACHE)
233
+ else:
234
+ our_preds = np.full(len(df), np.nan)
235
+ ups = np.unique(proteins)
236
+ print(f"\n Running LPOCV ({len(ups)} proteins) …")
237
+ for i, p in enumerate(ups):
238
+ te = proteins == p; tr = ~te
239
+ if te.sum() < 2 or tr.sum() < 10: continue
240
+ Xtr, Xte = prepare(X_features, X_emb_raw, tr, te)
241
+ our_preds[te] = train_pred(Xtr, y[tr], Xte)
242
+ if i % 50 == 0: print(f" … {i}/{len(ups)} proteins")
243
+ np.save(OUR_CACHE, our_preds)
244
+ print(" Saved")
245
+
246
+ df_bench['our_score'] = our_preds
247
+
248
+
249
+ tools = {
250
+ 'Our model (MLP + ESM-2)': 'our_score',
251
+ 'AlphaMissense': 'am_pathogenicity',
252
+ 'PolyPhen-2': 'polyphen2_score',
253
+ 'SIFT (inverted)': 'sift_score_inv',
254
+ }
255
+ results = {}
256
+ for name, col in tools.items():
257
+ mask = df_bench[col].notna() & df_bench['our_score'].notna()
258
+ sub = df_bench[mask]
259
+ if len(sub) < 50:
260
+ print(f" ⚠ {name}: only {len(sub)} variants — skipping")
261
+ continue
262
+ results[name] = {
263
+ 'auc_roc': roc_auc_score(sub['label'], sub[col]),
264
+ 'auc_pr': average_precision_score(sub['label'], sub[col]),
265
+ 'n': len(sub), 'col': col, 'mask': mask}
266
+ print(f" {name:<35} n={len(sub):>6,} "
267
+ f"AUC-ROC={results[name]['auc_roc']:.3f} "
268
+ f"AUC-PR={results[name]['auc_pr']:.3f}")