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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from huggingface_hub import HfApi, ModelFilter
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForMaskedLM
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import re
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
import torch
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import warnings
|
| 9 |
+
warnings.filterwarnings('ignore')
|
| 10 |
+
|
| 11 |
+
MODEL, MODEL_NAME, BATCH_CONVERTER, ALPHABET = None, None, None, None
|
| 12 |
+
OFFSET = 1
|
| 13 |
+
MODELS = [m.modelId for m in HfApi().list_models(filter=ModelFilter(author="facebook", model_name="esm", task="fill-mask"), sort="lastModified", direction=-1)]
|
| 14 |
+
SCORING = ["masked-marginals (more accurate)", "wt-marginals (faster)"]
|
| 15 |
+
|
| 16 |
+
def label_row(row, sequence, token_probs):
|
| 17 |
+
wt, idx, mt = row[0], int(row[1:-1]) - OFFSET, row[-1]
|
| 18 |
+
assert sequence[idx] == wt, "The listed wildtype does not match the provided sequence"
|
| 19 |
+
|
| 20 |
+
wt_encoded, mt_encoded = ALPHABET[wt], ALPHABET[mt]
|
| 21 |
+
|
| 22 |
+
score = token_probs[0, 1 + idx, mt_encoded] - token_probs[0, 1 + idx, wt_encoded]
|
| 23 |
+
return score.item()
|
| 24 |
+
|
| 25 |
+
def initialise_model(model_name):
|
| 26 |
+
global MODEL, MODEL_NAME, BATCH_CONVERTER, ALPHABET
|
| 27 |
+
MODEL_NAME = model_name
|
| 28 |
+
MODEL = AutoModelForMaskedLM.from_pretrained(model_name)
|
| 29 |
+
BATCH_CONVERTER = AutoTokenizer.from_pretrained(model_name)
|
| 30 |
+
ALPHABET = BATCH_CONVERTER.get_vocab()
|
| 31 |
+
if torch.cuda.is_available():
|
| 32 |
+
MODEL = MODEL.cuda()
|
| 33 |
+
|
| 34 |
+
def parse_input(seq, sub):
|
| 35 |
+
assert seq.isalpha(), "Sequence must be alphabetic"
|
| 36 |
+
substitutions, mode = list(), None
|
| 37 |
+
|
| 38 |
+
if len(sub.split()) == 1 and len(sub.split()[0]) == len(seq):
|
| 39 |
+
mode = 'seq vs seq'
|
| 40 |
+
for resi,(src,trg) in enumerate(zip(seq,sub), OFFSET):
|
| 41 |
+
if src != trg:
|
| 42 |
+
substitutions.append(f"{src}{resi}{trg}")
|
| 43 |
+
elif len(targets := sub.split()) > 1:
|
| 44 |
+
if all(re.match(r'\d+', x) for x in targets):
|
| 45 |
+
mode = 'deep mutational scan'
|
| 46 |
+
for resi in map(int, sub.split()):
|
| 47 |
+
src = seq[resi-OFFSET]
|
| 48 |
+
for trg in "ACDEFGHIKLMNPQRSTVWY".replace(src,''):
|
| 49 |
+
substitutions.append(f"{src}{resi}{trg}")
|
| 50 |
+
elif all(re.match(r'[A-Z]\d+[A-Z]', x) for x in targets):
|
| 51 |
+
mode = 'aa substitutions'
|
| 52 |
+
substitutions = targets
|
| 53 |
+
|
| 54 |
+
if not mode:
|
| 55 |
+
raise RuntimeError("Unrecognised running mode")
|
| 56 |
+
|
| 57 |
+
return mode, pd.DataFrame(substitutions, columns=['0'])
|
| 58 |
+
|
| 59 |
+
def run_model(sequence, substitutions, batch_tokens, scoring_strategy):
|
| 60 |
+
if scoring_strategy.startswith("wt-marginals"):
|
| 61 |
+
with torch.no_grad():
|
| 62 |
+
token_probs = torch.log_softmax(MODEL(batch_tokens)["logits"], dim=-1)
|
| 63 |
+
substitutions[MODEL_NAME] = substitutions.apply(
|
| 64 |
+
lambda row: label_row(
|
| 65 |
+
row['0'],
|
| 66 |
+
sequence,
|
| 67 |
+
token_probs,
|
| 68 |
+
),
|
| 69 |
+
axis=1,
|
| 70 |
+
)
|
| 71 |
+
elif scoring_strategy.startswith("masked-marginals"):
|
| 72 |
+
all_token_probs = []
|
| 73 |
+
for i in tqdm(range(batch_tokens.size()[1])):
|
| 74 |
+
batch_tokens_masked = batch_tokens.clone()
|
| 75 |
+
batch_tokens_masked[0, i] = ALPHABET['<mask>']
|
| 76 |
+
with torch.no_grad():
|
| 77 |
+
token_probs = torch.log_softmax(
|
| 78 |
+
MODEL(batch_tokens_masked)["logits"], dim=-1
|
| 79 |
+
)
|
| 80 |
+
all_token_probs.append(token_probs[:, i])
|
| 81 |
+
token_probs = torch.cat(all_token_probs, dim=0).unsqueeze(0)
|
| 82 |
+
substitutions[MODEL_NAME] = substitutions.apply(
|
| 83 |
+
lambda row: label_row(
|
| 84 |
+
row['0'],
|
| 85 |
+
sequence,
|
| 86 |
+
token_probs,
|
| 87 |
+
),
|
| 88 |
+
axis=1,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
return substitutions
|
| 92 |
+
|
| 93 |
+
def parse_output(output, mode):
|
| 94 |
+
if mode == 'aa substitutions':
|
| 95 |
+
output = output.sort_values(MODEL_NAME, ascending=False)
|
| 96 |
+
elif mode == 'deep mutational scan':
|
| 97 |
+
output = pd.concat([(output.assign(resi=output['0'].str.extract(r'(\d+)', expand=False).astype(int))
|
| 98 |
+
.sort_values(['resi', MODEL_NAME], ascending=[True,False])
|
| 99 |
+
.groupby(['resi'])
|
| 100 |
+
.head(19)
|
| 101 |
+
.drop(['resi'], axis=1)).iloc[19*x:19*(x+1)].reset_index(drop=True) for x in range(output.shape[0]//19)]
|
| 102 |
+
, axis=1).set_axis(range(output.shape[0]//19*2), axis='columns')
|
| 103 |
+
|
| 104 |
+
return output.style.format(lambda x: f'{x:.2f}' if isinstance(x, float) else x).hide_index().hide_columns().background_gradient(cmap="RdYlGn", vmax=8, vmin=-8).to_html()
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# mode = 'deep mutational scan' #@param ['seq vs seq', 'deep mutational scan', 'aa substitutions']
|
| 108 |
+
# sequence = "MVEQYLLEAIVRDARDGITISDCSRPDNPLVFVNDAFTRMTGYDAEEVIGKNCRFLQRGDINLSAVHTIKIAMLTHEPCLVTLKNYRKDGTIFWNELSLTPIINKNGLITHYLGIQKDVSAQVILNQTLHEENHLLKSNKEMLEYLVNIDALTGLHNRRFLEDQLVIQWKLASRHINTITIFMIDIDYFKAFNDTYGHTAGDEALRTIAKTLNNCFMRGSDFVARYGGEEFTILAIGMTELQAHEYSTKLVQKIENLNIHHKGSPLGHLTISLGYSQANPQYHNDQNLVIEQADRALYSAKVEGKNRAVAYREQ" #@param {type:"string"}
|
| 109 |
+
# target = "61 214 19 30 122 140" #@param {type:"string"}
|
| 110 |
+
# substitutions = list()
|
| 111 |
+
# scoring_strategy = "masked-marginals"
|
| 112 |
+
|
| 113 |
+
# if mode == 'seq vs seq':
|
| 114 |
+
# for resi,(seq,trg) in enumerate(zip(sequence,target), OFFSET):
|
| 115 |
+
# if seq != trg:
|
| 116 |
+
# substitutions.append(f"{seq}{resi}{trg}")
|
| 117 |
+
# elif mode == 'deep mutational scan':
|
| 118 |
+
# for resi in map(int, target.split()):
|
| 119 |
+
# seq = sequence[resi-OFFSET]
|
| 120 |
+
# for trg in "ACDEFGHIKLMNPQRSTVWY".replace(seq,''):
|
| 121 |
+
# substitutions.append(f"{seq}{resi}{trg}")
|
| 122 |
+
# elif mode == 'aa substitutions':
|
| 123 |
+
# substitutions = target.split()
|
| 124 |
+
# else:
|
| 125 |
+
# raise RuntimeError("Unrecognised running mode")
|
| 126 |
+
|
| 127 |
+
# df = pd.DataFrame(substitutions, columns=['0'])
|
| 128 |
+
# mutation_col = df.columns[0]
|
| 129 |
+
|
| 130 |
+
# batch_tokens = batch_converter(sequence, return_tensors='pt')['input_ids']
|
| 131 |
+
|
| 132 |
+
# if scoring_strategy == "wt-marginals":
|
| 133 |
+
# with torch.no_grad():
|
| 134 |
+
# token_probs = torch.log_softmax(model(batch_tokens)["logits"], dim=-1)
|
| 135 |
+
# df[model_name] = df.apply(
|
| 136 |
+
# lambda row: label_row(
|
| 137 |
+
# row[mutation_col],
|
| 138 |
+
# sequence,
|
| 139 |
+
# token_probs,
|
| 140 |
+
# alphabet,
|
| 141 |
+
# OFFSET,
|
| 142 |
+
# ),
|
| 143 |
+
# axis=1,
|
| 144 |
+
# )
|
| 145 |
+
# elif scoring_strategy == "masked-marginals":
|
| 146 |
+
# all_token_probs = []
|
| 147 |
+
# for i in tqdm(range(batch_tokens.size()[1])):
|
| 148 |
+
# batch_tokens_masked = batch_tokens.clone()
|
| 149 |
+
# batch_tokens_masked[0, i] = alphabet['<mask>']
|
| 150 |
+
# with torch.no_grad():
|
| 151 |
+
# token_probs = torch.log_softmax(
|
| 152 |
+
# model(batch_tokens_masked)["logits"], dim=-1
|
| 153 |
+
# )
|
| 154 |
+
# all_token_probs.append(token_probs[:, i]) # vocab size
|
| 155 |
+
# token_probs = torch.cat(all_token_probs, dim=0).unsqueeze(0)
|
| 156 |
+
# df[model_name] = df.apply(
|
| 157 |
+
# lambda row: label_row(
|
| 158 |
+
# row[mutation_col],
|
| 159 |
+
# sequence,
|
| 160 |
+
# token_probs,
|
| 161 |
+
# alphabet,
|
| 162 |
+
# OFFSET,
|
| 163 |
+
# ),
|
| 164 |
+
# axis=1,
|
| 165 |
+
# )
|
| 166 |
+
|
| 167 |
+
# if mode == 'aa substitutions':
|
| 168 |
+
# df = df.sort_values(model_name, ascending=False)
|
| 169 |
+
# elif mode == 'deep mutational scan':
|
| 170 |
+
# df = pd.concat([(df.assign(resi=df['0'].str.extract(f'(\d+)', expand=False).astype(int))
|
| 171 |
+
# .sort_values(['resi', model_name], ascending=[True,False])
|
| 172 |
+
# .groupby(['resi'])
|
| 173 |
+
# .head(19)
|
| 174 |
+
# .drop(['resi'], axis=1)).iloc[19*x:19*(x+1)].reset_index(drop=True) for x in range(df.shape[0]//19)]
|
| 175 |
+
# , axis=1).set_axis(range(df.shape[0]//19*2), axis='columns')
|
| 176 |
+
|
| 177 |
+
# df.style.hide_index().hide_columns().background_gradient(cmap="RdYlGn", vmax=8, vmin=-8)
|
| 178 |
+
|
| 179 |
+
def app(*argv):
|
| 180 |
+
seq, trg, model_name, scoring_strategy, *_ = argv
|
| 181 |
+
|
| 182 |
+
mode, substitutions = parse_input(seq, trg)
|
| 183 |
+
|
| 184 |
+
if model_name != MODEL_NAME:
|
| 185 |
+
initialise_model(model_name)
|
| 186 |
+
|
| 187 |
+
batch_tokens = BATCH_CONVERTER(seq, return_tensors='pt')['input_ids']
|
| 188 |
+
|
| 189 |
+
df = run_model(seq, substitutions, batch_tokens, scoring_strategy)
|
| 190 |
+
|
| 191 |
+
return parse_output(df, mode)
|
| 192 |
+
|
| 193 |
+
# demo = gr.Interface(
|
| 194 |
+
# theme=gr.themes.Base(),
|
| 195 |
+
# title="Protein Sequence Mutagenesis",
|
| 196 |
+
# description="Predict the effect of mutations on protein stability",
|
| 197 |
+
# fn=app,
|
| 198 |
+
# inputs=[gr.Textbox(lines=2, label="Sequence", placeholder="Sequence here...", required=True, value='MVEQYLLEAIVRDARDGITISDCSRPDNPLVFVNDAFTRMTGYDAEEVIGKNCRFLQRGDINLSAVHTIKIAMLTHEPCLVTLKNYRKDGTIFWNELSLTPIINKNGLITHYLGIQKDVSAQVILNQTLHEENHLLKSNKEMLEYLVNIDALTGLHNRRFLEDQLVIQWKLASRHINTITIFMIDIDYFKAFNDTYGHTAGDEALRTIAKTLNNCFMRGSDFVARYGGEEFTILAIGMTELQAHEYSTKLVQKIENLNIHHKGSPLGHLTISLGYSQANPQYHNDQNLVIEQADRALYSAKVEGKNRAVAYREQ'),
|
| 199 |
+
# gr.Textbox(lines=2, label="Substitutions", placeholder="Substitutions here...", required=True, value="61 214 19 30 122 140"),
|
| 200 |
+
# gr.Dropdown(MODELS, label="Model", value=MODELS[1]),
|
| 201 |
+
# gr.Dropdown(["masked-marginals (more accurate)", "wt-marginals (faster)"], label="Scoring strategy", value="wt-marginals (faster)"),
|
| 202 |
+
# ],
|
| 203 |
+
# outputs=gr.HTML(formatter="html", label="Output"),
|
| 204 |
+
# )
|
| 205 |
+
|
| 206 |
+
with gr.Blocks() as demo:
|
| 207 |
+
gr.Markdown("""Protein Sequence Mutagenesis""", name="title")
|
| 208 |
+
gr.Markdown("""Predict the effect of mutations on protein stability""", name="description")
|
| 209 |
+
seq = gr.Textbox(lines=2, label="Sequence", placeholder="Sequence here...", required=True, value='MVEQYLLEAIVRDARDGITISDCSRPDNPLVFVNDAFTRMTGYDAEEVIGKNCRFLQRGDINLSAVHTIKIAMLTHEPCLVTLKNYRKDGTIFWNELSLTPIINKNGLITHYLGIQKDVSAQVILNQTLHEENHLLKSNKEMLEYLVNIDALTGLHNRRFLEDQLVIQWKLASRHINTITIFMIDIDYFKAFNDTYGHTAGDEALRTIAKTLNNCFMRGSDFVARYGGEEFTILAIGMTELQAHEYSTKLVQKIENLNIHHKGSPLGHLTISLGYSQANPQYHNDQNLVIEQADRALYSAKVEGKNRAVAYREQ')
|
| 210 |
+
trg = gr.Textbox(lines=1, label="Substitutions", placeholder="Substitutions here...", required=True, value="61 214 19 30 122 140")
|
| 211 |
+
model_name = gr.Dropdown(MODELS, label="Model", value=MODELS[1])
|
| 212 |
+
scoring_strategy = gr.Dropdown(SCORING, label="Scoring strategy", value=SCORING[1])
|
| 213 |
+
btn = gr.Button(label="Submit", type="submit")
|
| 214 |
+
btn.click(fn=app, inputs=[seq, trg, model_name, scoring_strategy], outputs=[gr.HTML()])
|
| 215 |
+
|
| 216 |
+
if __name__ == '__main__':
|
| 217 |
+
demo.launch()
|
| 218 |
+
# demo.launch(share=True, server_name="0.0.0.0", server_port=7878)
|