thewall commited on
Commit
60240c7
·
1 Parent(s): 73477fb

Create deepbind.py

Browse files
Files changed (1) hide show
  1. deepbind.py +301 -0
deepbind.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ /*
3
+ Copyright (c) 2023, thewall.
4
+ All rights reserved.
5
+
6
+ BSD 3-clause license:
7
+ Redistribution and use in source and binary forms,
8
+ with or without modification, are permitted provided
9
+ that the following conditions are met:
10
+
11
+ 1. Redistributions of source code must retain the
12
+ above copyright notice, this list of conditions
13
+ and the following disclaimer.
14
+
15
+ 2. Redistributions in binary form must reproduce
16
+ the above copyright notice, this list of conditions
17
+ and the following disclaimer in the documentation
18
+ and/or other materials provided with the distribution.
19
+
20
+ 3. Neither the name of the copyright holder nor the
21
+ names of its contributors may be used to endorse or
22
+ promote products derived from this software without
23
+ specific prior written permission.
24
+
25
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
+ */
37
+ """
38
+
39
+ import datasets
40
+ import torch
41
+ from torch import nn
42
+ import torch.nn.functional as F
43
+ import numpy as np
44
+ import pandas as pd
45
+ from typing import List
46
+ from functools import partial
47
+
48
+
49
+ class DeepBind(nn.Module):
50
+ ALPHABET = "ATGCN"
51
+ ALPHABET_MAP = {key:i for i, key in enumerate(ALPHABET)}
52
+ ALPHABET_MAP["U"] = 1
53
+ ALPHABET_COMPLEMENT = "TACGN"
54
+ COMPLEMENT_ID_MAP = np.array([1, 0, 3, 2, 4])
55
+ def __init__(self, reverse_complement=True, num_detectors=16, detector_len=24, has_avg_pooling=True, num_hidden=1, tokenizer=None):
56
+ super(DeepBind, self).__init__()
57
+ self.reverse_complement = reverse_complement
58
+ self.num_detectors = num_detectors
59
+ self.detector_len = detector_len
60
+ self.has_avg_pooling = has_avg_pooling
61
+ self.num_hidden = num_hidden
62
+ self.build_embedding()
63
+ self.detectors = nn.Conv1d(4, num_detectors, detector_len)
64
+ if has_avg_pooling:
65
+ self.avg_pool = nn.AvgPool1d(detector_len)
66
+ self.max_pool = nn.MaxPool1d(detector_len)
67
+ fcs = [nn.Linear(num_detectors*2 if self.has_avg_pooling else num_detectors, num_hidden)]
68
+ if num_hidden>1:
69
+ fcs.append(nn.ReLU())
70
+ fcs.append(nn.Linear(num_hidden, 1))
71
+ self.fc = nn.Sequential(*fcs)
72
+ self.tokenizer = tokenizer if tokenizer is not None else self.get_tokenizer()
73
+
74
+ @classmethod
75
+ def get_tokenizer(cls):
76
+ from tokenizers import Tokenizer, models, decoders
77
+ tokenizer = Tokenizer(models.BPE(vocab=cls.ALPHABET_MAP, merges=[]))
78
+ tokenizer.decoder = decoders.ByteLevel()
79
+ return tokenizer
80
+
81
+ @classmethod
82
+ def complement_idxs_encode_batch(cls, idxs, reverse=False):
83
+ return np.array(list(map(partial(cls.complement_idxs_encode, reverse=reverse), idxs)))
84
+
85
+ @classmethod
86
+ def complement_idxs_encode(cls, idxs, reverse=False):
87
+ if reverse:
88
+ idxs = reversed(idxs)
89
+ return cls.COMPLEMENT_ID_MAP[idxs]
90
+
91
+ def build_embedding(self):
92
+ """ATGC->ACGT:0321"""
93
+ embedding = torch.zeros(5,4)
94
+ embedding[0, 0] = 1
95
+ embedding[1, 3] = 1
96
+ embedding[2, 2] = 1
97
+ embedding[3, 1] = 1
98
+ embedding[-1] = 0.25
99
+ self.embedding = nn.Embedding.from_pretrained(embedding, freeze=True)
100
+ return embedding
101
+
102
+ @property
103
+ def device(self):
104
+ return self.detectors.bias.device
105
+
106
+ def _load_detector(self, fobj):
107
+ # dtype = functools.partial(lambda x:torch.Tensor(eval(x))
108
+ dtype = lambda x:torch.Tensor(eval(x))
109
+ weight1 = self._load_param(fobj, "detectors", dtype).reshape(self.detector_len, 4, self.num_detectors)
110
+ biases1 = self._load_param(fobj, "thresholds", dtype)
111
+ # Tx4xC->Cx4xT
112
+ self.detectors.weight.data = weight1.permute(2, 1, 0).contiguous().to(device=self.detectors.weight.device)
113
+ self.detectors.bias.data = biases1.to(device=self.detectors.bias.device)
114
+
115
+ def _load_fc1(self, fobj):
116
+ num_hidden1 = self.num_detectors * 2 if self.has_avg_pooling else self.num_detectors
117
+ dtype = lambda x:torch.Tensor(np.array(eval(x)))
118
+ weight1 = self._load_param(fobj, "weights1", dtype).reshape(num_hidden1, self.num_hidden)
119
+ biases1 = self._load_param(fobj, "biases1", dtype)
120
+ self.fc[0].weight.data = weight1.T.contiguous().to(device=self.fc[0].weight.device)
121
+ self.fc[0].bias.data = biases1.to(device=self.fc[0].bias.device)
122
+
123
+ def _load_fc2(self, fobj):
124
+ dtype = lambda x:torch.Tensor(np.array(eval(x)))
125
+ weight2 = self._load_param(fobj, "weights2", dtype)
126
+ biases2 = self._load_param(fobj, "biases2", dtype)
127
+ assert not (weight2 is None and self.num_hidden>1)
128
+ assert not (biases2 is None and self.num_hidden>1)
129
+ if self.num_hidden>1:
130
+ self.fc[2].weight.data = weight2.reshape(1,-1).to(device=self.fc[2].weight.device)
131
+ self.fc[2].bias.data = biases2.to(device=self.fc[2].bias.device)
132
+
133
+ @classmethod
134
+ def _load_param(cls, fobj, param_name, dtype):
135
+ line = fobj.readline().strip()
136
+ tmp = line.split("=")
137
+ assert tmp[0].strip() == param_name
138
+ if len(tmp)>1 and len(tmp[1].strip())>0:
139
+ return dtype(tmp[1].strip())
140
+
141
+ @classmethod
142
+ def load_model(cls, sra_id="ERR173157", file=None, ID=None):
143
+ if file is None:
144
+ config = datasets.load_dataset(path="thewall/deepbindweight", split="all")
145
+ if ID is None:
146
+ data = pd.read_excel(config[0]['table'], index_col=0)
147
+ ID = data.loc[sra_id]["ID"]
148
+ file = datasets.load_dataset(path="thewall/deepbindweight", name=ID, split="all")[0]['config']
149
+ keys = [("reverse_complement", lambda x:bool(eval(x))), ("num_detectors", int), ("detector_len", int),
150
+ ("has_avg_pooling", lambda x:bool(eval(x))), ("num_hidden", int)]
151
+ hparams = {}
152
+ with open(file) as fobj:
153
+ version = fobj.readline()[1:].strip()
154
+ for key in keys:
155
+ value = cls._load_param(fobj, key[0], key[1])
156
+ hparams[key[0]]=value
157
+ if hparams['num_hidden']==0:
158
+ hparams['num_hidden']=1
159
+ model = cls(**hparams)
160
+ model._load_detector(fobj)
161
+ model._load_fc1(fobj)
162
+ model._load_fc2(fobj)
163
+ print(f"load model from {file}")
164
+ return model
165
+
166
+ def inference(self, sequence: List[str], window_size=0, average_flag=False):
167
+ if isinstance(sequence, str):
168
+ sequence = [sequence]
169
+ ans = []
170
+ self.tokenizer.no_padding()
171
+ for seq in sequence:
172
+ inputs = torch.IntTensor(self.tokenizer.encode(seq).ids).unsqueeze(0).to(device=self.device)
173
+ score = self.test(inputs, window_size, average_flag).item()
174
+ ans.append(score)
175
+ return ans
176
+
177
+ @torch.no_grad()
178
+ def batch_inference(self, sequence: List[str], window_size=0, average_flag=False):
179
+ if isinstance(sequence, str):
180
+ sequence = [sequence]
181
+ self.tokenizer.enable_padding()
182
+ encodings = self.tokenizer.encode_batch(sequences)
183
+ ids = torch.Tensor([encoding.ids for encoding in encodings]).to(device=self.device)
184
+ mask = torch.BoolTensor([encoding.attention_mask for encoding in encodings]).to(device=self.device)
185
+ seq_len = mask.sum(dim=1)
186
+ score = self.batch_scan_model(ids, seq_len, window_size, average_flag)
187
+ if self.reverse_complement:
188
+ rev_seq = self.complement_idxs_encode_batch(ids.cpu().int(), reverse=True)
189
+ rev_seq = torch.Tensor(rev_seq).to(device=self.device)
190
+ rev_score = self.batch_scan_model(rev_seq, seq_len, window_size, average_flag)
191
+ score = torch.stack([rev_score, score], dim=-1).max(dim=-1)[0]
192
+ return score.cpu().tolist()
193
+
194
+ def batch_scan_model(self, ids, seq_len, window_size: int = 0, average_flag: bool = False):
195
+ if window_size < 1:
196
+ window_size = int(self.detector_len * 1.5)
197
+ scores = torch.zeros_like(seq_len).float()
198
+ masked = seq_len<=window_size
199
+ for idx in torch.where(masked)[0]:
200
+ scores[idx] = self.forward(ids[idx:idx+1, :seq_len[idx]].int())
201
+
202
+ fold_ids = F.unfold(ids[~masked].unsqueeze(1).unsqueeze(1), kernel_size=(1, window_size), stride=1)
203
+ B, W, G = fold_ids.shape
204
+ fold_ids = fold_ids.permute(0, 2, 1).reshape(-1, W)
205
+ ans = self.forward(fold_ids.int())
206
+ ans = ans.reshape(B, G)
207
+ if average_flag:
208
+ valid_len = seq_len-window_size+1
209
+ for idx, value in zip(torch.where(~masked)[0], ans):
210
+ scores[idx] = value[:valid_len[idx]].mean()
211
+ else:
212
+ unvalid_mask = torch.arange(G).unsqueeze(0).to(seq_len.device)>=(seq_len[~masked]-window_size+1).unsqueeze(1)
213
+ ans[unvalid_mask] = -torch.inf
214
+ scores[~masked] = ans.max(dim=1)[0]
215
+ return scores
216
+
217
+ @torch.no_grad()
218
+ def test(self, seq: torch.IntTensor, window_size=0, average_flag=False):
219
+ score = self.scan_model(seq, window_size, average_flag)
220
+ if self.reverse_complement:
221
+ rev_seq = self.complement_idxs_encode_batch(seq.cpu(), reverse=True)
222
+ rev_seq = torch.IntTensor(rev_seq).to(device=seq.device)
223
+ rev_score = self.scan_model(rev_seq, window_size, average_flag)
224
+ score = torch.cat([rev_score, score], dim=-1).max(dim=-1)[0]
225
+ return score
226
+
227
+ def scan_model(self, seq: torch.IntTensor, window_size: int = 0, average_flag: bool = False):
228
+ seq_len = seq.shape[1]
229
+ if window_size<1:
230
+ window_size = int(self.detector_len*1.5)
231
+ if seq_len<=window_size:
232
+ return self.forward(seq)
233
+ else:
234
+ scores = []
235
+ for i in range(0, seq_len-window_size+1):
236
+ scores.append(self.forward(seq[:,i:i+window_size]))
237
+ scores = torch.stack(scores, dim=-1)
238
+ if average_flag:
239
+ return scores.mean(dim=-1)
240
+ else:
241
+ return scores.max(dim=-1)[0]
242
+
243
+ def forward(self, seq: torch.IntTensor):
244
+ seq = F.pad(seq, (self.detector_len-1, self.detector_len-1), value=4)
245
+ x = self.embedding(seq)
246
+ x = x.permute(0, 2, 1)
247
+ x = self.detectors(x)
248
+ x = torch.relu(x)
249
+ x = x.permute(0, 2, 1)
250
+ if self.has_avg_pooling:
251
+ x = torch.stack([torch.max(x, dim=1)[0], torch.mean(x, dim=1)], dim=-1)
252
+ x = torch.flatten(x, 1)
253
+ else:
254
+ x = torch.max(x, dim=1)[0]
255
+ x = x.squeeze(dim=-1)
256
+ x = self.fc(x)
257
+ return x
258
+
259
+
260
+ if __name__=="__main__":
261
+ """
262
+ AGGUAAUAAUUUGCAUGAAAUAACUUGGAGAGGAUAGC
263
+ AGACAGAGCUUCCAUCAGCGCUAGCAGCAGAGACCAUU
264
+ GAGGTTACGCGGCAAGATAA
265
+ TACCACTAGGGGGCGCCACC
266
+
267
+ To generate 16 predictions (4 models, 4 sequences), run
268
+ the deepbind executable as follows:
269
+
270
+ % deepbind example.ids < example.seq
271
+ D00210.001 D00120.001 D00410.003 D00328.003
272
+ 7.451420 -0.166146 -0.408751 -0.026180
273
+ -0.155398 4.113817 0.516956 -0.248167
274
+ -0.140683 0.181295 5.885349 -0.026180
275
+ -0.174985 -0.152521 -0.379695 17.682623
276
+ """
277
+ sequences = ["AGGUAAUAAUUUGCAUGAAAUAACUUGGAGAGGAUAGC",
278
+ "AGACAGAGCUUCCAUCAGCGCUAGCAGCAGAGACCAUU",
279
+ "GAGGTTACGCGGCAAGATAA",
280
+ "TACCACTAGGGGGCGCCACC"]
281
+ model = DeepBind.load_model(ID='D00410.003')
282
+ print(model.batch_inference(sequences))
283
+
284
+ import random
285
+ import time
286
+ from tqdm import tqdm
287
+ sequences = ["".join([random.choice("ATGC") for _ in range(40)]) for i in range(1000)]
288
+ def test_fn(sequences, fn):
289
+ start_time = time.time()
290
+ for start in tqdm(range(0, len(sequences), 256)):
291
+ batch = sequences[start: min(start+256, len(sequences))]
292
+ fn(batch)
293
+ print(time.time()-start_time)
294
+
295
+ # test_fn(sequences, model.inference)
296
+ # test_fn(sequences, model.batch_inference)
297
+ model = model.cuda()
298
+ test_fn(sequences, model.batch_inference)
299
+ test_fn(sequences, model.inference)
300
+ test_fn(sequences, model.batch_inference)
301
+ test_fn(sequences, model.inference)