File size: 10,728 Bytes
2d60d37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import numpy as np
import requests
import time
import json
from pathlib import Path
import matplotlib.pyplot as plt
from sklearn.metrics import (roc_auc_score, average_precision_score,
                             roc_curve, precision_recall_curve)
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import torch
import torch.nn as nn
import warnings
warnings.filterwarnings('ignore')

BASE_PATH = Path('/content/IDP')
PATHS = {
    'features':   BASE_PATH / 'features',
    'embeddings': BASE_PATH / 'embeddings',
    'benchmark':  BASE_PATH / 'results' / 'benchmark',
    'figures':    BASE_PATH / 'results' / 'figures',
}
PATHS['benchmark'].mkdir(parents=True, exist_ok=True)
PATHS['figures'].mkdir(parents=True, exist_ok=True)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

df = pd.read_parquet(PATHS['features'] / 'features_classical_full.parquet')
id_cols = ['mutation_idx', 'uniprot_acc', 'gene_symbol', 'position',
           'wt_aa', 'mut_aa', 'label']
feature_cols = [c for c in df.columns if c not in id_cols]
X_features = np.nan_to_num(df[feature_cols].values.astype(np.float32),
                           nan=0.0, posinf=0.0, neginf=0.0)
X_emb_raw  = np.load(PATHS['embeddings'] / 'embeddings_combined_full.npy').astype(np.float32)
y          = df['label'].values
proteins   = df['uniprot_acc'].values

print(f"   Variants: {len(df)}  |  Proteins: {df['uniprot_acc'].nunique()}")


PP_SIFT_CACHE = PATHS['benchmark'] / 'polyphen_sift_filtered.parquet'

if PP_SIFT_CACHE.exists():
    print("   ✓ PolyPhen-2/SIFT cache found — loading")
    df_pp_sift = pd.read_parquet(PP_SIFT_CACHE)

else:

    our_variants = {}
    for _, row in df.iterrows():
        acc  = row['uniprot_acc'].split('-')[0]
        key  = (acc, int(row['position']) + 1, row['wt_aa'], row['mut_aa'])
        our_variants[key] = row['uniprot_acc']

    print(f"   Lookup: {len(our_variants)} variants across "
          f"{df['uniprot_acc'].nunique()} proteins\n")

    session  = requests.Session()
    session.headers.update({
        "Accept":     "application/json",
        "User-Agent": "research-query/1.0"
    })

    collected = []
    unique_accs = df['uniprot_acc'].unique()

    PARTIAL = PATHS['benchmark'] / 'pp_sift_partial.parquet'
    if PARTIAL.exists():
        done_df   = pd.read_parquet(PARTIAL)
        done_accs = set(done_df['uniprot_acc'].str.split('-').str[0])
        print(f"   Resuming — {len(done_accs)} proteins already fetched, "
              f"{done_df['polyphen2_score'].notna().sum()} PP2 hits so far")
        collected = done_df.to_dict('records')
    else:
        done_accs = set()

    todo_accs = [a for a in unique_accs if a.split('-')[0] not in done_accs]
    print(f"   Fetching {len(todo_accs)} proteins from UniProt variation API …")

    for i, acc in enumerate(todo_accs):
        acc_bare = acc.split('-')[0]
        url = f"https://www.ebi.ac.uk/proteins/api/variation/{acc_bare}"

        pp2_hits = sift_hits = 0
        for attempt in range(4):
            try:
                r = session.get(url, timeout=30)
                if r.status_code == 200:
                    data = r.json()
                    for feat in data.get('features', []):

                        if feat.get('type') != 'VARIANT':
                            continue

                        pos_begin = feat.get('begin')
                        wt_aa     = feat.get('wildType', '')
                        mut_aa    = feat.get('alternativeSequence', '')

                        if not pos_begin or not wt_aa or not mut_aa:
                            continue
                        if len(wt_aa) != 1 or len(mut_aa) != 1:
                            continue

                        try:
                            pos_1 = int(pos_begin)
                        except (ValueError, TypeError):
                            continue

                        key = (acc_bare, pos_1, wt_aa, mut_aa)
                        if key not in our_variants:
                            continue


                        pp2_score  = None
                        sift_score = None
                        for pred in feat.get('predictions', []):
                            algo = pred.get('predAlgorithmNameType', '')
                            score = pred.get('score')
                            if score is None:
                                continue
                            if 'PolyPhen' in algo or 'polyphen' in algo.lower():
                                pp2_score = float(score)
                                pp2_hits += 1
                            elif 'SIFT' in algo or 'sift' in algo.lower():
                                sift_score = float(score)
                                sift_hits += 1

                        collected.append({
                            'uniprot_acc':     our_variants[key],
                            'position':        pos_1 - 1,
                            'wt_aa':           wt_aa,
                            'mut_aa':          mut_aa,
                            'polyphen2_score': pp2_score,
                            'sift_score':      sift_score,
                        })
                    break

                elif r.status_code == 404:
                    break
                elif r.status_code == 429:
                    time.sleep(5 * (attempt + 1))
                else:
                    time.sleep(2 ** attempt)

            except requests.exceptions.Timeout:
                time.sleep(3)
            except Exception as e:
                time.sleep(2)

        time.sleep(0.2)

        if (i + 1) % 50 == 0:
            partial_df = pd.DataFrame(collected).drop_duplicates(
                subset=['uniprot_acc', 'position', 'wt_aa', 'mut_aa'])
            partial_df.to_parquet(PARTIAL, index=False)
            n_pp   = partial_df['polyphen2_score'].notna().sum()
            n_sift = partial_df['sift_score'].notna().sum()
            print(f"   … {i+1}/{len(todo_accs)} proteins | "
                  f"variants matched: {len(partial_df)} | "
                  f"PP2: {n_pp} | SIFT: {n_sift}")

    df_pp_sift = pd.DataFrame(collected).drop_duplicates(
        subset=['uniprot_acc', 'position', 'wt_aa', 'mut_aa'])
    df_pp_sift.to_parquet(PP_SIFT_CACHE, index=False)
    print(f"\n    Matched variants: {len(df_pp_sift)}")
    print(f"    PolyPhen-2:       {df_pp_sift['polyphen2_score'].notna().sum()}")
    print(f"    SIFT:             {df_pp_sift['sift_score'].notna().sum()}")


