-
Notifications
You must be signed in to change notification settings - Fork 2
/
pyalign.py
1662 lines (1203 loc) · 56.7 KB
/
pyalign.py
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
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pysam
from scipy.sparse import coo_matrix
import time
import numpy as np
import tensorflow as tf
import pysam
import matplotlib.pyplot as plt
def allocation(cigartuples, posinref, readarray, qualityarray, start, end):
posinread = 0
padinsertinfo = []
softclipinfo = []
cigararray = np.array(-1)
itemcount = 0
slicestart = 0
reachstart = False
reachend = False
softclippresent = False
softclipcount = 0
totalcount = readarray.shape[0]
if(posinref <= start):
itemcount = -1
for item in cigartuples:
itemcount = itemcount + 1
if(item[0] in [0, 2, 7, 8]):
if(posinref + item[1] > start): # Meet start. Slice required.
#print('front early stopping')
#print('posinref is', posinref)
#cigararray = np.append(cigararray, np.ones(posinref + item[1] - start) * item[0])
cigartuples[itemcount] = [item[0], int(posinref + item[1] - start)]
#print(item[1])
#print('push in cigararray ', cigartuples[itemcount])
if(item[0] in [0, 7, 8]): # For reference match
slicestart = posinread + start - posinref
posinread = posinread + start - posinref
posinref = start
else: # For deletion
slicestart = posinread
posinref = start
reachstart = True
break
if(item[0] in [0, 7, 8]):
posinread = posinread + item[1]
posinref = posinref + item[1]
else: # For deletion
posinref = posinref + item[1]
continue
if(item[0] in [1, 4]):
posinread = posinread + item[1]
if(item[0] == 4):
softclippresent = True
softclipcount = softclipcount + item[1]
continue
if(item[0] == 5):
softclippresent = True
softclipcount = softclipcount + item[1]
totalcount = totalcount + item[1]
continue
print(str(item[0]),' CIGAR TAG DONT SUPPORT ')
return None
else:
if(posinref >= end):
return None, np.ones(int(end - start)) * 6, np.column_stack((np.arange(start, end).reshape(int(end - start), 1), np.zeros((int(end - start), 1)))), np.ones(int(end - start)).reshape(int(end - start), 1) * 0
else:
readfrontpadding = np.column_stack((np.arange(start, posinref).reshape(int(posinref - start), 1), np.zeros((int(posinref - start), 1))))
readarray = np.row_stack((readfrontpadding, readarray))
qualityarray = np.row_stack((np.zeros((int(posinref - start), 1)), qualityarray))
cigararray = np.ones(int(posinref - start + 1)) * 6 # add 1 to deal with last slice
posinread = posinread + posinref - start
reachstart = True
if(reachstart == False):
return None, np.ones(int(end - start)) * 6, np.column_stack((np.arange(start, end).reshape(int(end - start), 1), np.zeros((int(end - start), 1)))), np.ones(int(end - start)).reshape(int(end - start), 1) * 0
#print('posinref is', posinref)
#print('read position is ', readarray[slicestart: slicestart +10])
if(posinref < end):
usefront = False
usetail = True
locincigartuples = 0
cliploc = []
for item in cigartuples[itemcount:]:
locincigartuples = locincigartuples + 1
#print('current cigar is ', item, 'posinref is ', posinref, 'posinread is ', posinread, 'start is ', start, 'end is ', end)
#For reference match: posinref is match part first base
if(item[0] in [0, 7, 8]):
usefront = True
if(end <= item[1] + posinref):
#print('posinref, end ', posinref, end)
cigararray = np.append(cigararray, np.ones(end - posinref) * item[0])
readarray = readarray[: posinread + end - posinref]
qualityarray = qualityarray[: posinread + end - posinref]
posinref = end
break
else:
cigararray = np.append(cigararray, np.ones(item[1]) * item[0])
posinref = posinref + item[1]
posinread = posinread + item[1]
usefront = True
continue
#For insertion
if(item[0] == 1):
cigararray = np.append(cigararray, np.ones(item[1]) * item[0])
posinread = posinread + item[1]
padinsertinfo.append([int(posinref - 1), int(item[1])])
continue
if(item[0] == 2):
usefront = True
if(end <= item[1] + posinref):
#print('del posinref, end ', posinref, end)
cigararray = np.append(cigararray, np.ones(end - posinref) * item[0])
readarray = np.row_stack((readarray[: posinread], np.column_stack((np.arange(posinref, end).reshape(end - posinref, 1), np.zeros(end - posinref).reshape(end - posinref, 1)))))
qualityarray = np.row_stack((qualityarray[: posinread], np.zeros(end - posinref).reshape(end - posinref, 1)))
posinref = end
break
else: #Not yet. Following parameter need update: posinref
cigararray = np.append(cigararray, np.ones(item[1]) * item[0])
paddelarray = np.column_stack((np.arange(posinref, posinref + item[1]).reshape(item[1], 1), np.zeros(item[1]).reshape(item[1], 1)))
#print(paddelarray.shape)
readarray = np.row_stack((np.row_stack((readarray[:posinread], paddelarray)), readarray[posinread:]))
qualityarray = np.row_stack((qualityarray[: posinread], np.row_stack((np.zeros(item[1]).reshape(item[1], 1), qualityarray[posinread: ]))))
posinref = posinref + item[1]
posinread = posinread + item[1]
usefront = True
continue
#For soft clip: posinref is first base follow with this softclip part
if(item[0] == 4): # We have not meet the end. Following parameter need update: posinread.
softcigartmp = np.ones(item[1]) * item[0]
if(locincigartuples == len(cigartuples[itemcount:])):
usetail = False
else:
usetail = False
for cigarinfo in cigartuples[itemcount + locincigartuples:]:
if(cigarinfo[0] in [0, 2, 7, 8]):
usetail = True
if(usefront == True and usetail == True):
softclipinfo.append([[int(posinref - 1), int(posinref)], readarray[posinread: posinread + item[1], 1]])
softcigartmp[0], softcigartmp[-1] = softcigartmp[0] + 0.1, softcigartmp[-1] + 0.1
cliploc.append(int(posinref - 1))
cliploc.append(int(posinref))
elif(usefront == True):
softclipinfo.append([[int(posinref - 1)], readarray[posinread: posinread + item[1], 1]])
softcigartmp[0] = softcigartmp[0] + 0.1
cliploc.append(int(posinref - 1))
else:
softclipinfo.append([[-int(posinref)], readarray[posinread: posinread + item[1], 1]])
softcigartmp[-1] = softcigartmp[-1] + 0.1
cliploc.append(int(posinref))
cigararray = np.append(cigararray, softcigartmp)
posinread = posinread + item[1]
padinsertinfo.append([int(posinref - 1), int(item[1])])
softclippresent = True
softclipcount = softclipcount + item[1]
continue
if(item[0] == 5): # Pass the hardclip cigar string.
totalcount = totalcount + item[1]
softclippresent = True
softclipcount = softclipcount + item[1]
if(locincigartuples == len(cigartuples[itemcount:])):
usetail = False
else:
usetail = False
for cigarinfo in cigartuples[itemcount + locincigartuples:]:
if(cigarinfo[0] in [0, 2, 7, 8]):
usetail = True
hardlen = 1
tmppadnone = np.array([[None]])
if(usefront and usetail):
hardlen = 2
tmppadnone = np.array([[None], [None]])
cliploc.append(int(posinref - 1))
cliploc.append(int(posinref))
elif(usefront == True):
cliploc.append(int(posinref - 1))
else:
cliploc.append(int(posinref))
cigararray = np.append(cigararray, np.ones(hardlen) * item[0])
padinsertinfo.append([int(posinref - 1), hardlen])
paddelarray = np.column_stack((tmppadnone, np.zeros(hardlen).reshape(hardlen, 1)))
#print(paddelarray.shape)
if(posinread == 0):
readarray = np.row_stack((paddelarray, readarray[posinread:]))
qualityarray = np.row_stack((np.zeros(hardlen).reshape(hardlen, 1), qualityarray[posinread: ]))
elif(posinread == readarray.shape[0]):
readarray = np.row_stack((readarray, paddelarray))
qualityarray = np.row_stack((qualityarray, np.zeros(hardlen).reshape(hardlen, 1)))
else:
readarray = np.row_stack((np.row_stack((readarray[:posinread], paddelarray)), readarray[posinread:]))
qualityarray = np.row_stack((qualityarray[: posinread], np.row_stack((np.zeros(hardlen).reshape(hardlen, 1), qualityarray[posinread: ]))))
posinread = posinread + hardlen
continue
print(str(item[0]),' CIGAR TAG DONT SUPPORT ')
return None
#readarray = readarray[slicestart: posinread + end - posinref]
#print(cigarinfodict)
if(posinref < end): #Need padding.
readrearpadding = np.column_stack((np.arange(posinref, end).reshape(end - posinref, 1), np.zeros(end - posinref).reshape(end - posinref, 1)))
readarray = np.row_stack((readarray, readrearpadding))
qualityarray = np.row_stack((qualityarray, np.zeros(end - posinref).reshape(end - posinref, 1)))
cigararray = np.append(cigararray, np.ones(end - posinref) * 6)
return np.array(padinsertinfo), cigararray[1:], readarray[slicestart:], qualityarray[slicestart:], [softclippresent, softclipcount / totalcount , softclipinfo, cliploc]
def paddel(AlignedSegment, start, end):
grp = np.array(AlignedSegment.get_reference_positions(True))#[AlignedSegment.query_alignment_start: AlignedSegment.query_alignment_end]
grp = grp.reshape(grp.size, 1)
read = pd.DataFrame(list(AlignedSegment.query_sequence)).replace({'A': 10, 'T': 15, 'G': 20, 'C': 25}).values.reshape(grp.size,1)
readarray = np.column_stack((grp, read))
pos = 0
i = 0
delpos = 0
'''print(readarray.T[0].tolist())
print(readarray.T[1].tolist())'''
#print(grp[-10:].T)
cigartuples = AlignedSegment.cigartuples
#print(grp[-cigartuples[-1][1] - 10:].T)
if(cigartuples == None):
print('The alignment does not give CIGAR string')
return None
while(cigartuples[i][0] not in [0, 7, 8]): # Get TRUE reference start location
if(cigartuples[i][0] != 5):
pos = cigartuples[i][1] + pos
if(cigartuples[i][0] == 2):
delpos = cigartuples[i][1] + delpos
i = i + 1
'''if(grp[0] == None):#test for insertion or softclip on begin
tmpbase = np.array([readarray[0][0] - 1, 0]).reshape(1,2)
readarray = np.row_stack((tmpbase, readarray))'''
#print('origin readarray is ', readarray.T.tolist())
qqarray = np.array(AlignedSegment.query_qualities)
if(qqarray.size == 1):
qqarray = np.zeros((readarray.shape[0], 1))
else:
qqarray = qqarray.reshape((readarray.shape[0], 1))
iarray, cigararray, readarray, qualityarray, softclipinfo = allocation(cigartuples, int(grp[pos] - delpos), readarray, qqarray, start, end)
if(softclipinfo[0] == True):
softclipinfo.append(read)
else:
softclipinfo.append([])
return readarray, iarray, cigararray, qualityarray, softclipinfo
def dropselectcigartag(pcigararray, selectedtag, refseq, filter = False, preadarray = None, cutvalue = 1, keepfrontsoftclip = True):
for tag in selectedtag:
try:
outputset = set(np.nonzero((pcigararray == tag).sum(axis = 0) == 0)[0].tolist()) & outputset
except:
outputset = set(np.nonzero((pcigararray == tag).sum(axis = 0) == 0)[0].tolist())
if(filter == True):
outputset = set(np.nonzero((preadarray > 0).sum(axis = 0, keepdims = True) > (cutvalue))[1].tolist()) & outputset
if(keepfrontsoftclip):
outputset = set(np.nonzero((pcigararray == 4.1).sum(axis = 0) != 0)[0].tolist()) & outputset
outputset = set(np.nonzero(refseq > -1)[0].tolist()) | outputset
return np.sort(np.array(list(outputset)))
def myshow(preadarray, pcigararray, qualityarray, refseq, seqbase, excludelist = [1, 4, 4.1], includecagtag = [2], filter = False, cutvalue = 1, maxdot = 200, softread = [], showpic = False, minrow = 18, maxrow = 18):
#print(preadarray.shape, pcigararray.shape, qualityarray.shape)
pltsoft = False
if(len(softread) > 0):
psoftarray = (np.array(softread[:,1]).reshape(preadarray.shape[0], 1).astype('float32') * (preadarray > 0).astype('float32'))
pltsoft = True
if(len(excludelist) > 0):
columnkeeped = dropselectcigartag(pcigararray, excludelist, refseq, filter, preadarray, cutvalue)
preadarray = preadarray[:, columnkeeped]
qualityarray = qualityarray[:, columnkeeped]
if(pltsoft == True):
psoftarray = psoftarray[:, columnkeeped]
slicedpcigararray = pcigararray[:, columnkeeped]
for cigartag in includecagtag:
try:
spotarray = spotarray + (slicedpcigararray == cigartag) * cigartag
except:
spotarray = (slicedpcigararray == cigartag) * cigartag
else:
slicedpcigararray = pcigararray
for cigartag in includecagtag:
try:
spotarray = spotarray + (slicedpcigararray == cigartag) * cigartag
except:
spotarray = (slicedpcigararray == cigartag) * cigartag
cspotarray = spotarray[:,:200][np.argsort(spotarray[:200].sum(axis = 1))[::-1]]
for loc in range(200, spotarray.shape[1], 200):
tmp = spotarray[:,loc:loc+200][np.argsort(spotarray[:,loc:loc+200].sum(axis = 1))[::-1]]
cspotarray = np.column_stack((cspotarray, tmp))
spotarray=cspotarray
if(preadarray.shape[0] < minrow):
pt = [preadarray, spotarray, psoftarray, qualityarray]
padrownumber = minrow - preadarray.shape[0]
column_number = preadarray.shape[1]
for locinpt in range(4):
pt[locinpt] = np.row_stack((pt[locinpt], np.zeros((padrownumber, column_number))))
preadarray, spotarray, psoftarray, qualityarray = pt[0], pt[1], pt[2], pt[3]
if(preadarray.shape[0] > maxrow and showpic == False):
preadarray, spotarray, psoftarray, qualityarray = preadarray[:maxrow], spotarray[:maxrow], psoftarray[:maxrow], qualityarray[:maxrow]
cliparray = np.ones((preadarray.shape[0], 1)) * seqbase
if(showpic):
loc = 0
print('Read sequence')
plt.matshow(preadarray)
plt.show()
else:
timestep = 100
fm = (spotarray>0).astype('float32').T
fm = fm.reshape(fm.size//(200 * 18), 200, 18, 1)
if(fm.shape[0]<timestep):
return np.array(0), fm.reshape(1, fm.shape[0], 200, 18, 1)
tail = fm.shape[0]%timestep
if(tail == 0):
return fm.reshape(fm.shape[0]//timestep, timestep, 200, 18, 1), np.array(0)
topdata, taildata = fm[:-tail], fm[-tail:].reshape(1, tail, 200, 18, 1)
return topdata.reshape(topdata.shape[0]//timestep, timestep, 200, 18, 1), taildata
def pileupf(bamfile, contig, start, end, droplq = False, dropvalue = 0.8):
window_size = 200
samplelocation = start + np.column_stack((np.arange(0, window_size * (int((end - start - 1) / window_size) + 1), window_size).reshape((int(( end - start - 1) / window_size) + 1), 1), np.arange(0, window_size * (int((end - start - 1) / window_size) + 1), window_size).reshape((int((end - start - 1) / window_size) + 1), 1) + window_size))
end = samplelocation[-1, 1]
totalstarttime = time.time()
locationlist = []
readlist = []
insertlist = []
insertinfo = dict()
keylist = []
cigarlist = []
qualitylist = []
softcliplist = []
debug = []
depth = 0
paddeltime = 0
fetchtime = time.time()
seqbase = np.zeros((1, end - start)).astype('float32')
overlap = False
for AlignedSegment in bamfile.fetch(contig, start, end):
#debug.append(AlignedSegment)
if(AlignedSegment.reference_start <= start):
frontloc = 0
whichstart = start
else:
frontloc = AlignedSegment.reference_start - start
whichstart = AlignedSegment.reference_start
if(AlignedSegment.reference_end >= (end - 1)):
tailloc = end - start - 1
else:
tailloc = AlignedSegment.reference_end - start
paddelstarttime = time.time()
read, iarray, cigararray, qualityarray, softclipinfo = paddel(AlignedSegment, start, end)
ratio = softclipinfo[1]
tmp = seqbase[:,frontloc: tailloc + 1] + ratio
for cclip in set(softclipinfo[3]):
tmp[:,cclip - whichstart] = tmp[:,cclip - whichstart] + ratio
fillblank = tmp.mean()
seqbase[:,frontloc: tailloc + 1] = (np.column_stack((np.array([[fillblank]]), tmp))[:,:-1] + tmp + np.column_stack((tmp, np.array([[fillblank]])))[:,1:])/3
if(droplq and softclipinfo[1] > dropvalue):
continue
overlap = True
paddeltime = - paddelstarttime + time.time() + paddeltime
locationlist.append(read[:,0])
readlist.append(np.array(read[:,1]).astype('float32'))
insertlist.append(iarray)
cigarlist.append(cigararray.astype('float32'))
qualitylist.append(qualityarray.flatten().astype('float32'))
softcliplist.append(softclipinfo)
depth = depth + 1
'''print(read.shape)
print(cigararray.shape)'''
if(type(iarray) != np.ndarray):
continue
for item in iarray:
cloc = item[0]
if((item[0]) in insertinfo):
if(cloc == lastloc):
insertinfo[item[0]] = insertinfo[item[0]] + item[1]
else:
insertinfo[item[0]] = max(insertinfo[item[0]], int(item[1]))
else:
insertinfo[item[0]] = item[1]
keylist.append(item[0])
lastloc = cloc
#print('fetch time = ', time.time() - fetchtime, time.time() - totalstarttime)
keylist = np.sort(np.array(keylist))
#print(keylist)
'''print(readlist)
print()
print(insertinfo)'''
#print(insertinfo)
#readposlist = [0 for i in range(len(readlist))]
refseq = np.arange(start, end)
bias = 0
for key in keylist:
if(key == (end - 1)):
print('end in insertioninfo')
return 0
insert = - np.ones(insertinfo[key])
refseq = np.append(np.append(refseq[:key+1 + bias-start], insert), refseq[key+1+bias-start: ])
bias = bias + insertinfo[key]
if(overlap == False):
return np.zeros((1, end - start)), np.ones((1, end - start)) * 6, np.zeros((1, end - start)), refseq, np.array([[False, 0]]), seqbase
readcount = 0
state = False
readlisttime = time.time()
cc = 0
if(True):
pallarray = 'None'
for read in readlist:
refloc = start
locinread = 0
insertcount = 0
parray = 'None'
for key in keylist:
#print(insertlist[readcount][insertcount])
while(True):
slicelength = key + 1 - refloc
refloc = refloc + slicelength
insertsizeofrfortkey = 0
insertpresentonkey = False
if(insertlist[readcount].shape[0] > insertcount and key == insertlist[readcount][insertcount][0]):
onreadinsert = insertlist[readcount][insertcount][1]
insertpresentonkey = True
while(insertlist[readcount].shape[0] > (insertcount + 1) and key == insertlist[readcount][insertcount + 1][0]):
insertcount = insertcount + 1
onreadinsert = onreadinsert + insertlist[readcount][insertcount][1]
slicelength = slicelength + onreadinsert
tmpparray = np.array([read[locinread: locinread + slicelength], cigarlist[readcount][locinread: locinread + slicelength], qualitylist[readcount][locinread: locinread + slicelength]])
locinread = locinread + slicelength
if(insertpresentonkey):
remainlengh = insertinfo[key] - onreadinsert
insertcount = insertcount + 1
if(remainlengh > 0):
tmpparray = np.column_stack((tmpparray, np.ones((3, remainlengh)) * np.array([[0.], [6.], [0.]])))
else:
tmpparray = np.column_stack((tmpparray, np.ones((3, insertinfo[key])) * np.array([[0.], [6.], [0.]])))
try:
parray = np.column_stack((parray, tmpparray))
except:
parray = tmpparray
break
if(locinread != len(read) and len(keylist) > 0):
parray = np.column_stack((parray, np.array([read[locinread: ], cigarlist[readcount][locinread: ], qualitylist[readcount][locinread: ]])))
#print()
else:
parray = np.array([read[locinread: ], cigarlist[readcount][locinread: ], qualitylist[readcount][locinread: ]])
readcount = readcount + 1
if(state):
pallarray = np.column_stack((pallarray, parray))
#print(parray.shape)
else:
pallarray = parray
readlength = parray.shape[1]
state = True
#print('readlisttime',time.time() - readlisttime)
#print(time.time() - totalstarttime, paddeltime)
return pallarray[0].reshape(int(pallarray.shape[1] / readlength), readlength), pallarray[1].reshape(int(pallarray.shape[1] / readlength), readlength), pallarray[2].reshape(int(pallarray.shape[1] / readlength), readlength), refseq, np.array(softcliplist, dtype = 'object'), seqbase
def fx(alist, blist, clist, rowcount):
for b in blist:
alist.append(b)
clist.append(rowcount)
def chioce_top18(tensor):
batch_size, window_size, rowcount = tensor.shape[0], tensor.shape[1], tensor.shape[2]
tensor = tf.concat([tensor, tf.zeros([batch_size, window_size, 18])], axis = 2)
return tf.reshape(tf.gather(tensor, tf.argsort(tf.reduce_sum(tensor, 1, keepdims = True), axis = 2), axis=2, batch_dims=1)[:,:,:,-18:], [tensor.shape[0], tensor.shape[1], 18, 1])
#position SIZE cluster
from numba.pycc import CC
from numba import jit, njit
from numba.typed import List
import numpy as np
cc = CC('mamnet')
@njit
def unpacklist(typed_result):
return [i[0] for i in typed_result]
@njit
def unpacklist_a(typed_result):
return [i for i in typed_result]
@njit
def combinelist(listoflist):#require same type
combinelist = listoflist[0]
for onelist in listoflist[1:]:
for item in onelist:
combinelist.append(item)
return combinelist
@njit('int64(unicode_type)')
def str_to_int(s):
final_index, result = len(s) - 1, 0
for i,v in enumerate(s):
result += (ord(v) - 48) * (10 ** (final_index - i))
return result
@njit('ListType(int64)(unicode_type, unicode_type)')
def c_ssee(cigar, refstartstr):#tested
zero = ord('0')
INSsyb = ord('I') - zero
SOFTsyb = ord('S') - zero
HARDsyb = ord('H') - zero
PADsyb = ord('P') - zero
DELsyb = ord('D') - zero
SKIPsyb = ord('N') - zero
delsyb = ord('^') - zero
readloc = 0
refloc = str_to_int(refstartstr)
meetstart = False
typed_cigar = List()
[typed_cigar.append(ord(item) - zero) for item in cigar]
number = 0
for item in typed_cigar:
if(item < 10):
number = number * 10 + item
else:
if(item != INSsyb and item != SOFTsyb and item != HARDsyb and item != PADsyb):
if(meetstart == False):
meetstart = True
refstart = refloc
readstart = readloc
if(item != DELsyb and item != SKIPsyb):
readloc += int(number)
readend = readloc
refloc += int(number)
number = 0
else:
if(item == INSsyb or item == SOFTsyb):
readloc += int(number)
number = 0
return List([refstart, refloc, readstart, readend])
@cc.export('g_d', 'float64[:,:](ListType(unicode_type), ListType(unicode_type), ListType(ListType(int64)), int64, int64[:], int64)')
def fast_info_P(mdtaglist, cigarlist, corposlist, end, qualityarray, maxcountread):
# 0 1 2 3 4 5 6 7 8
info = np.zeros((end, 9))#MISMATCHCOUNT, DELETIONCOUNT, SOFTHARDCOUNT, INSERTIONCOUNT, INSERTIONMEAN, INSERTIONMAX, DELETIONMEAN, DELETIONMAX, DEPTH
zero = ord('0')
INSsyb = ord('I') - zero
SOFTsyb = ord('S') - zero
HARDsyb = ord('H') - zero
PADsyb = ord('P') - zero
DELsyb = ord('D') - zero
delsyb = ord('^') - zero
for readcount in qualityarray:
cigar = cigarlist[readcount]
loc = corposlist[readcount][0]
weight = 1.
typed_cigar = List()
[typed_cigar.append(ord(item) - zero) for item in cigar]
number = 0.
for item in typed_cigar:
if(item < 10):
number = number * 10. + item
else:
if(item != INSsyb and item != SOFTsyb and item != HARDsyb and item != PADsyb):
if(loc >= 0 and info[loc][8] < maxcountread and item == DELsyb and loc < end):
info[loc][6] += number
info[loc][7] = max(info[loc][7], number)
loc += int(number)
number = 0.
if(loc >= end):
break
else:
if(loc >= 0 and info[loc][8] < maxcountread):
if(item == INSsyb):
info[loc][4] += number
info[loc][5] = max(info[loc][5], number)
info[loc][3] += 1.
number = 0.
continue
if(item == SOFTsyb or item == HARDsyb):
info[loc][2] += 1.
number = 0.
continue
number = 0.
else:
number = 0.
typed_mdtag = List()
[typed_mdtag.append(ord(item) - zero) for item in mdtaglist[readcount]]
matchnumber = 0
loc = corposlist[readcount][0]
indeletion = False
inmatch = False
for item in typed_mdtag:
if(item < 10):
matchnumber = matchnumber * 10 + item
indeletion = False
inmatch = True
continue
if(inmatch):
loc += matchnumber
#print(matchnumber)
matchnumber = 0
inmatch = False
if(item == delsyb):
indeletion = True
continue
if(loc >= end):
break
if(loc >= 0 and info[loc][8] < maxcountread):
if(indeletion == False):
info[loc][0] += 1.
else:
info[loc][1] += 1.
loc += 1
if(inmatch):
loc += matchnumber
info[max(corposlist[readcount][0], 0): min(corposlist[readcount][1], end), 8:9] += 1.
info[:,4:5] = info[:,4:5] / (info[:,3:4] + 1e-20)
info[:,6:7] = info[:,6:7] / (info[:,1:2] + 1e-20)
#info[:,0:4] = info[:,0:4] / (info[:,8:9]+ 1e-20)
return info
@njit
def cluster_fn(num_total_indelinfo):
thorhold = 200
order = np.argsort(np.array(unpacklist(num_total_indelinfo)))
numinfo = num_total_indelinfo[order[0]]
cluster_result = List([numinfo[:2]])
cluster_readcount = List([1])
cluster_split_id = List()
prestart = numinfo[0]
pos_cache = List([numinfo[0]])
size_cache = List([numinfo[1]])
split_id_cache = List([numinfo[2]])
cluster_count = 0
C_skipedrec = List([numinfo])#transfer all data to P_skipedrec when initial new cluster
P_skipedrec = List([numinfo])
for locationinorder in order[1:]:
numinfo = num_total_indelinfo[locationinorder]
numinfoused = False
while(True):
if(numinfoused == False):
numinfoused = True
else:
if(len(P_skipedrec) == 1):
break
else:
numinfo = P_skipedrec.pop(1)
if((prestart+thorhold)>= numinfo[0]): #add in current cluster
if((numinfo[1] * size_cache[-1]) > 0):
if((min(abs(size_cache[-1]), abs(numinfo[1])) / max(abs(size_cache[-1]), abs(numinfo[1]))) > 0.7):
pos_cache.append(numinfo[0])
size_cache.append(numinfo[1])
cluster_readcount[-1] += 1
if(numinfo[2] != 0):
split_id_cache.append(numinfo[2])
prestart = numinfo[0]
continue
C_skipedrec.append(numinfo)
else:#create new cluster
cluster_result[-1][0] = pos_cache[cluster_readcount[-1]//2]
size_cache.sort()
cluster_result[-1][1] = size_cache[cluster_readcount[-1]//2]
cluster_split_id.append(split_id_cache)
while(len(C_skipedrec) != 1):
P_skipedrec.append(C_skipedrec.pop(1))
if(len(P_skipedrec) != 1):
P_skipedrec.append(numinfo)
numinfo = P_skipedrec.pop(1)
pos_cache = List([numinfo[0]])
size_cache = List([numinfo[1]])
split_id_cache = List([numinfo[2]])
cluster_result.append(numinfo[:2])
cluster_count += 1
cluster_readcount.append(1)
prestart = numinfo[0]
if(len(C_skipedrec) !=1):
while(len(C_skipedrec) != 1):
P_skipedrec.append(C_skipedrec.pop(1))
while(True):
numinfovaild = False
if(len(P_skipedrec) != 1):
numinfo = P_skipedrec.pop(1)
numinfovaild = True
else:
if(len(C_skipedrec) == 1):
break
if(((prestart+thorhold)>= numinfo[0]) and (numinfovaild == True)): #add in current cluster
if((numinfo[1] * size_cache[-1]) > 0):
if((min(abs(size_cache[-1]), abs(numinfo[1])) / max(abs(size_cache[-1]), abs(numinfo[1]))) > 0.7):
pos_cache.append(numinfo[0])
size_cache.append(numinfo[1])
cluster_readcount[-1] += 1
if(numinfo[2] != 0):
split_id_cache.append(numinfo[2])
prestart = numinfo[0]
continue
C_skipedrec.append(numinfo)
else:#create new cluster
cluster_result[-1][0] = pos_cache[cluster_readcount[-1]//2]
size_cache.sort()
cluster_result[-1][1] = size_cache[cluster_readcount[-1]//2]
while(len(C_skipedrec) != 1):
P_skipedrec.append(C_skipedrec.pop(1))
if(len(P_skipedrec) != 1):
if(numinfovaild == True):
P_skipedrec.append(numinfo)
numinfo = P_skipedrec.pop(1)
numinfovaild = True
if(numinfovaild == True):
pos_cache = List([numinfo[0]])
size_cache = List([numinfo[1]])
cluster_split_id.append(split_id_cache)
split_id_cache = List([numinfo[2]])
cluster_result.append(numinfo[:2])
cluster_count += 1
cluster_readcount.append(1)
prestart = numinfo[0]
cluster_result[-1][0] = pos_cache[cluster_readcount[-1]//2]
size_cache.sort()
cluster_result[-1][1] = size_cache[cluster_readcount[-1]//2]
cluster_split_id.append(split_id_cache)
confi_order = np.argsort(np.array(unpacklist_a(cluster_readcount)))
argloc = 1
used_split_set = set()
while(argloc<=len(confi_order)):
loc = confi_order[-argloc]
for splitid in cluster_split_id[loc]:
if(splitid == 0):
continue
else:
if(splitid in used_split_set):
cluster_readcount[loc] -= 1
else:
used_split_set.add(splitid)
argloc += 1
return cluster_result, cluster_readcount
@cc.export('c_cw', 'Tuple((float64[:,:], ListType(ListType(int64)), ListType(int64)))(ListType(unicode_type), ListType(unicode_type), ListType(ListType(int64)), int64, int64, ListType(ListType(unicode_type)), ListType(ListType(int64)), unicode_type, int64[:], int64)')
def c_c_withsa(mdtaglist, cigarlist, corposlist, tstart, end, primaryreadidcontigandsa, primaryssee, svtype, qualityarray, maxcountread):