a96123155 commited on
Commit
c4bd04f
·
1 Parent(s): 2ec2d5e
Files changed (2) hide show
  1. .DS_Store +0 -0
  2. app.py +0 -519
.DS_Store CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
 
app.py DELETED
@@ -1,519 +0,0 @@
1
- import streamlit as st
2
- from io import StringIO
3
- from Bio import SeqIO
4
-
5
- import numpy as np
6
- import os
7
- import pandas as pd
8
- import random
9
- import torch
10
- import torch.nn as nn
11
- import torch.nn.functional as F
12
- from collections import Counter, OrderedDict
13
- from copy import deepcopy
14
- from esm import Alphabet, FastaBatchedDataset, ProteinBertModel, pretrained, MSATransformer
15
- from esm.data import *
16
- from esm.model.esm2 import ESM2
17
- from torch import nn
18
- from torch.nn import Linear
19
- from torch.nn.utils.rnn import pad_sequence
20
- from torch.utils.data import Dataset, DataLoader
21
- seed = 19961231
22
- random.seed(seed)
23
- np.random.seed(seed)
24
- torch.manual_seed(seed)
25
-
26
-
27
- st.title("IRES-LM prediction and mutation")
28
-
29
- # Input sequence
30
- st.subheader("Input sequence")
31
-
32
- seq = st.text_area("FASTA format only", value=">vir_CVB3_ires_00505.1\nTTAAAACAGCCTGTGGGTTGATCCCACCCACAGGCCCATTGGGCGCTAGCACTCTGGTATCACGGTACCTTTGTGCGCCTGTTTTATACCCCCTCCCCCAACTGTAACTTAGAAGTAACACACACCGATCAACAGTCAGCGTGGCACACCAGCCACGTTTTGATCAAGCACTTCTGTTACCCCGGACTGAGTATCAATAGACTGCTCACGCGGTTGAAGGAGAAAGCGTTCGTTATCCGGCCAACTACTTCGAAAAACCTAGTAACACCGTGGAAGTTGCAGAGTGTTTCGCTCAGCACTACCCCAGTGTAGATCAGGTCGATGAGTCACCGCATTCCCCACGGGCGACCGTGGCGGTGGCTGCGTTGGCGGCCTGCCCATGGGGAAACCCATGGGACGCTCTAATACAGACATGGTGCGAAGAGTCTATTGAGCTAGTTGGTAGTCCTCCGGCCCCTGAATGCGGCTAATCCTAACTGCGGAGCACACACCCTCAAGCCAGAGGGCAGTGTGTCGTAACGGGCAACTCTGCAGCGGAACCGACTACTTTGGGTGTCCGTGTTTCATTTTATTCCTATACTGGCTGCTTATGGTGACAATTGAGAGATCGTTACCATATAGCTATTGGATTGGCCATCCGGTGACTAATAGAGCTATTATATATCCCTTTGTTGGGTTTATACCACTTAGCTTGAAAGAGGTTAAAACATTACAATTCATTGTTAAGTTGAATACAGCAAA")
33
- st.subheader("Upload sequence file")
34
- uploaded = st.file_uploader("Sequence file in FASTA format")
35
-
36
- # augments
37
- global output_filename, start_nt_position, end_nt_position, mut_by_prob, transform_type, mlm_tok_num, n_mut, n_designs_ep, n_sampling_designs_ep, n_mlm_recovery_sampling, mutate2stronger
38
- output_filename = st.text_input("output a .csv file", value='IRES_LM_prediction_mutation')
39
- start_nt_position = st.number_input("The start position of the mutation of this sequence, the first position is defined as 0", value=0)
40
- end_nt_position = st.number_input("The last position of the mutation of this sequence, the last position is defined as length(sequence)-1 or -1", value=-1)
41
- mut_by_prob = st.checkbox("Mutated by predicted Probability or Transformed Probability of the sequence", value=True)
42
- transform_type = st.selectbox("Type of probability transformation",
43
- ['', 'sigmoid', 'logit', 'power_law', 'tanh'],
44
- index=2)
45
- mlm_tok_num = st.number_input("Number of masked tokens for each sequence per epoch", value=1)
46
- n_mut = st.number_input("Maximum number of mutations for each sequence", value=3)
47
- n_designs_ep = st.number_input("Number of mutations per epoch", value=10)
48
- n_sampling_designs_ep = st.number_input("Number of sampling mutations from n_designs_ep per epoch", value=5)
49
- n_mlm_recovery_sampling = st.number_input("Number of MLM recovery samplings (with AGCT recovery)", value=1)
50
- mutate2stronger = st.checkbox("Mutate to stronger IRES variant, otherwise mutate to weaker IRES", value=True)
51
- if not mut_by_prob and transform_type != '':
52
- st.write("--transform_type must be '' when --mut_by_prob is False")
53
- transform_type = ''
54
-
55
- global idx_to_tok, prefix, epochs, layers, heads, fc_node, dropout_prob, embed_dim, batch_toks, repr_layers, evaluation, include, truncate, return_contacts, return_representation, mask_toks_id, finetune
56
-
57
- epochs = 5
58
- layers = 6
59
- heads = 16
60
- embed_dim = 128
61
- batch_toks = 4096
62
- fc_node = 64
63
- dropout_prob = 0.5
64
- folds = 10
65
- repr_layers = [-1]
66
- include = ["mean"]
67
- truncate = True
68
- finetune = False
69
- return_contacts = False
70
- return_representation = False
71
-
72
- global tok_to_idx, idx_to_tok, mask_toks_id
73
- alphabet = Alphabet(mask_prob = 0.15, standard_toks = 'AGCT')
74
- assert alphabet.tok_to_idx == {'<pad>': 0, '<eos>': 1, '<unk>': 2, 'A': 3, 'G': 4, 'C': 5, 'T': 6, '<cls>': 7, '<mask>': 8, '<sep>': 9}
75
-
76
- # tok_to_idx = {'<pad>': 0, '<eos>': 1, '<unk>': 2, 'A': 3, 'G': 4, 'C': 5, 'T': 6, '<cls>': 7, '<mask>': 8, '<sep>': 9}
77
- tok_to_idx = {'-': 0, '&': 1, '?': 2, 'A': 3, 'G': 4, 'C': 5, 'T': 6, '!': 7, '*': 8, '|': 9}
78
- idx_to_tok = {idx: tok for tok, idx in tok_to_idx.items()}
79
- # st.write(tok_to_idx)
80
- mask_toks_id = 8
81
-
82
- global w1, w2, w3
83
- w1, w2, w3 = 1, 1, 100
84
-
85
- class CNN_linear(nn.Module):
86
- def __init__(self):
87
- super(CNN_linear, self).__init__()
88
-
89
- self.esm2 = ESM2(num_layers = layers,
90
- embed_dim = embed_dim,
91
- attention_heads = heads,
92
- alphabet = alphabet)
93
-
94
- self.dropout = nn.Dropout(dropout_prob)
95
- self.relu = nn.ReLU()
96
- self.flatten = nn.Flatten()
97
- self.fc = nn.Linear(in_features = embed_dim, out_features = fc_node)
98
- self.output = nn.Linear(in_features = fc_node, out_features = 2)
99
-
100
- def predict(self, tokens):
101
-
102
- x = self.esm2(tokens, [layers], need_head_weights=False, return_contacts=False, return_representation = True)
103
- x_cls = x["representations"][layers][:, 0]
104
-
105
- o = self.fc(x_cls)
106
- o = self.relu(o)
107
- o = self.dropout(o)
108
- o = self.output(o)
109
-
110
- y_prob = torch.softmax(o, dim = 1)
111
- y_pred = torch.argmax(y_prob, dim = 1)
112
-
113
- if transform_type:
114
- y_prob_transformed = prob_transform(y_prob[:,1])
115
- return y_prob[:,1], y_pred, x['logits'], y_prob_transformed
116
- else:
117
- return y_prob[:,1], y_pred, x['logits'], o[:,1]
118
-
119
- def forward(self, x1, x2):
120
- logit_1, repr_1 = self.predict(x1)
121
- logit_2, repr_2 = self.predict(x2)
122
- return (logit_1, logit_2), (repr_1, repr_2)
123
-
124
-
125
- def prob_transform(prob, **kwargs): # Logits
126
- """
127
- Transforms probability values based on the specified method.
128
-
129
- :param prob: torch.Tensor, the input probabilities to be transformed
130
- :param transform_type: str, the type of transformation to be applied
131
- :param kwargs: additional parameters for transformations
132
- :return: torch.Tensor, transformed probabilities
133
- """
134
-
135
- if transform_type == 'sigmoid':
136
- x0 = kwget('x0', 0.5)
137
- k = kwget('k', 10.0)
138
- prob_transformed = 1 / (1 + torch.exp(-k * (prob - x0)))
139
-
140
- elif transform_type == 'logit':
141
- # Adding a small value to avoid log(0) and log(1)
142
- prob_transformed = torch.log(prob + 1e-6) - torch.log(1 - prob + 1e-6)
143
-
144
- elif transform_type == 'power_law':
145
- gamma = kwget('gamma', 2.0)
146
- prob_transformed = torch.pow(prob, gamma)
147
-
148
- elif transform_type == 'tanh':
149
- k = kwget('k', 2.0)
150
- prob_transformed = torch.tanh(k * prob)
151
-
152
- return prob_transformed
153
-
154
- def random_replace(sequence, continuous_replace=False):
155
- global start_nt_position, end_nt_position
156
- if end_nt_position == -1: end_nt_position = len(sequence)-1
157
- if start_nt_position < 0 or end_nt_position > len(sequence)-1 or start_nt_position > end_nt_position:
158
- # raise ValueError("Invalid start/end positions")
159
- st.write("Invalid start/end positions")
160
- start_nt_position, end_nt_position = 0, len(sequence)-1
161
-
162
- # 将序列切片成三部分:替换区域前、替换区域、替换区域后
163
- pre_segment = sequence[:start_nt_position]
164
- target_segment = list(sequence[start_nt_position:end_nt_position + 1]) # +1因为Python的切片是右开区间
165
- post_segment = sequence[end_nt_position + 1:]
166
-
167
- if not continuous_replace:
168
- # 随机替换目标片段的mlm_tok_num个位置
169
- indices = random.sample(range(len(target_segment)), mlm_tok_num)
170
- for idx in indices:
171
- target_segment[idx] = '*'
172
- else:
173
- # 在目标片段连续替换mlm_tok_num个位置
174
- max_start_idx = len(target_segment) - mlm_tok_num # 确保从i开始的n_mut个元素不会超出目标片段的长度
175
- if max_start_idx < 1: # 如果目标片段长度小于mlm_tok_num,返回原始序列
176
- return target_segment
177
- start_idx = random.randint(0, max_start_idx)
178
- for idx in range(start_idx, start_idx + mlm_tok_num):
179
- target_segment[idx] = '*'
180
-
181
- # 合并并返回最终的序列
182
- return ''.join([pre_segment] + target_segment + [post_segment])
183
-
184
-
185
- def mlm_seq(seq):
186
- seq_token, masked_sequence_token = [7],[7]
187
- seq_token += [tok_to_idx[token] for token in seq]
188
-
189
- masked_seq = random_replace(seq, n_mut) # 随机替换n_mut个元素为'*'
190
- masked_seq_token += [tok_to_idx[token] for token in masked_seq]
191
-
192
- return seq, masked_seq, torch.LongTensor(seq_token), torch.LongTensor(masked_seq_token)
193
-
194
- def batch_mlm_seq(seq_list, continuous_replace = False):
195
- batch_seq = []
196
- batch_masked_seq = []
197
- batch_seq_token_list = []
198
- batch_masked_seq_token_list = []
199
-
200
- for i, seq in enumerate(seq_list):
201
- seq_token, masked_seq_token = [7], [7]
202
- seq_token += [tok_to_idx[token] for token in seq]
203
-
204
- masked_seq = random_replace(seq, continuous_replace) # 随机替换n_mut个元素为'*'
205
- masked_seq_token += [tok_to_idx[token] for token in masked_seq]
206
-
207
- batch_seq.append(seq)
208
- batch_masked_seq.append(masked_seq)
209
-
210
- batch_seq_token_list.append(seq_token)
211
- batch_masked_seq_token_list.append(masked_seq_token)
212
-
213
- return batch_seq, batch_masked_seq, torch.LongTensor(batch_seq_token_list), torch.LongTensor(batch_masked_seq_token_list)
214
-
215
- def recovered_mlm_tokens(masked_seqs, masked_toks, esm_logits, exclude_low_prob = False):
216
- # Only remain the AGCT logits
217
- esm_logits = esm_logits[:,:,3:7]
218
- # Get the predicted tokens using argmax
219
- predicted_toks = (esm_logits.argmax(dim=-1)+3).tolist()
220
-
221
- batch_size, seq_len, vocab_size = esm_logits.size()
222
- if exclude_low_prob: min_prob = 1 / vocab_size
223
- # Initialize an empty list to store the recovered sequences
224
- recovered_sequences, recovered_toks = [], []
225
-
226
- for i in range(batch_size):
227
- recovered_sequence_i, recovered_tok_i = [], []
228
- for j in range(seq_len):
229
- if masked_toks[i][j] == 8:
230
- st.write(i,j)
231
- ### Sample M recovery sequences using the logits
232
- recovery_probs = torch.softmax(esm_logits[i, j], dim=-1)
233
- recovery_probs[predicted_toks[i][j]-3] = 0 # Exclude the most probable token
234
- if exclude_low_prob: recovery_probs[recovery_probs < min_prob] = 0 # Exclude tokens with low probs < min_prob
235
- recovery_probs /= recovery_probs.sum() # Normalize the probabilities
236
-
237
- ### 有放回抽样
238
- max_retries = 5
239
- retries = 0
240
- success = False
241
-
242
- while retries < max_retries and not success:
243
- try:
244
- recovery_indices = list(np.random.choice(vocab_size, size=n_mlm_recovery_sampling, p=recovery_probs.cpu().detach().numpy(), replace=False))
245
- success = True # 设置成功标志
246
- except ValueError as e:
247
- retries += 1
248
- st.write(f"Attempt {retries} failed with error: {e}")
249
- if retries >= max_retries:
250
- st.write("Max retries reached. Skipping this iteration.")
251
-
252
- ### recovery to sequence
253
- if retries < max_retries:
254
- for idx in [predicted_toks[i][j]] + [3+i for i in recovery_indices]:
255
- recovery_seq = deepcopy(list(masked_seqs[i]))
256
- recovery_tok = deepcopy(masked_toks[i])
257
-
258
- recovery_tok[j] = idx
259
- recovery_seq[j-1] = idx_to_tok[idx]
260
-
261
- recovered_tok_i.append(recovery_tok)
262
- recovered_sequence_i.append(''.join(recovery_seq))
263
-
264
- recovered_sequences.extend(recovered_sequence_i)
265
- recovered_toks.extend(recovered_tok_i)
266
- return recovered_sequences, torch.LongTensor(torch.stack(recovered_toks))
267
-
268
- def recovered_mlm_multi_tokens(masked_seqs, masked_toks, esm_logits, exclude_low_prob = False):
269
- # Only remain the AGCT logits
270
- esm_logits = esm_logits[:,:,3:7]
271
- # Get the predicted tokens using argmax
272
- predicted_toks = (esm_logits.argmax(dim=-1)+3).tolist()
273
-
274
- batch_size, seq_len, vocab_size = esm_logits.size()
275
- if exclude_low_prob: min_prob = 1 / vocab_size
276
- # Initialize an empty list to store the recovered sequences
277
- recovered_sequences, recovered_toks = [], []
278
-
279
- for i in range(batch_size):
280
- recovered_sequence_i, recovered_tok_i = [], []
281
- recovered_masked_num = 0
282
- for j in range(seq_len):
283
- if masked_toks[i][j] == 8:
284
- ### Sample M recovery sequences using the logits
285
- recovery_probs = torch.softmax(esm_logits[i, j], dim=-1)
286
- recovery_probs[predicted_toks[i][j]-3] = 0 # Exclude the most probable token
287
- if exclude_low_prob: recovery_probs[recovery_probs < min_prob] = 0 # Exclude tokens with low probs < min_prob
288
- recovery_probs /= recovery_probs.sum() # Normalize the probabilities
289
-
290
- ### 有放回抽样
291
- max_retries = 5
292
- retries = 0
293
- success = False
294
-
295
- while retries < max_retries and not success:
296
- try:
297
- recovery_indices = list(np.random.choice(vocab_size, size=n_mlm_recovery_sampling, p=recovery_probs.cpu().detach().numpy(), replace=False))
298
- success = True # 设置成功标志
299
- except ValueError as e:
300
- retries += 1
301
- st.write(f"Attempt {retries} failed with error: {e}")
302
- if retries >= max_retries:
303
- st.write("Max retries reached. Skipping this iteration.")
304
-
305
- ### recovery to sequence
306
-
307
- if recovered_masked_num == 0:
308
- if retries < max_retries:
309
- for idx in [predicted_toks[i][j]] + [3+i for i in recovery_indices]:
310
- recovery_seq = deepcopy(list(masked_seqs[i]))
311
- recovery_tok = deepcopy(masked_toks[i])
312
-
313
- recovery_tok[j] = idx
314
- recovery_seq[j-1] = idx_to_tok[idx]
315
-
316
- recovered_tok_i.append(recovery_tok)
317
- recovered_sequence_i.append(''.join(recovery_seq))
318
-
319
- elif recovered_masked_num > 0:
320
- if retries < max_retries:
321
- for idx in [predicted_toks[i][j]] + [3+i for i in recovery_indices]:
322
- for recovery_seq, recovery_tok in zip(list(recovered_sequence_i), list(recovered_tok_i)): # 要在循环开始之前获取列表的副本来进行迭代。这样,在循环中即使我们修改了原始的列表,也不会影响迭代的行为。
323
-
324
- recovery_seq_temp = list(recovery_seq)
325
- recovery_tok[j] = idx
326
- recovery_seq_temp[j-1] = idx_to_tok[idx]
327
-
328
- recovered_tok_i.append(recovery_tok)
329
- recovered_sequence_i.append(''.join(recovery_seq_temp))
330
-
331
- recovered_masked_num += 1
332
- recovered_indices = [i for i, s in enumerate(recovered_sequence_i) if '*' not in s]
333
- recovered_tok_i = [recovered_tok_i[i] for i in recovered_indices]
334
- recovered_sequence_i = [recovered_sequence_i[i] for i in recovered_indices]
335
-
336
- recovered_sequences.extend(recovered_sequence_i)
337
- recovered_toks.extend(recovered_tok_i)
338
-
339
- recovered_sequences, recovered_toks = remove_duplicates_double(recovered_sequences, recovered_toks)
340
-
341
- return recovered_sequences, torch.LongTensor(torch.stack(recovered_toks))
342
-
343
- def mismatched_positions(s1, s2):
344
- # 这个函数假定两个字符串的长度相同。
345
- """Return the number of positions where two strings differ."""
346
-
347
- # The number of mismatches will be the sum of positions where characters are not the same
348
- return sum(1 for c1, c2 in zip(s1, s2) if c1 != c2)
349
-
350
- def remove_duplicates_triple(filtered_mut_seqs, filtered_mut_probs, filtered_mut_logits):
351
- seen = {}
352
- unique_seqs = []
353
- unique_probs = []
354
- unique_logits = []
355
-
356
- for seq, prob, logit in zip(filtered_mut_seqs, filtered_mut_probs, filtered_mut_logits):
357
- if seq not in seen:
358
- unique_seqs.append(seq)
359
- unique_probs.append(prob)
360
- unique_logits.append(logit)
361
- seen[seq] = True
362
-
363
- return unique_seqs, unique_probs, unique_logits
364
-
365
- def remove_duplicates_double(filtered_mut_seqs, filtered_mut_probs):
366
- seen = {}
367
- unique_seqs = []
368
- unique_probs = []
369
-
370
- for seq, prob in zip(filtered_mut_seqs, filtered_mut_probs):
371
- if seq not in seen:
372
- unique_seqs.append(seq)
373
- unique_probs.append(prob)
374
- seen[seq] = True
375
-
376
- return unique_seqs, unique_probs
377
-
378
- def mutated_seq(wt_seq, wt_label):
379
- wt_seq = '!'+ wt_seq
380
- wt_tok = torch.LongTensor([[tok_to_idx[token] for token in wt_seq]]).to(device)
381
- wt_prob, wt_pred, _, wt_logit = model.predict(wt_tok)
382
-
383
- st.write(f'Wild Type: Length = {len(wt_seq)} \n{wt_seq}')
384
- st.write(f'Wild Type: Label = {wt_label}, Y_pred = {wt_pred.item()}, Y_prob = {wt_prob.item():.2%}')
385
-
386
- # st.write(n_mut, mlm_tok_num, n_designs_ep, n_sampling_designs_ep, n_mlm_recovery_sampling, mutate2stronger)
387
- # pbar = tqdm(total=n_mut)
388
- mutated_seqs = []
389
- i = 1
390
- # pbar = st.progress(i, text="mutated number of sequence")
391
- while i <= n_mut:
392
- if i == 1: seeds_ep = [wt_seq[1:]]
393
- seeds_next_ep, seeds_probs_next_ep, seeds_logits_next_ep = [], [], []
394
- for seed in seeds_ep:
395
- seed_seq, masked_seed_seq, seed_seq_token, masked_seed_seq_token = batch_mlm_seq([seed] * n_designs_ep, continuous_replace = True) ### mask seed with 1 site to "*"
396
-
397
- seed_prob, seed_pred, _, seed_logit = model.predict(seed_seq_token[0].unsqueeze_(0).to(device))
398
- _, _, seed_esm_logit, _ = model.predict(masked_seed_seq_token.to(device))
399
- mut_seqs, mut_toks = recovered_mlm_multi_tokens(masked_seed_seq, masked_seed_seq_token, seed_esm_logit)
400
- mut_probs, mut_preds, mut_esm_logits, mut_logits = model.predict(mut_toks.to(device))
401
-
402
- ### Filter mut_seqs that mut_prob < seed_prob and mut_prob < wild_prob
403
- filtered_mut_seqs = []
404
- filtered_mut_probs = []
405
- filtered_mut_logits = []
406
- if mut_by_prob:
407
- for z in range(len(mut_seqs)):
408
- if mutate2stronger:
409
- if mut_probs[z] >= seed_prob and mut_probs[z] >= wt_prob:
410
- filtered_mut_seqs.append(mut_seqs[z])
411
- filtered_mut_probs.append(mut_probs[z].cpu().detach().numpy())
412
- filtered_mut_logits.append(mut_logits[z].cpu().detach().numpy())
413
- else:
414
- if mut_probs[z] < seed_prob and mut_probs[z] < wt_prob:
415
- filtered_mut_seqs.append(mut_seqs[z])
416
- filtered_mut_probs.append(mut_probs[z].cpu().detach().numpy())
417
- filtered_mut_logits.append(mut_logits[z].cpu().detach().numpy())
418
- else:
419
- for z in range(len(mut_seqs)):
420
- if mutate2stronger:
421
- if mut_logits[z] >= seed_logit and mut_logits[z] >= wt_logit:
422
- filtered_mut_seqs.append(mut_seqs[z])
423
- filtered_mut_probs.append(mut_probs[z].cpu().detach().numpy())
424
- filtered_mut_logits.append(mut_logits[z].cpu().detach().numpy())
425
- else:
426
- if mut_logits[z] < seed_logit and mut_logits[z] < wt_logit:
427
- filtered_mut_seqs.append(mut_seqs[z])
428
- filtered_mut_probs.append(mut_probs[z].cpu().detach().numpy())
429
- filtered_mut_logits.append(mut_logits[z].cpu().detach().numpy())
430
-
431
-
432
-
433
- ### Save
434
- seeds_next_ep.extend(filtered_mut_seqs)
435
- seeds_probs_next_ep.extend(filtered_mut_probs)
436
- seeds_logits_next_ep.extend(filtered_mut_logits)
437
- seeds_next_ep, seeds_probs_next_ep, seeds_logits_next_ep = remove_duplicates_triple(seeds_next_ep, seeds_probs_next_ep, seeds_logits_next_ep)
438
-
439
- ### Sampling based on prob
440
- if len(seeds_next_ep) > n_sampling_designs_ep:
441
- seeds_probs_next_ep_norm = seeds_probs_next_ep / sum(seeds_probs_next_ep) # Normalize the probabilities
442
- seeds_index_next_ep = np.random.choice(len(seeds_next_ep), n_sampling_designs_ep, p = seeds_probs_next_ep_norm, replace = False)
443
-
444
- seeds_next_ep = np.array(seeds_next_ep)[seeds_index_next_ep]
445
- seeds_probs_next_ep = np.array(seeds_probs_next_ep)[seeds_index_next_ep]
446
- seeds_logits_next_ep = np.array(seeds_logits_next_ep)[seeds_index_next_ep]
447
- seeds_mutated_num_next_ep = [mismatched_positions(wt_seq[1:], s) for s in seeds_next_ep]
448
-
449
- mutated_seqs.extend(list(zip(seeds_next_ep, seeds_logits_next_ep, seeds_probs_next_ep, seeds_mutated_num_next_ep)))
450
-
451
- seeds_ep = seeds_next_ep
452
- i += 1
453
- # pbar.update(1)
454
- # pbar.progress(i/n_mut, text="Mutating")
455
- # pbar.close()
456
- # st.success('Done', icon="✅")
457
- mutated_seqs.extend([(wt_seq[1:], wt_logit.item(), wt_prob.item(), 0)])
458
- mutated_seqs = sorted(mutated_seqs, key=lambda x: x[2], reverse=True)
459
- mutated_seqs = pd.DataFrame(mutated_seqs, columns = ['mutated_seq', 'predicted_logit', 'predicted_probability', 'mutated_num']).drop_duplicates('mutated_seq')
460
- return mutated_seqs
461
-
462
- def read_raw(raw_input):
463
- ids = []
464
- sequences = []
465
-
466
- file = StringIO(raw_input)
467
- for record in SeqIO.parse(file, "fasta"):
468
-
469
- # 检查序列是否只包含A, G, C, T
470
- sequence = str(record.seq.back_transcribe()).upper()
471
- if not set(sequence).issubset(set("AGCT")):
472
- st.write(f"Record '{record.description}' was skipped for containing invalid characters. Only A, G, C, T(U) are allowed.")
473
- continue
474
-
475
- # 将符合条件的序列添加到列表中
476
- ids.append(record.id)
477
- sequences.append(sequence)
478
-
479
- return ids, sequences
480
-
481
- def predict_raw(raw_input):
482
- model.eval()
483
- # st.write('====Parse Input====')
484
- ids, seqs = read_raw(raw_input)
485
-
486
- # st.write('====Predict====')
487
- res_pd = pd.DataFrame(columns = ['mutated_seq', 'predicted_logit', 'predicted_probability', 'mutated_num'])
488
- for wt_seq, wt_id in zip(seqs, ids):
489
- # try:
490
- res = mutated_seq(wt_seq, wt_id)
491
- res_pd = pd.concat([res_pd,res], axis = 0)
492
- # except:
493
- # st.write('====Please Try Again this sequence: ', wt_id, wt_seq)
494
-
495
- st.write(res_pd)
496
- return res_pd
497
-
498
- global model, device
499
- device = "cpu"
500
- state_dict = torch.load('model.pt', map_location=torch.device(device))
501
- new_state_dict = OrderedDict()
502
-
503
- for k, v in state_dict.items():
504
- name = k.replace('module.','')
505
- new_state_dict[name] = v
506
-
507
- model = CNN_linear().to(device)
508
- model.load_state_dict(new_state_dict, strict = False)
509
-
510
- # Run
511
- if st.button("Predict and Mutate"):
512
- if uploaded:
513
- result = predict_raw(uploaded.getvalue().decode())
514
- else:
515
- result = predict_raw(seq)
516
-
517
- result_file = result.to_csv(index=False)
518
- st.download_button("Download", result_file, file_name=output_filename+".csv")
519
- st.dataframe(result)