print("\n" + "=" * 60)
print(" MERGING SCORES")
print("=" * 60)

df_am = pd.read_parquet(PATHS['benchmark'] / 'alphamissense_filtered.parquet')

df_bench = df[id_cols].copy()
df_bench = df_bench.merge(
    df_am[['uniprot_acc','position','wt_aa','mut_aa','am_pathogenicity']],
    on=['uniprot_acc','position','wt_aa','mut_aa'], how='left')
df_bench = df_bench.merge(
    df_pp_sift[['uniprot_acc','position','wt_aa','mut_aa',
                'polyphen2_score','sift_score']],
    on=['uniprot_acc','position','wt_aa','mut_aa'], how='left')

df_bench['sift_score_inv'] = 1 - df_bench['sift_score']

print(f"   AlphaMissense: {df_bench['am_pathogenicity'].notna().sum()} "
      f"({100*df_bench['am_pathogenicity'].notna().mean():.1f}%)")
print(f"   PolyPhen-2:    {df_bench['polyphen2_score'].notna().sum()} "
      f"({100*df_bench['polyphen2_score'].notna().mean():.1f}%)")
print(f"   SIFT:          {df_bench['sift_score_inv'].notna().sum()} "
      f"({100*df_bench['sift_score_inv'].notna().mean():.1f}%)")

df_bench.to_parquet(PATHS['benchmark'] / 'benchmark_merged.parquet', index=False)

class SimpleMLP(nn.Module):
    def __init__(self, d, h=256):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(d,h), nn.ReLU(), nn.Dropout(0.3),
            nn.Linear(h,h//2), nn.ReLU(), nn.Dropout(0.2),
            nn.Linear(h//2,1), nn.Sigmoid())
    def forward(self, x): return self.net(x).squeeze()

def prepare(Xf, Xe, tr, te, n=128):
    sf = StandardScaler()
    Xf_tr = sf.fit_transform(Xf[tr]); Xf_te = sf.transform(Xf[te])
    pca = PCA(n_components=min(n, Xe[tr].shape[0]-1), random_state=42)
    Xp_tr = pca.fit_transform(Xe[tr]); Xp_te = pca.transform(Xe[te])
    se = StandardScaler()
    Xe_tr = se.fit_transform(Xp_tr); Xe_te = se.transform(Xp_te)
    return (np.c_[Xf_tr,Xe_tr].astype(np.float32),
            np.c_[Xf_te,Xe_te].astype(np.float32))

def train_pred(Xtr, ytr, Xte, epochs=50):
    m = SimpleMLP(Xtr.shape[1]).to(device)
    opt = torch.optim.Adam(m.parameters(), lr=0.001, weight_decay=1e-4)
    crit = nn.BCELoss()
    Xt = torch.FloatTensor(Xtr).to(device)
    yt = torch.FloatTensor(ytr).to(device)
    Xv = torch.FloatTensor(Xte).to(device)
    m.train()
    for _ in range(epochs):
        opt.zero_grad(); crit(m(Xt), yt).backward(); opt.step()
    m.eval()
    with torch.no_grad(): return m(Xv).cpu().numpy()

OUR_CACHE = PATHS['benchmark'] / 'our_model_lpocv_preds.npy'
if OUR_CACHE.exists():
    print("\n   ✓ Model predictions cache found")
    our_preds = np.load(OUR_CACHE)
else:
    our_preds = np.full(len(df), np.nan)
    ups = np.unique(proteins)
    print(f"\n   Running LPOCV ({len(ups)} proteins) …")
    for i, p in enumerate(ups):
        te = proteins == p; tr = ~te
        if te.sum() < 2 or tr.sum() < 10: continue
        Xtr, Xte = prepare(X_features, X_emb_raw, tr, te)
        our_preds[te] = train_pred(Xtr, y[tr], Xte)
        if i % 50 == 0: print(f"   … {i}/{len(ups)} proteins")
    np.save(OUR_CACHE, our_preds)
    print("    Saved")

df_bench['our_score'] = our_preds


tools = {
    'Our model (MLP + ESM-2)': 'our_score',
    'AlphaMissense':           'am_pathogenicity',
    'PolyPhen-2':              'polyphen2_score',
    'SIFT (inverted)':         'sift_score_inv',
}
results = {}
for name, col in tools.items():
    mask = df_bench[col].notna() & df_bench['our_score'].notna()
    sub  = df_bench[mask]
    if len(sub) < 50:
        print(f"   ⚠ {name}: only {len(sub)} variants — skipping")
        continue
    results[name] = {
        'auc_roc': roc_auc_score(sub['label'], sub[col]),
        'auc_pr':  average_precision_score(sub['label'], sub[col]),
        'n': len(sub), 'col': col, 'mask': mask}
    print(f"   {name:<35} n={len(sub):>6,}  "
          f"AUC-ROC={results[name]['auc_roc']:.3f}  "
          f"AUC-PR={results[name]['auc_pr']:.3f}")