forked from quentin0515/devas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
executable file
·1516 lines (1161 loc) · 50.2 KB
/
utils.py
File metadata and controls
executable file
·1516 lines (1161 loc) · 50.2 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# In[9]:
import pysam
import csv
import numpy as np
import random
import math
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import random_split, Dataset, DataLoader
from gensim.models import Word2Vec
# In[1]:
#lb, ub of len of DEL, DUP
min_len = 50
max_len = 2000
max_len_ins = 500
#upper bound of cov (from select_seq.ipynb)
cov_ub = 300
#the interval of two sv to be counted as overlap
ol_interval = 1000
#flanking length
flanking = 200
#flanking length
flanking_ins = 500
# ref fasta file
fasta_file_path = "/project/mchaisso_100/datasets/1kg_phase3_related/GRCh38_full_analysis_set_plus_decoy_hla.fa"
sample = "HG00"
# no of features: cov, sc, insert size, 3mer emb
no_features = 4
# add constant to scale features
cov_scaler = 50
sc_scaler = 10
insert_scaler = 10000
emb_scaler = 1
# upper bound of insert size after scaling
insert_upper = 50
# the pretrained word2vec model
kmer_emb_size = 5
# Word2Vec_model_name = "del_2000_30samples_3mers_truth__word2vec"
# Word2Vec_model = Word2Vec.load(f"{Word2Vec_model_name}.model")
# In[6]:
nucs='ACGT'
kmer_mapping = dict()
for i in range(0,4):
for j in range(0,4):
for k in range(0,4):
kmer_mapping[nucs[i] + nucs[j] + nucs[k]] = i*16+j*4+k + 1
# In[7]:
kmer_reverse_mapping = dict()
for key, value in kmer_mapping.items():
kmer_reverse_mapping[value] = key
# In[3]:
# chr
chr_list = ["chr1", "chr2", "chr3", "chr4", "chr5",
"chr6", "chr7", "chr8", "chr9", "chr10",
"chr11", "chr12", "chr13", "chr14", "chr15",
"chr16", "chr17", "chr18", "chr19", "chr20",
"chr21", "chr22"]
# valid types
# valid_types = ['DEL', 'INS', 'DUP']
valid_types = ['DEL', 'INS', 'DUP', 'INV']
#len of chr
chr_len_ori = [250000000, 244000000, 202000000, 194000000, 183000000,
173000000, 161000000, 147000000, 151000000, 136000000,
136000000, 134000000, 116000000, 108000000, 103000000,
96400000, 84300000, 80600000, 61800000, 66300000,
48200000, 51400000, 157000000, 62500000]
chr_len = [int(0.8 * length) for length in chr_len_ori]
# In[5]:
# # Define the Transformer model
# class TransformerClassifier_naive(nn.Module):
# def __init__(self, d_model, nhead, num_layers, num_classes, dim_feedforward):
# super(TransformerClassifier_naive, self).__init__()
# self.embedding = nn.Embedding(512, d_model)
# self.transformer = nn.Transformer(d_model, nhead, num_layers, dim_feedforward)
# self.fc = nn.Linear(d_model, num_classes)
# def forward(self, x):
# x = self.embedding(x)
# x = x.permute(1, 0, 2)
# x = self.transformer.encoder(x)
# x = x.permute(1, 0, 2)
# x = self.fc(x[:, 0, :])
# return x
# In[ ]:
# # Define the Transformer model
# class TransformerClassifier(nn.Module):
# def __init__(self, d_model, nhead, num_layers, num_classes, dim_feedforward, dropout=0.1):
# super(TransformerClassifier, self).__init__()
# self.embedding = nn.Embedding(512, d_model)
# self.linear0 = nn.Linear(2, d_model)
# # self.pos_encoder = self.make_sincos_pos_encoding(d_model, 2000)
# self.pos_encoder = PositionalEncoding(d_model, (max_len + 2 * flanking + 100) * 2)
# self.encoder_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=nhead, dropout=dropout)
# self.transformer_encoder = nn.TransformerEncoder(self.encoder_layer, num_layers=num_layers)
# self.fc_out = nn.Linear(d_model, num_classes)
# self.init_weights()
# def init_weights(self):
# initrange = 0.1
# self.embedding.weight.data.uniform_(-initrange, initrange)
# self.fc_out.weight.data.uniform_(-initrange, initrange)
# def make_sincos_pos_encoding(self, d_model, max_len):
# pos_encoding = torch.zeros(max_len, d_model)
# position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
# div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
# pos_encoding[:, 0::2] = torch.sin(position * div_term)
# pos_encoding[:, 1::2] = torch.cos(position * div_term)
# pos_encoding = pos_encoding.unsqueeze(0).transpose(0, 1)
# return pos_encoding
# def forward(self, src):
# # print(src.size())
# # src = self.linear0(src)
# src = self.embedding(src.long()) # Embedding each integer
# src = src.view(src.size(0), -1, src.size(-1))
# src = self.pos_encoder(src)
# # print(src.size())
# src = src.permute(1, 0, 2) # Adjust shape for transformer encoder: [seq_len, batch_size, d_model]
# # src += self.pos_encoder[:src.size(0), :, :].to(src.device)
# transformer_output = self.transformer_encoder(src)
# # print("1", transformer_output.size())
# output = transformer_output.mean(dim=0)
# output = self.fc_out(output)
# return output
# In[ ]:
# sparse attention
def get_attn_mask(n, attn_mode, local_attn_ctx=None):
if attn_mode == 'all':
b = torch.tril(torch.ones([n, n]))
elif attn_mode == 'local':
bandwidth = local_attn_ctx
ctx = min(n - 1, bandwidth - 1)
b = torch.tril(torch.ones([n, n]), ctx)
elif attn_mode == 'strided':
stride = local_attn_ctx
x = torch.reshape(torch.arange(n, dtype=torch.int32), [n, 1])
y = torch.transpose(x, 0, 1)
z = torch.zeros([n, n], dtype=torch.int32)
q = z + x
k = z + y
c1 = q >= k
c2 = torch.eq(torch.fmod(q - k, stride), 0)
c3 = torch.logical_and(c1, c2)
b = c3.float()
else:
raise ValueError('Not yet implemented')
b = torch.reshape(b, [1, 1, n, n])
return b
def strided_transpose(x, n_ctx, local_attn_ctx, blocksize):
bT_ctx = n_ctx // local_attn_ctx
assert bT_ctx % blocksize == 0, f'{bT_ctx}, {blocksize}'
n, t, embd = x.size()
x = torch.reshape(x, [n, bT_ctx, local_attn_ctx, embd])
# print(x.size())
# x = torch.transpose(x, 0, 2, 1, 3)
x = torch.permute(x, (0, 2, 1, 3))
x = torch.reshape(x, [n, t, embd])
return x
def split_heads(x, n):
return torch.transpose(split_states(x, n), 0, 2, 1, 3)
def merge_heads(x):
return merge_states(torch.transpose(x, 0, 2, 1, 3))
def split_states(x, n):
"""
reshape (batch, pixel, state) -> (batch, pixel, head, head_state)
"""
x_shape = x.size()
m = x_shape[-1]
new_x_shape = x_shape[:-1] + [n, m // n]
return torch.reshape(x, new_x_shape)
return torch.reshape(x, new_x_shape)
def merge_states(x):
"""
reshape (batch, pixel, head, head_state) -> (batch, pixel, state)
"""
x_shape = x.size()
new_x_shape = x_shape[:-2] + [np.prod(x_shape[-2:])]
return torch.reshape(x, new_x_shape)
def attention_impl(q, k, v, heads, attn_mode, local_attn_ctx=None):
q = split_heads(q, heads)
k = split_heads(k, heads)
v = split_heads(v, heads)
n_timesteps = k.size()[2]
mask = get_attn_mask(n_timesteps, attn_mode, local_attn_ctx).float()
w = torch.matmul(q, k.transpose(-2, -1))
scale_amount = 1.0 / np.sqrt(q.size()[-1])
w = w * scale_amount
w = w * mask + -1e9 * (1 - mask)
w = F.softmax(w, dim=-1)
a = torch.matmul(w, v)
a = merge_heads(a)
return a
def blocksparse_attention_impl(q, k, v, heads, attn_mode, local_attn_ctx=None, blocksize=32, num_verts=None, vertsize=None):
n_ctx = q.size()[1]
if attn_mode == 'strided':
q = strided_transpose(q, n_ctx, local_attn_ctx, blocksize)
k = strided_transpose(k, n_ctx, local_attn_ctx, blocksize)
v = strided_transpose(v, n_ctx, local_attn_ctx, blocksize)
n_state = q.size()[-1] // heads
# bst = get_blocksparse_obj(n_ctx, heads, attn_mode, blocksize, local_attn_ctx, num_verts, vertsize)
scale_amount = 1.0 / np.sqrt(n_state)
w = torch.matmul(q, k.transpose(-2, -1))
# w = bst.masked_softmax(w, scale=scale_amount)
w = F.softmax(w * scale_amount, dim=-1)
a = torch.matmul(w, v)
if attn_mode == 'strided':
n, t, embd = a.size()
bT_ctx = n_ctx // local_attn_ctx
a = torch.reshape(a, [n, local_attn_ctx, bT_ctx, embd])
# a = torch.transpose(a, 0, 2, 1, 3)
a = torch.permute(a, (0, 2, 1, 3))
a = torch.reshape(a, [n, t, embd])
return a
class SparseAttention(nn.Module):
def __init__(self, heads, attn_mode, local_attn_ctx=None, blocksize=32):
super(SparseAttention, self).__init__()
self.heads = heads
self.attn_mode = attn_mode
self.local_attn_ctx = local_attn_ctx
self.blocksize = blocksize
def forward(self, q, k, v):
return blocksparse_attention_impl(q, k, v, self.heads, self.attn_mode, self.local_attn_ctx, self.blocksize)
# In[ ]:
class BinaryClassificationTransformer11117Norm2(nn.Module):
def __init__(self, d_model, nhead, attn_mode, local_attn_ctx=None, blocksize=32, num_layers=1, dim_feedforward=32, dropout=0.1):
super(BinaryClassificationTransformer11117Norm2, self).__init__()
self.embedding = nn.Embedding(512, d_model)
self.linear0 = nn.Linear(8, d_model)
self.pos_encoder = PositionalEncoding(d_model, (max_len + 2 * flanking + 100) * 2)
self.encoder_layer = TransformerEncoderLayerWithSparseAttentionNorm1(d_model, nhead, attn_mode, local_attn_ctx, blocksize, dim_feedforward, dropout)
self.encoder = nn.Sequential(*[self.encoder_layer for _ in range(num_layers)])
self.classifier = nn.Linear(d_model, 2)
def forward(self, src):
# print(src.size())
src = self.linear0(src)
# src = self.embedding(src.long()) # Embedding each integer
# src = src.view(src.size(0), src.size(1), -1)
src = self.pos_encoder(src)
# print(src.size())
# print(src.size())
src = src.permute(1, 0, 2)
encoded = self.encoder(src)
# print("1", encoded.size())
# encoded = encoded.permute(1, 0, 2)
output = encoded.mean(dim=0)
# print(output.size())
output = self.classifier(output)
# print(output.size())
return output
# In[ ]:
class TransformerEncoderLayerWithSparseAttention(nn.Module):
def __init__(self, d_model, heads, attn_mode, local_attn_ctx=None, blocksize=32, dim_feedforward=32, dropout=0.1):
super(TransformerEncoderLayerWithSparseAttention, self).__init__()
self.sparse_attention = SparseAttention(heads=heads, attn_mode=attn_mode, local_attn_ctx=local_attn_ctx, blocksize=blocksize)
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.activation = nn.ReLU()
def forward(self, src):
# print("1", src.size())
src = src.permute(1, 0, 2)
src2 = self.sparse_attention(q=src, k=src, v=src)
# print("2", src.size())
src = src + self.dropout1(src2)
# print("3", src.size())
# src = self.norm1(src)
# print("4", src.size())
# src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
# print("5", src.size())
# src = src + self.dropout2(src2)
# print("6", src.size())
# src = self.norm2(src)
# print("7", src.size())
src = src.permute(1, 0, 2)
return src
class TransformerEncoderLayerWithSparseAttentionNorm(nn.Module):
def __init__(self, d_model, heads, attn_mode, local_attn_ctx=None, blocksize=32, dim_feedforward=32, dropout=0.1):
super(TransformerEncoderLayerWithSparseAttentionNorm, self).__init__()
self.sparse_attention = SparseAttention(heads=heads, attn_mode=attn_mode, local_attn_ctx=local_attn_ctx, blocksize=blocksize)
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.activation = nn.ReLU()
def forward(self, src):
# print("1", src.size())
src = src.permute(1, 0, 2)
src2 = self.sparse_attention(q=src, k=src, v=src)
# print("2", src.size())
src = src + self.dropout1(src2)
# print("3", src.size())
src = self.norm1(src)
# print("4", src.size())
src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
# print("5", src.size())
# src = src + self.dropout2(src2)
# print("6", src.size())
# src = self.norm2(src)
# print("7", src.size())
src = src.permute(1, 0, 2)
return src
class BinaryClassificationTransformer11117Norm(nn.Module):
def __init__(self, d_model, nhead, attn_mode, local_attn_ctx=None, blocksize=32, num_layers=1, dim_feedforward=32, dropout=0.1):
super(BinaryClassificationTransformer11117Norm, self).__init__()
self.embedding = nn.Embedding(512, d_model)
self.linear0 = nn.Linear(2, d_model)
self.pos_encoder = PositionalEncoding(d_model * 2, (max_len + 2 * flanking + 100) * 2)
self.encoder_layer = TransformerEncoderLayerWithSparseAttentionNorm(d_model * 2, nhead, attn_mode, local_attn_ctx, blocksize, dim_feedforward, dropout)
self.encoder = nn.Sequential(*[self.encoder_layer for _ in range(num_layers)])
self.classifier = nn.Linear(d_model * 2, 2)
def forward(self, src):
# print(src.size())
# src = self.linear0(src)
src = self.embedding(src.long()) # Embedding each integer
src = src.view(src.size(0), src.size(1), -1)
src = self.pos_encoder(src)
# print(src.size())
# print(src.size())
src = src.permute(1, 0, 2)
encoded = self.encoder(src)
# print("1", encoded.size())
# encoded = encoded.permute(1, 0, 2)
output = encoded.mean(dim=0)
# print(output.size())
output = self.classifier(output)
# print(output.size())
return output
class TransformerEncoderLayerWithSparseAttentionNorm1(nn.Module):
def __init__(self, d_model, heads, attn_mode, local_attn_ctx=None, blocksize=32, dim_feedforward=32, dropout=0.1):
super(TransformerEncoderLayerWithSparseAttentionNorm1, self).__init__()
self.sparse_attention = SparseAttention(heads=heads, attn_mode=attn_mode, local_attn_ctx=local_attn_ctx, blocksize=blocksize)
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.activation = nn.ReLU()
def forward(self, src):
# print("1", src.size())
src = src.permute(1, 0, 2)
src2 = self.sparse_attention(q=src, k=src, v=src)
# print("2", src.size())
src = src + self.dropout1(src2)
# print("3", src.size())
src = self.norm1(src)
# print("4", src.size())
src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
# print("5", src.size())
src = src + self.dropout2(src2)
# print("6", src.size())
src = self.norm2(src)
# print("7", src.size())
src = src.permute(1, 0, 2)
return src
class BinaryClassificationTransformer11117Norm1(nn.Module):
def __init__(self, d_model, nhead, attn_mode, local_attn_ctx=None, blocksize=32, num_layers=1, dim_feedforward=32, dropout=0.1):
super(BinaryClassificationTransformer11117Norm1, self).__init__()
self.embedding = nn.Embedding(512, d_model)
self.linear0 = nn.Linear(2, d_model)
self.pos_encoder = PositionalEncoding(d_model * 2, (max_len + 2 * flanking + 100) * 2)
self.encoder_layer = TransformerEncoderLayerWithSparseAttentionNorm1(d_model * 2, nhead, attn_mode, local_attn_ctx, blocksize, dim_feedforward, dropout)
self.encoder = nn.Sequential(*[self.encoder_layer for _ in range(num_layers)])
self.classifier = nn.Linear(d_model * 2, 2)
def forward(self, src):
# print(src.size())
# src = self.linear0(src)
src = self.embedding(src.long()) # Embedding each integer
src = src.view(src.size(0), src.size(1), -1)
src = self.pos_encoder(src)
# print(src.size())
# print(src.size())
src = src.permute(1, 0, 2)
encoded = self.encoder(src)
# print("1", encoded.size())
# encoded = encoded.permute(1, 0, 2)
output = encoded.mean(dim=0)
# print(output.size())
output = self.classifier(output)
# print(output.size())
return output
class BinaryClassificationTransformerNorm1(nn.Module):
def __init__(self, d_model, nhead, attn_mode, local_attn_ctx=None, blocksize=32, num_layers=1, dim_feedforward=32, dropout=0.1):
super(BinaryClassificationTransformerNorm1, self).__init__()
self.embedding = nn.Embedding(512, d_model)
self.linear0 = nn.Linear(2, d_model)
self.pos_encoder = PositionalEncoding(d_model, (max_len + 2 * flanking + 100) * 2)
self.encoder_layer = TransformerEncoderLayerWithSparseAttentionNorm1(d_model, nhead, attn_mode, local_attn_ctx, blocksize, dim_feedforward, dropout)
self.encoder = nn.Sequential(*[self.encoder_layer for _ in range(num_layers)])
self.classifier = nn.Linear(d_model, 2)
def forward(self, src):
# print(src.size())
# src = self.linear0(src)
src = self.embedding(src.long()) # Embedding each integer
src = src.view(src.size(0), -1, src.size(-1))
src = self.pos_encoder(src)
# print(src.size())
# print(src.size())
src = src.permute(1, 0, 2)
encoded = self.encoder(src)
# print("1", encoded.size())
# encoded = encoded.permute(1, 0, 2)
output = encoded.mean(dim=0)
# print(output.size())
output = self.classifier(output)
# print(output.size())
return output
class BinaryClassificationTransformer(nn.Module):
def __init__(self, d_model, nhead, attn_mode, local_attn_ctx=None, blocksize=32, num_layers=1, dim_feedforward=32, dropout=0.1):
super(BinaryClassificationTransformer, self).__init__()
self.embedding = nn.Embedding(512, d_model)
self.linear0 = nn.Linear(2, d_model)
self.pos_encoder = PositionalEncoding(d_model, (max_len + 2 * flanking + 100) * 2)
self.encoder_layer = TransformerEncoderLayerWithSparseAttention(d_model, nhead, attn_mode, local_attn_ctx, blocksize, dim_feedforward, dropout)
self.encoder = nn.Sequential(*[self.encoder_layer for _ in range(num_layers)])
self.classifier = nn.Linear(d_model, 2)
def forward(self, src):
# print(src.size())
# src = self.linear0(src)
src = self.embedding(src.long()) # Embedding each integer
src = src.view(src.size(0), -1, src.size(-1))
src = self.pos_encoder(src)
# print(src.size())
# print(src.size())
src = src.permute(1, 0, 2)
encoded = self.encoder(src)
# print("1", encoded.size())
# encoded = encoded.permute(1, 0, 2)
output = encoded.mean(dim=0)
# print(output.size())
output = self.classifier(output)
# print(output.size())
return output
class BinaryClassificationTransformer11117(nn.Module):
def __init__(self, d_model, nhead, attn_mode, local_attn_ctx=None, blocksize=32, num_layers=1, dim_feedforward=32, dropout=0.1):
super(BinaryClassificationTransformer11117, self).__init__()
self.embedding = nn.Embedding(512, d_model)
self.linear0 = nn.Linear(2, d_model)
self.pos_encoder = PositionalEncoding(d_model * 2, (max_len + 2 * flanking + 100) * 2)
self.encoder_layer = TransformerEncoderLayerWithSparseAttention(d_model * 2, nhead, attn_mode, local_attn_ctx, blocksize, dim_feedforward, dropout)
self.encoder = nn.Sequential(*[self.encoder_layer for _ in range(num_layers)])
self.classifier = nn.Linear(d_model * 2, 2)
def forward(self, src):
# print(src.size())
# src = self.linear0(src)
src = self.embedding(src.long()) # Embedding each integer
src = src.view(src.size(0), src.size(1), -1)
src = self.pos_encoder(src)
# print(src.size())
# print(src.size())
src = src.permute(1, 0, 2)
encoded = self.encoder(src)
# print("1", encoded.size())
# encoded = encoded.permute(1, 0, 2)
output = encoded.mean(dim=0)
# print(output.size())
output = self.classifier(output)
# print(output.size())
return output
# In[ ]:
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super(PositionalEncoding, self).__init__()
# Create a long enough PE matrix of zeros
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0) # Add a batch dimension (B x SeqLen x DModel)
self.register_buffer('pe', pe)
def forward(self, x):
"""
Args:
x: Tensor, shape [batch_size, seq_length, d_model]
"""
# Add positional encoding to the input batch, assuming x is of shape (B, SeqLen, DModel)
x = (x + self.pe[:, :x.size(1)]).cuda()
return x
# In[ ]:
class SlidingWindowAttention(nn.Module):
def __init__(self, embed_dim, window_size):
super(SlidingWindowAttention, self).__init__()
self.embed_dim = embed_dim
self.window_size = window_size
self.linear = nn.Linear(embed_dim, embed_dim)
def forward(self, x):
# x: [batch_size, seq_len, embed_dim]
batch_size, seq_len, embed_dim = x.shape
output = torch.zeros_like(x)
for i in range(seq_len):
# Determine the window range
start = max(0, i - self.window_size)
end = min(seq_len, i + self.window_size + 1)
# Apply linear transformation within the window
window_features = self.linear(x[:, start:end, :])
# Sum features within the window for simplicity
output[:, i, :] = window_features.sum(dim=1)
return output
# In[2]:
class SlidingWindowAttention(nn.Module):
def __init__(self, embed_size, heads, window_size):
super(SlidingWindowAttention, self).__init__()
self.embed_size = embed_size
self.heads = heads
self.head_dim = embed_size // heads
self.window_size = window_size
assert (
self.head_dim * heads == embed_size
), "Embedding size needs to be divisible by heads"
self.values = nn.Linear(self.head_dim, self.head_dim, bias=False)
self.keys = nn.Linear(self.head_dim, self.head_dim, bias=False)
self.queries = nn.Linear(self.head_dim, self.head_dim, bias=False)
self.fc_out = nn.Linear(heads * self.head_dim, embed_size)
def forward(self, value, key, query):
N = query.shape[0]
value_len, key_len, query_len = value.shape[1], key.shape[1], query.shape[1]
values = self.values(value).view(N, value_len, self.heads, self.head_dim)
keys = self.keys(key).view(N, key_len, self.heads, self.head_dim)
queries = self.queries(query).view(N, query_len, self.heads, self.head_dim)
attention_scores = torch.zeros((N, self.heads, query_len, self.window_size * 2 + 1), device=query.device)
for i in range(query_len):
# Define the window bounds
start = max(0, i - self.window_size)
end = min(key_len, i + self.window_size + 1)
# Calculate scores
scores = torch.einsum("nhqd,nhkd->nhqk", [queries[:, i:i+1, :, :], keys[:, start:end, :, :]])
attention_scores[:, :, i, start-i+self.window_size:end-i+self.window_size] = scores.squeeze(1)
# Apply softmax on the last dimension to normalize the scores
attention = torch.softmax(attention_scores, dim=-1)
# Apply attention to values
out = torch.einsum("nhql,nhld->nqhd", [attention, values]).reshape(N, query_len, self.heads * self.head_dim)
return self.fc_out(out)
# In[3]:
class TransformerClassifierWindow(nn.Module):
def __init__(self, feature_dim, embed_dim, num_classes, max_seq_len, window_size):
super(TransformerClassifierWindow, self).__init__()
self.feature_to_embed = nn.Linear(feature_dim, embed_dim)
self.position_embedding = nn.Parameter(torch.randn(1, max_seq_len, embed_dim))
self.sliding_window_attention = SlidingWindowAttention(embed_dim, window_size)
self.classifier = nn.Linear(embed_dim, num_classes)
def forward(self, x):
# x: [batch_size, seq_len, feature_dim]
x = self.feature_to_embed(x) # [batch_size, seq_len, embed_dim]
x += self.position_embedding[:, :x.size(1), :] # Add position embedding
x = self.sliding_window_attention(x)
x = x.mean(dim=1) # Pooling over the sequence dimension
out = self.classifier(x)
return out
# In[10]:
# class TransformerVAE(nn.Module):
# def __init__(self, input_dim, hidden_dim, z_dim, num_classes, max_length):
# super().__init__()
# self.embedding = nn.Embedding(input_dim, hidden_dim)
# self.position_embedding = nn.Embedding(max_length, hidden_dim)
# # Transformer encoder
# self.transformer_encoder = nn.TransformerEncoderLayer(d_model=hidden_dim, nhead=8)
# self.fc_mean = nn.Linear(hidden_dim, z_dim)
# self.fc_logvar = nn.Linear(hidden_dim, z_dim)
# # Transformer decoder
# self.transformer_decoder = nn.TransformerDecoderLayer(d_model=hidden_dim, nhead=8)
# self.fc_out = nn.Linear(hidden_dim, input_dim)
# # Classification head
# self.classifier = nn.Linear(hidden_dim, num_classes)
# def encode(self, x):
# embedded = self.embedding(x) + self.position_embedding(torch.arange(x.size(1), device=x.device))
# encoded = self.transformer_encoder(embedded)
# mean = self.fc_mean(encoded.mean(dim=1))
# logvar = self.fc_logvar(encoded.mean(dim=1))
# logits = self.classifier(encoded.mean(dim=1))
# return mean, logvar, logits
# def reparameterize(self, mean, logvar):
# std = torch.exp(0.5 * logvar)
# eps = torch.randn_like(std)
# return mean + eps * std
# def decode(self, z):
# decoded = self.transformer_decoder(z.unsqueeze(1))
# return torch.sigmoid(self.fc_out(decoded))
# def forward(self, x):
# mean, logvar, logits = self.encode(x)
# z = self.reparameterize(mean, logvar)
# reconstructed = self.decode(z)
# return reconstructed, mean, logvar, logits
# # Model parameters
# # input_dim = 1000 # Vocabulary size
# # hidden_dim = 512
# # z_dim = 20
# # num_classes = 10
# # max_length = 50
# # Initialize the model
# # model = TransformerVAE(input_dim, hidden_dim, z_dim, num_classes, max_length)
# # Example forward pass with random data
# # x = torch.randint(0, input_dim, (32, max_length)) # Example batch of sequences
# # reconstructed, mean, logvar, logits = model(x)
# In[11]:
class CustomDataset(Dataset):
def __init__(self, feature_matrix, labels):
self.features = torch.tensor(feature_matrix, dtype=torch.float)
self.labels = torch.tensor(labels, dtype=torch.long)
def __len__(self):
return len(self.labels)
def __getitem__(self, index):
return self.features[index], self.labels[index]
# In[7]:
class CustomDatasetSparse(Dataset):
def __init__(self, feature_matrix, labels):
self.features = torch.tensor(feature_matrix, dtype=torch.float)
self.labels = torch.tensor(labels, dtype=torch.float)
def __len__(self):
return len(self.labels)
def __getitem__(self, index):
return self.features[index], self.labels[index]
# In[1]:
class struc_var:
def __init__(self,
id,
ref_name,
sv_type,
sv_pos,
sv_stop,
length,
gt,
wrong_len,
ref_len,
alt_len,
sample,
ac,
af=0):
self.idx = str(sample) + "_" + str(id)
self.ref_name = ref_name
self.sv_pos = sv_pos
self.sv_stop = sv_stop
self.sv_type = sv_type
self.length = length
self.gt = gt
self.wrong_len = wrong_len
self.ref_len = ref_len
self.alt_len = alt_len
self.sample = sample
self.id = id
self.ac = ac
self.af = af
self.valid = None
self.ttmars_valid = None
def print_info(self):
print(self.idx, self.ref_name, self.sv_pos, self.sv_stop, self.sv_type, self.length, self.gt, self.ac, self.af, self.valid, self.ttmars_valid)
# In[ ]:
# In[13]:
# Testing function
def test_model(model, test_loader):
model.eval()
correct = 0
total = 0
with torch.no_grad():
for input_seq, labels in test_loader:
# put data to GPU
input_seq = input_seq.cuda()
labels = labels.cuda()
outputs = model(input_seq)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
return accuracy
# In[2]:
# filter to select sv
def filters(sv, sv_type, if_pass_only, sv_len):
#type filter
if sv_type not in valid_types:
return True
#PASS filter
if if_pass_only:
if 'PASS' not in sv.filter.keys():
return True
chr_name = sv.chrom
#chr filter
if chr_name not in chr_list:
return True
#len filter
if sv_len < min_len or sv_len > max_len:
return True
return False
# In[2]:
# store input bed file into a list
def input_bed(bed_file):
f = open(bed_file, 'r')
lines = []
for line in f:
# print(line.split())
lines.append(line.split())
# close the file
f.close()
return lines
###########################################################################s
#
# Function to get soft-clipping, insert-size, and coverage.
#
def get_sc_ins_cov(bam, ref_name, ref_start, ref_end):
sc_stride = 25
refLen = ref_end - ref_start
nBins = int(refLen / 25)
if refLen % 25 != 0:
nBins +=1
sc_ratio=0.2
scBins = np.zeros(shape=nBins, dtype=int)
insertLen = np.zeros(shape=nBins, dtype=int)
insertCount= np.zeros(shape=nBins, dtype=int)
counter= [0] * refLen
for read in bam.fetch(ref_name, ref_start, ref_end):
cigar = read.cigartuples
#not many reads are bad
if not cigar:
continue
# Handle the coverage counter.
alnStart=read.reference_start
alnEnd = read.reference_end
if alnStart < ref_start:
counter[0] +=1
else:
counter[alnStart-ref_start]+=1
if alnEnd < ref_end:
counter[alnEnd - ref_start] -=1
#discard if hard clipped
try:
if cigar[0][0] == 5:
cigar.pop(0)
if len(cigar) > 0 and cigar[-1] == 5:
cigar.pop()
except:
continue
readLen = read.query_length
if alnStart >= ref_start and len(cigar) > 0 and cigar[0][0] == 4 and cigar[0][1] / readLen > sc_ratio:
if alnStart >= ref_start:
startBin = int((alnStart - ref_start) / sc_stride)
scBins[startBin] +=1
if alnEnd < ref_end and len(cigar) > 1 and cigar[-1][0] == 4 and cigar[-1][1] / readLen > sc_ratio:
endBin = int((alnEnd - ref_start) / sc_stride)
if endBin > len(scBins):
print("ERROR SETTING BIN")
scBins[endBin] +=1
insert_size = abs(read.template_length) # Use abs to ensure the size is positive
startBin = int((alnStart - ref_start)/sc_stride)
endBin = int((alnStart - ref_start)/sc_stride)
for b in range(startBin, endBin+1):
insertLen[b] += insert_size
insertCount[b] += 1
sv_sc = np.zeros(shape = (ref_end - ref_start), dtype=int)
sv_insert = np.zeros(shape = (ref_end - ref_start), dtype=int)
for i in range(ref_start, ref_end):
sv_sc[i-ref_start] = scBins[ int(( i - ref_start) / sc_stride)]
insertBin = int((i - ref_start) / sc_stride)
if insertCount[insertBin] > 0:
sv_insert[i-ref_start] = int(insertLen[b] / insertCount[b])
else:
sv_insert[i-ref_start] = 0
sv_sc = sv_sc.reshape(sv_sc.shape[0])
sv_sc = torch.tensor(sv_sc)
sv_insert=sv_insert.reshape(sv_insert.shape[0])
sv_insert=torch.tensor(sv_insert)
cov = np.zeros(shape = (ref_end - ref_start), dtype=int)
curCov=0
for c in range(0,len(counter)):
curCov += counter[c]
cov[c] = curCov
cov = torch.tensor(cov)
return sv_sc, sv_insert, cov
###########################################################################
#return a simulated cn with a random locus and length
def simu_fp_cn(chr_len, min_len, max_len):
rand_chr = random.randint(0, 21)
rand_len = random.randint(min_len, max_len)
# rand_len = int(rand_len // 1000 * 1000)
chr_len = chr_len[rand_chr]
rand_start_raw = random.randint(100 * rand_len, chr_len - 100 * rand_len)
rand_start = round(rand_start_raw / 100) * 100
return ['chr' + str(rand_chr + 1), str(rand_start), str(rand_start + rand_len)]