File size: 4,053 Bytes
70321a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
---
license_name: unknown
license_link: LICENSE
---
import torch
import pandas as pd
import seaborn as sns
import matplotlib.pylab as plt
from mlm import *
import matplotlib.pyplot as plt
from predict import predict

import esm

_, alphabet = esm.pretrained.esm1b_t33_650M_UR50S()

raw_sequence = "SNPYQRGPNPTRSALTTDGPFSVATYSVSRLSVSGFGGGVIYYPTGTTLTFGGIAMSPGYTADASSLAWLGRRLASHGFVVIVINTNSRLDFPDSRASQLSAALNYLRTSSPSAVRARLDANRLAVAGHSMGGGATLRISEQIPTLKAGVPLTPWHTDKTFNTPVPQLIVGAEADTVAPVSQHAIPFYQNLPSTTPKVYVELDNATHFAPNSPNAAISVYTISWMKLWVDNDTRYRQFLCNVNDPALSDFRSNNRHCQ"

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

model = torch.load('./trans_best.pt', map_location=device)

model.eval()

def read_vocab(vocab_file):
    vocab_dict = {}
    with open(vocab_file, 'r') as vocab_file:
        for i, line in enumerate(vocab_file):
            vocab = line.replace("\n", "")
            vocab_dict[vocab] = i
    return vocab_dict

vocab = read_vocab('vocab.txt')

def tokenizer(seq):
    x = torch.zeros(len(seq)+2)
    x[0] = 2
    for i, aa in enumerate(seq):
        w = vocab.get(aa)
        if w:
            x[i+1] = w
        else:
            x[i+1] = 1
    x[-1] = 3
    return x.long()

def check_heatmap():
    inp = tokenizer(raw_sequence).view(1, -1)
    map = []
    for i, w in enumerate(raw_sequence):
        wild = vocab[w]
        inp[0][i] = 4
        with torch.no_grad():
            y = model(inp.to(device))
            map.append(list(y[0].cpu()[i].numpy() - y[0].cpu()[i].numpy()[wild])[5:])
        inp = tokenizer(raw_sequence).view(1, -1)
    return map

map = check_heatmap()

plot_x = []
plot_y = []

for x, y in zip([i for i in range(len(map))], np.array(map).mean(axis=-1)):
    if x+36 < 280: # we remove the unstructured C-terminal
        plot_x.append(x+36)
        plot_y.append(y)

df = pd.DataFrame({'pos':plot_x, 'score':plot_y})
top10 = df.sort_values('score', ascending=False).head(10)

# sns.set_style('white')
# fig, ax = plt.subplots(figsize=(2,3.4))
# sns.lineplot(x=(np.array(plot_x)-36)/(len(plot_x)), y=plot_y, color='grey')
# ax.set_xlim([0,1])
# ax.set_ylim([-2.5,4.5])
# ax.set_yticks(np.arange(8)-2.5)
# ax.set_xticks([0,235/max(plot_x)])
# ax.set_xticklabels([35, 235])
# ax.scatter(x=(top10['pos']-36)/len(plot_x), y=top10['score'], color='brown', zorder=10)
# ax.text(x=0.2,y=-2.2,s='BhrPETase', fontsize=15)

with open("mutations-BhrPETase-new.fasta", 'a') as ofile:
    x = (top10['pos']-36).to_numpy()
    inds = []
    scores = []
    for i in x:
        masked_seq = raw_sequence[:i] + "<mask>" + raw_sequence[i+1:]
        predicted_sequence, predicted_scores, mask_idx = predict(masked_seq)
        predicted_sequence = predicted_sequence[5:-5:]
        res = predicted_sequence[i]
        inds.append(mask_idx)
        scores.append(predicted_scores[4:-4:])
        ofile.write(f"{raw_sequence[i]}{i+1}{res}\n")
        ofile.write(f"{raw_sequence[:i] + res + raw_sequence[i+1:]}\n")
        ofile.write(f"Old: {raw_sequence[i]}\n")
        ofile.write(f"New: {predicted_sequence[i]}\n\n")

    amino_acids = []
    for i in range(len(scores[0])):
        amino_acids.append(alphabet.get_tok(4+i))
    print(np.array(scores[0]).argmax(axis=0))
    # ploting the heatmap of the scores
    fig, ax = plt.subplots(figsize=(8,6))
    sns.heatmap(np.array(scores), cmap='coolwarm', ax=ax, square=True, linewidth=0.5, cbar_kws={"shrink": 0.5})
    # Increase cell size
    ax.set_aspect(1.5)
    # Rename the x_axis labels using the indices of the mutations
    ax.set_yticklabels([f"{i+2} ({raw_sequence[i]})" for i in inds])
    ax.set_xticklabels(amino_acids, rotation=0, ha="right", rotation_mode="anchor")
    ax.set_title("Predicted Scores of Mutations on Top 10 Positions on BhrPETase")
    ax.set_xlabel("Amino Acid Mutations")
    ax.set_ylabel("Position on BhrPETase")
    # Control the size of the color bar
    plt.setp(ax.get_yticklabels(), rotation=0, ha="right",
         rotation_mode="anchor")
    plt.savefig("heatmap-BhrPETase-new.png", dpi=300)
print("DONE!")