-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredict.py
More file actions
182 lines (151 loc) · 5.11 KB
/
Copy pathpredict.py
File metadata and controls
182 lines (151 loc) · 5.11 KB
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
import argparse
import pandas as pd
import torch
import torch.nn as nn
import numpy as np
# =====================
# CONFIG
# =====================
MAX_LEN = 28
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
AA_VOCAB = "ACDEFGHIKLMNPQRSTVWY*"
aa_to_idx = {aa: i for i, aa in enumerate(AA_VOCAB)}
# =====================
# MODEL (UPDATED: 1 OUTPUT)
# =====================
class PeptideTransformer(nn.Module):
def __init__(self, vocab_size, d_model=128, nhead=8, num_layers=4):
super().__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
self.cls_token = nn.Parameter(torch.randn(1, 1, d_model))
self.pos_embedding = nn.Parameter(torch.randn(1, MAX_LEN + 1, d_model))
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model,
nhead=nhead,
dim_feedforward=256,
dropout=0.1,
batch_first=True
)
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers)
# 🔥 single output
self.head = nn.Sequential(
nn.LayerNorm(d_model),
nn.Linear(d_model, 64),
nn.ReLU(),
nn.Linear(64, 1)
)
def forward(self, x):
B = x.size(0)
x = self.embedding(x)
cls = self.cls_token.expand(B, -1, -1)
x = torch.cat([cls, x], dim=1)
x = x + self.pos_embedding[:, :x.size(1), :]
x = self.transformer(x)
return self.head(x[:, 0]).squeeze(-1) # [B]
# =====================
# HELPERS
# =====================
def encode(seq):
return torch.tensor([aa_to_idx[a] for a in seq], dtype=torch.long)
def generate_sat_mut(seq):
mutants = []
L = len(seq)
for i in range(L):
orig_aa = seq[i]
for aa in AA_VOCAB:
if aa == "*" or aa == orig_aa:
continue
mutant = list(seq)
mutant[i] = aa
mutants.append(("".join(mutant), i, aa))
return mutants
def generate_scan_mut(seq, residue):
mutants = [(seq, -1, "WT")]
for i in range(len(seq)):
if seq[i] == residue or seq[i] == "*":
continue
mutant = list(seq)
mutant[i] = residue
mutants.append(("".join(mutant), i, residue))
return mutants
def generate_protein_windows(seq):
windows = []
for i in range(len(seq) - MAX_LEN + 1):
window = seq[i:i+MAX_LEN]
windows.append((window, i))
return windows
# =====================
# ARGPARSE
# =====================
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True, help="CSV: name (col1), sequence (col2)")
parser.add_argument("--mode", default="default",
choices=["default", "sat_mut", "scan_mut", "protein"])
parser.add_argument("--residue", default="A")
args = parser.parse_args()
# =====================
# LOAD MODEL
# =====================
checkpoint = torch.load("peptide_model_epoch50.pt", map_location=DEVICE, weights_only=False)
model = PeptideTransformer(vocab_size=len(AA_VOCAB)).to(DEVICE)
model.load_state_dict(checkpoint["model_state_dict"])
model.eval()
# 🔥 only one scaler now
control_scaler = checkpoint["control_scaler"]
# =====================
# LOAD INPUT
# =====================
df = pd.read_csv(args.input)
names = df.iloc[:, 0].values
sequences = df.iloc[:, 1].values
all_sequences = []
all_names = []
# =====================
# MODE HANDLING
# =====================
for idx, seq in enumerate(sequences):
name = names[idx]
if args.mode == "default":
all_sequences.append(seq)
all_names.append(name)
elif args.mode == "sat_mut":
all_sequences.append(seq)
all_names.append(name + "_WT")
mutants = generate_sat_mut(seq)
for m_seq, pos, aa in mutants:
all_sequences.append(m_seq)
all_names.append(f"{name}_{pos+1}{aa}")
elif args.mode == "scan_mut":
mutants = generate_scan_mut(seq, args.residue)
for m_seq, pos, aa in mutants:
if pos == -1:
all_names.append(name + "_WT")
else:
all_names.append(f"{name}_{pos+1}{aa}")
all_sequences.append(m_seq)
elif args.mode == "protein":
windows = generate_protein_windows(seq)
for window, start in windows:
all_sequences.append(window)
all_names.append(f"{name}_{start+1}")
# =====================
# ENCODE
# =====================
X = torch.stack([encode(seq) for seq in all_sequences]).to(DEVICE)
# =====================
# PREDICT
# =====================
with torch.no_grad():
preds = model(X).cpu().numpy()
# 🔥 inverse scale (single output)
control_pred = control_scaler.inverse_transform(preds.reshape(-1, 1)).flatten()
# =====================
# SAVE OUTPUT
# =====================
out = pd.DataFrame({
"name": all_names,
"sequence": all_sequences,
"pred_controlPSI": control_pred
})
out.to_csv("predict_output.csv", index=False)
print("Saved predict_output.csv")