-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathPEPPAN.py
executable file
·1942 lines (1768 loc) · 95.2 KB
/
PEPPAN.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
#!/usr/bin/env python
import os, re, sys, shlex, ete3, tempfile, hashlib, shutil
import subprocess, numpy as np, pandas as pd, numba as nb
from operator import itemgetter
import zipfile, io
from multiprocessing import Pool, Manager, Process
from collections import defaultdict
try:
from modules.configure import externals, logger, rc, transeq, readFasta, uopen, xrange, asc2int
from modules.clust import getClust
from modules.uberBlast import uberBlast
except:
from .modules.configure import externals, logger, rc, transeq, readFasta, uopen, xrange, asc2int
from .modules.clust import getClust
from .modules.uberBlast import uberBlast
params = dict(
ml = '{fasttree} -nt -gtr -pseudo {0}',
nj = '{rapidnj} -i fa -t d {0}',
)
def in1d(arr1, arr2, invert=False) :
darr2 = set(arr2)
res = np.array([n in darr2 for n in np.array(arr1).flatten()])
return ~res if invert else res
class MapBsn(object) :
def __init__(self, fname, mode='r') :
self.fname = fname
self.mode = mode
self.conn = zipfile.ZipFile(self.fname, mode=mode, compression=zipfile.ZIP_DEFLATED,allowZip64=True)
self.namelist = set(self.conn.namelist())
def __enter__(self) :
return self
def __exit__(self, type, value, traceback) :
self.conn.close()
def get(self, key, default=[]) :
key = str(key)
if self.exists(key) :
buf = io.BytesIO(self.conn.read(key))
return np.lib.npyio.format.read_array(buf, allow_pickle=True)
else :
return default
def __getitem__(self, key) :
return self.get(key)
def exists(self, key) :
return str(key) in self.namelist
def keys(self) :
return self.namelist
def items(self) :
for key in self.namelist :
yield key, self.get(key)
def values(self) :
for key in self.namelist :
yield self.get(key)
def delete(self, key) :
self.namelist -= {str(key)}
def delete_real(self, key) :
key = str(key)
if key in self.namelist :
self.namelist -= {key}
self.conn.close()
subprocess.Popen(['zip', '-d', self.fname, key]).wait()
self.conn = zipfile.ZipFile(self.fname, mode='w', compression=zipfile.ZIP_DEFLATED,allowZip64=True)
def pop(self, key, default=[]) :
val = self.get(key, default)
self.delete(key)
return val
def size(self) :
return len(self.namelist)
def save(self, key, val) :
key = str(key)
self.delete_real(key)
self._save(self.conn, key, val)
self.namelist |= {key}
def _save(self, db, key, val) :
buf = io.BytesIO()
np.lib.npyio.format.write_array(buf,
np.asanyarray(val),
allow_pickle=True)
db.writestr(key, buf.getvalue())
def update(self, dataset) :
newList = set([])
tmpName = self.fname[:-4] + '.tmp.npz'
tmp = zipfile.ZipFile(tmpName, mode='w', compression=zipfile.ZIP_DEFLATED,allowZip64=True)
for d in dataset :
key = str(d[0][0])
newList.add(key)
oldData = self.get(key)
data = np.vstack([oldData, d]) if len(oldData) else d
self._save(tmp, key, data)
for key in self.keys() :
if key not in newList :
data = self.get(key)
if len(data) :
newList.add(key)
self._save(tmp, key, data)
tmp.close()
self.conn.close()
self.namelist = newList
os.rename(tmpName, self.fname)
self.conn = zipfile.ZipFile(self.fname, mode='a', compression=zipfile.ZIP_DEFLATED,allowZip64=True)
def iter_readGFF(data) :
fname, feature, gtable = data
seq, cds = {}, {}
names = {}
fnames = fname.split(',')
fname = fnames[0]
fprefix = os.path.basename(fname).split('.')[0]
for fn in fnames :
with uopen(fn) as fin :
sequenceMode = False
for line in fin :
if line.startswith('#') :
continue
elif line.startswith('>') :
sequenceMode = True
name = line[1:].strip().split()[0]
cname = '{0}:{1}'.format(fprefix, name)
assert cname not in seq, logger('Error: duplicated sequence name {0}'.format(name))
seq[cname] = [fname, []]
elif sequenceMode :
seq[cname][1].extend(line.strip().split())
else :
part = line.strip().split('\t')
if len(part) > 2 :
name = re.findall(r'locus_tag=([^;]+)', part[8])
if len(name) == 0 :
parent = re.findall(r'Parent=([^;]+)', part[8])
if len(parent) and parent[0] in names :
name = names[parent[0]]
if len(name) == 0 :
name = re.findall(r'Name=([^;]+)', part[8])
if len(name) == 0 :
name = re.findall(r'ID=([^;]+)', part[8])
if part[2] == feature :
assert len(name) > 0, logger('Error: CDS has no name. {0}'.format(line))
# source_file, seqName, Start, End, Direction, hash, Sequences
gname = '{0}:{1}'.format(fprefix, name[0])
if gname not in cds :
cds[gname] = [fname, '{0}:{1}'.format(fprefix, part[0]), int(part[3]), int(part[4]), part[6], 0, [], int(part[3]), int(part[4])]
elif part[0] == cds[gname][1] and fname == cds[gname][0] :
cds[gname].extend([int(part[3]), int(part[4])])
cds[gname][3] = max(cds[gname][3], int(part[4]))
else :
ids = re.findall(r'ID=([^;]+)', part[8])
if len(ids) :
names[ids[0]] = name
for n in seq :
seq[n][1] = ''.join(seq[n][1]).upper()
for n, c in cds.items() :
try:
for i in np.arange(7, len(c), 2) :
s = seq[c[1]][1][(c[i]-1) : c[i+1]]
c[6].append(s)
c[6] = ''.join([ rc(s) for s in reversed(c[6]) ]) if c[4] == '-' else ''.join(c[6])
pcode = checkPseu(n, c[6], gtable)
if pcode :
c[5], c[6] = pcode, ''
else :
c[5] = int(hashlib.sha1(c[6].encode('utf-8')).hexdigest(), 16)
except :
c[5], c[6] = 6, ''
cds[n][:] = c[:7]
return seq, cds
def readGFF(fnames, feature, gtable) :
if not isinstance(fnames, list) : fnames = [fnames]
seq, cds = {}, {}
#for ss, cc in map(iter_readGFF, [[fn, feature, gtable] for fn in fnames]) :
for ss, cc in pool.imap_unordered(iter_readGFF, [[fn, feature, gtable] for fn in fnames]) :
seq.update(ss)
cds.update(cc)
return seq, cds
def get_similar_pairs(clust, priorities, params) :
def get_similar(bsn, ortho_pairs) :
key = tuple(sorted([bsn[0][0], bsn[0][1]]))
if key in ortho_pairs :
return
if min(int(bsn[0][13]), int(bsn[0][12])) * 20 <= max(int(bsn[0][13]), int(bsn[0][12])) :
return
matched_aa = {}
for part in bsn :
s_i, e_i, s_j, e_j = [ int(x) for x in part[6:10] ]
for s, t in re.findall(r'(\d+)([A-Z])', part[14]) :
s, frame_i, frame_j = int(s), s_i % 3, s_j % 3
if t == 'M' :
if frame_i == frame_j or 'f' in params['incompleteCDS'] :
matched_aa.update({ (s_i+x): part[2] for x in xrange( (3 - (frame_i - 1))%3, s )})
s_i += s
s_j += s
if len(matched_aa)*3 >= min(params['match_len2'], params['match_len'], params['match_len1']) and len(matched_aa)*3 >= min(params['match_prop'], params['match_prop1'], params['match_prop2']) * int(bsn[0][12]) :
ave_iden = int(np.mean(list(matched_aa.values()))*10000)
if ave_iden >= params['match_identity']*10000 :
if len(matched_aa)*3 >= min(max(params['match_len'], params['match_prop']* min(int(bsn[0][13]), int(bsn[0][12]))),
max(params['match_len1'], params['match_prop1']* min(int(bsn[0][13]), int(bsn[0][12]))),
max(params['match_len2'], params['match_prop2']* min(int(bsn[0][13]), int(bsn[0][12]))) ) :
ortho_pairs[key] = ave_iden
else :
ortho_pairs[key] = 0
return
elif t == 'I' :
s_i += s
else :
s_j += s
if params['noDiamond'] :
self_bsn = uberBlast('-r {0} -q {0} --blastn --min_id {1} --min_cov {2} -t {3} --min_ratio {4} -e 3,3 -p --gtable {5}'.format(\
clust, params['match_identity'] - 0.05, params['match_frag_len'], params['n_thread'], params['match_frag_prop'], params['gtable']).split(), pool)
else :
self_bsn = uberBlast('-r {0} -q {0} --blastn --diamond -s 1 --min_id {1} --min_cov {2} -t {3} --min_ratio {4} -e 3,3 -p --gtable {5}'.format(\
clust, params['match_identity'] - 0.05, params['match_frag_len'], params['n_thread'], params['match_frag_prop'], params['gtable']).split(), pool)
self_bsn.T[:2] = self_bsn.T[:2].astype(int)
presence, ortho_pairs = {}, {}
save = []
cluGroups = []
for part in self_bsn :
if part[0] not in presence :
presence[part[0]] = 1
elif presence[part[0]] == 0 :
continue
iden, qs, qe, ss, se, ql, sl = float(part[2]), float(part[6]), float(part[7]), float(part[8]), float(part[9]), float(part[12]), float(part[13])
if presence.get(part[1], 1) == 0 :
continue
qa = qe - qs + 1
sa = abs(se - ss) + 1
if part[0] != part[1] and iden >= params['clust_identity'] :
if ss > se or (qs%3 != ss%3 and (ql-qe)%3 == (sl-se)%3) :
if qa >= params['clust_match_prop'] * ql or sa >= params['clust_match_prop'] * sl :
ortho_pairs[tuple(sorted([part[0], part[1]]))] = -2
continue
elif ss < se and qs%3 == ss%3 and (ql-qe)%3 == (sl-se)%3 :
if ql <= sl :
if qa >= np.sqrt(params['clust_match_prop']) * sl and priorities[part[0]][0] >= priorities[part[1]][0] :
cluGroups.append([int(part[1]), int(part[0]), int(iden*10000.)])
presence[part[0]] = 0
continue
elif sa >= np.sqrt(params['clust_match_prop']) * ql and priorities[part[0]][0] <= priorities[part[1]][0] :
cluGroups.append([int(part[0]), int(part[1]), int(iden*10000.)])
presence[part[1]] = 0
continue
if ss >= se :
continue
if len(save) > 0 and np.any(save[0][:2] != part[:2]) :
if len(save) >= 50 :
presence[save[0][1]] = 0
elif save[0][0] != save[0][1] :
get_similar(save, ortho_pairs)
save = []
save.append(part)
if len(save) > 0 :
if len(save) >= 50 :
presence[save[0][1]] = 0
elif save[0][0] != save[0][1] :
get_similar(save, ortho_pairs)
toWrite = []
with uopen(params['clust'], 'r') as fin :
for line in fin :
if line.startswith('>') :
name = line[1:].strip().split()[0]
write= True if presence.get(int(name), 0) > 0 else False
if write :
toWrite.append(line)
with open(params['clust'], 'w') as fout :
for line in toWrite :
fout.write(line)
if len(cluGroups) :
clu = np.load(params['clust'].rsplit('.',1)[0] + '.npy', allow_pickle=True)
clu = np.vstack([clu, cluGroups])
clu = clu[np.argsort(-clu.T[2])]
np.save(params['clust'].rsplit('.',1)[0] + '.npy', clu)
return np.array([[k[0], k[1], v] for k, v in ortho_pairs.items() if v != 0], dtype=int)
@nb.jit('i8[:,:,:](u1[:,:], i8[:,:,:])', nopython=True)
def compare_seq(seqs, diff) :
for id in np.arange(seqs.shape[0]) :
s = seqs[id]
c = (s > 0) * (seqs[(id+1):] > 0)
n_comparable = np.sum(c, 1) + 2
n_diff = np.sum(( s != seqs[(id+1):] ) & c, 1) + 1
diff[id, id+1:, 0] = n_diff
diff[id, id+1:, 1] = n_comparable
return diff
@nb.jit('i8[:,:,:](u1[:,:], i8[:,:,:])', nopython=True)
def compare_seqX(seqs, diff) :
for id in (0, seqs.shape[0]-1) :
s = seqs[id]
c = (s > 0) * (seqs > 0)
n_comparable = np.sum(c, 1) + 2
n_diff = np.sum(( s != seqs ) & c, 1) + 1
diff[id, :, 0] = n_diff
diff[id, :, 1] = n_comparable
return diff
def decodeSeq(seqs) :
ori_seqs = np.zeros([seqs.shape[0], seqs.shape[1]*3], dtype=np.uint8)
ori_seqs[:, :seqs.shape[1]] = (seqs/25).astype(np.uint8)
ori_seqs[:, seqs.shape[1]:seqs.shape[1]*2] = (np.mod(seqs, 25)/5).astype(np.uint8)
ori_seqs[:, seqs.shape[1]*2:seqs.shape[1]*3] = np.mod(seqs, 5)
return ori_seqs
def filt_per_group(data) :
mat, inparalog, ref_len, seq_file, global_file = data
global_differences = dict(np.load(global_file, allow_pickle=True))
nMat = mat.shape[0]
with MapBsn(seq_file) as conn :
seqs = np.array([ conn.get(int(id/1000))[id%1000] for id in mat.T[5].tolist() ])
seqs = np.array([45, 65, 67, 71, 84], dtype=np.uint8)[decodeSeq(seqs)][:, :ref_len]
seqs[in1d(seqs, [65, 67, 71, 84], invert=True).reshape(seqs.shape)] = 0
def checkDiv(mat, diffX, i1) :
m1 = mat[i1]
for i2, m2 in enumerate(mat) :
if i1 != i2 :
mut, aln = diffX[i1, i2]
gd = (np.max([params['self_id'], 2.0/aln]), 0.) if m1[1] == m2[1] else global_differences.get(tuple(sorted([m1[1], m2[1]])), (0.5, 0.6))
dX = mut/aln/(gd[0]*np.exp(gd[1]*np.sqrt(params['allowed_sigma'])))
if dX > 1 :
return True
return False
diffX = compare_seqX(seqs, np.zeros(shape=[seqs.shape[0], seqs.shape[0], 2], dtype=int)).astype(float)
isDiv = False
for i1 in (0, mat.shape[0]-1) :
isDiv = checkDiv(mat, diffX, i1)
if isDiv :
break
if inparalog and not isDiv :
from collections import defaultdict
dupGenome = defaultdict(list)
for idx, g in enumerate(mat.T[1]):
dupGenome[g].append(idx)
dupGenome = [v for v in dupGenome.values() if len(v) > 1]
for group in dupGenome :
m = mat[group]
diffX = compare_seqX(seqs[group], np.zeros(shape=[len(group), len(group), 2], dtype=int)).astype(float)
for i1 in (0, m.shape[0] - 1):
isDiv = checkDiv(m, diffX, i1)
if isDiv:
break
if isDiv :
break
if not isDiv :
return [mat]
diff = compare_seq(seqs, np.zeros(shape=[seqs.shape[0], seqs.shape[0], 2], dtype=int)).astype(float)
distances = np.zeros(shape=[mat.shape[0], mat.shape[0], 2], dtype=float)
for i1, m1 in enumerate(mat) :
for i2 in xrange(i1+1, nMat) :
m2 = mat[i2]
mut, aln = diff[i1, i2]
gd = (np.max([params['self_id'], 2.0/aln]), 0.) if m1[1] == m2[1] else global_differences.get(tuple(sorted([m1[1], m2[1]])), (0.5, 0.6))
d = mut/aln/(gd[0]*np.exp(gd[1]*params['allowed_sigma']))
distances[i1, i2, :] = [d/gd[0], 1/gd[0]]
distances[i2, i1, :] = distances[i1, i2, :]
if np.any(distances[:, :, 0] > distances[:, :, 1]) :
groups = []
for j, m in enumerate(mat) :
novel = 1
for g in groups :
if diff[g[0], j, 0] <= 0.01*diff[g[0], j, 1] :
g.append(j)
novel = 0
break
if novel :
groups.append([j])
group_size = {g[0]:len(g) for g in groups}
seqs[seqs == 0] = 45
try :
tags = {g[0]:seqs[g[0]].tostring().decode('ascii') for g in groups}
except :
tags = {g[0]:seqs[g[0]].tostring() for g in groups}
incompatible = np.zeros(shape=distances.shape, dtype=float)
for i1, g1 in enumerate(groups) :
for i2 in range(i1+1, len(groups)) :
g2 = groups[i2]
incompatible[g2[0], g1[0], :] = incompatible[g1[0], g2[0], :] = np.sum(distances[g1][:, g2, :], (0, 1))
if np.all(incompatible[:,:,0] <= incompatible[:,:,1]) :
return [mat]
for ite in xrange(3) :
try :
tmpFile = tempfile.NamedTemporaryFile(dir='.', delete=False)
for n, s in tags.items() :
tmpFile.write('>X{0}\n{1}\n{2}'.format(n, s, '\n'*ite).encode('utf-8'))
tmpFile.close()
cmd = params[params['orthology']].format(tmpFile.name, **params) if len(tags) < 500 else params['nj'].format(tmpFile.name, **params)
phy_run = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
gene_phy = ete3.Tree(phy_run.communicate()[0].replace("'", ''))
break
except :
if ite == 2 :
return [mat]
finally:
os.unlink(tmpFile.name)
for n in gene_phy.get_leaves() :
if len(n.name) :
n.name = n.name[1:]
node = gene_phy.get_midpoint_outgroup()
if node is not None :
gene_phy.set_outgroup(node)
gene_phys = [gene_phy]
id = 0
while id < len(gene_phys) :
gene_phy = gene_phys[id]
for ite in xrange(3000) :
all_tips = {int(t) for t in gene_phy.get_leaf_names()}
if np.all(incompatible[list(all_tips)].T[0, list(all_tips)] <= incompatible[list(all_tips)].T[1, list(all_tips)]) :
break
rdist = sum([c.dist for c in gene_phy.get_children()])
for c in gene_phy.get_children() :
c.dist = rdist
for node in gene_phy.iter_descendants('postorder') :
if node.is_leaf() :
node.leaves = { int(node.name) } if node.name != 'REF' else set([])
else :
node.leaves = { n for child in node.get_children() for n in child.leaves }
node.leaf_size = np.sum([group_size[t] for t in node.leaves])
if len(node.leaves) :
oleaves = all_tips - node.leaves
c = incompatible[list(node.leaves)].T[:, list(oleaves)]
ic = np.sum(c, (1,2))
node.ic = [ic[0]/max(1., ic[1]), np.sum(c[1, (c[0] > c[1])])]
else :
node.ic = [0., 0.]
cut_node = [[n.ic[0]*np.sqrt(n.ic[1]), n.ic[0], n.dist, n] for n in gene_phy.iter_descendants('postorder') if n.ic[0] > 1]
if len(cut_node) > 0 :
cut_node = max(cut_node, key=lambda x:(x[0], x[1], x[2]))[3]
prev_node = cut_node.up
cut_node.detach()
t2 = cut_node
if prev_node.is_root() :
gene_phy = gene_phy.get_children()[0]
else :
prev_node.delete(preserve_branch_length=True)
if np.min(np.array(gene_phy.get_leaf_names()).astype(int)) > np.min(np.array(t2.get_leaf_names()).astype(int)) :
gene_phy, t2 = t2, gene_phy
gene_phys[id] = gene_phy
if np.max(mat[np.array(t2.get_leaf_names()).astype(int), 4]) >= (params['clust_identity']-0.02)*10000 :
gene_phys.append(t2)
else :
break
id += 1
mats = []
for gene_phy in gene_phys :
if len(gene_phy.get_leaf_names()) < len(tags) :
g = {str(g[0]):g for g in groups}
tips = sorted([ nn for n in gene_phy.get_leaf_names() for nn in g.get(n, [])])
mats.append(mat[tips])
else :
mats.append(mat)
return mats
else :
return [mat]
def get_gene(allScores, priorities, ortho_groups, cnt=1) :
ranking = {gene:priorities.get(gene)[0] for gene in allScores.keys() if gene in priorities}
if len(ranking) > 0 :
min_rank = min(ranking.values())
scores = { gene:allScores[gene] for gene, r in ranking.items() if r == min_rank }
else :
min_rank = -1
scores = {}
genes, all_useds = [], set([])
nGene = len(scores)
for id, (gene, score) in enumerate(sorted(scores.items(), key=itemgetter(1), reverse=True)) :
if score <= 0 : break
if gene not in all_useds or nGene < 2*cnt :
genes.append([gene, score, min_rank])
if len(genes) >= cnt :
break
all_useds.update(set(ortho_groups[ortho_groups.T[0] == int(gene), 1]))
if len(genes) <= 0 :
for gene in scores :
allScores.pop(gene)
return []
return genes
def load_conflict(data) :
cfl_file, idss = data
conflicts = []
with MapBsn(cfl_file) as cfl_conn :
for ids in idss :
gid = int(ids[0, 0]/30000)
d = cfl_conn[gid]
for id, g in ids :
idx = id%30000
idx1, idx2 = d[idx:(idx+2)]
if idx1 < idx2 :
conflicts.append([g, id, d[idx1:idx2]])
return conflicts
def filt_genes(groups, ortho_groups, global_file, cfl_file, priorities, scores, encodes) :
conflicting = ortho_groups[ortho_groups.T[2] < 0]
conflicting = np.vstack([conflicting[:, :2], conflicting[:, [1,0]]])*1000
ortho_groups = np.vstack([ortho_groups[:, :2], ortho_groups[:, [1,0]]])*1000
priorities = { k*1000:v for k, v in priorities.items() }
scores = { k*1000:v for k, v in scores.items() }
conflicts, new_groups = {}, {}
encodes = np.array([n for i, n in sorted([[i, n] for n, i in encodes.items()])])
clust_ref = { int(n)*1000:s for n, s in readFasta(params['clust']).items()}
used, pangenome, panList = {}, {}, {}
lowest_p = max([v[0] for v in priorities.values()])
while len(scores) > 0 :
# get top 500 genes
ortho_groups = ortho_groups[np.all(in1d(ortho_groups, list(scores.keys())).reshape(ortho_groups.shape), 1)]
genes = get_gene(scores, priorities, ortho_groups, cnt=500)
if len(genes) <= 0 :
continue
to_run, (min_score, min_rank) = [], genes[-1][1:]
genes = {gene:score for gene, score, min_rank in genes}
minSet = len(genes)*0.5
tmpSet = {}
for gene, score in list(genes.items()) :
present_iden = 0
if gene not in new_groups :
mat = groups.get(int(gene/1000))
mat.T[4] = (10000 * mat.T[3]/np.max(mat.T[3])).astype(int)
for m in mat :
v = used.get(m[5], None)
if v is None :
present_iden = max(present_iden, m[4])
else :
m[3] = 0 if v > 0 else -m[3]
if present_iden < (params['clust_identity']-0.02)*10000 :
exclude_gene(gene, scores, genes, conflicts, conflicting)
else :
tmpSet[gene] = mat[mat.T[3] != 0]
if len(genes) < minSet :
continue
logger('Selected {0} genes after initial checking'.format(len(genes)))
conflicts.update({gene:{} for gene in tmpSet.keys()})
if len(tmpSet):
tab_ids = np.vstack([ mat[:, (5, 0)] for mat in tmpSet.values() ])
tab_ids = tab_ids[np.argsort(tab_ids.T[0])]
tab_ids = np.split(tab_ids, np.cumsum(np.unique((tab_ids.T[0]/30000).astype(int), return_counts=True)[1])[:-1])
chunk_size = float(len(tab_ids))/params['n_thread']
tab_ids = [tab_ids[int(i):int(i + chunk_size)] for i in np.arange(params['n_thread'], dtype=float) * chunk_size if \
int(i) < int(i + chunk_size)]
for cfl in pool2.imap_unordered(load_conflict, [ [cfl_file, ids] for ids in tab_ids ]) :
for g, i, c in cfl :
conflicts[g*1000][i] = c
used2 = set([])
for gene, score in sorted(genes.items(), key=lambda x:-x[1]) :
if gene not in new_groups :
mat = tmpSet.get(gene)
unsure = np.sum([ 1 for m in mat if m[3] > 0 and m[5] in used2 ])
if unsure >= np.sum(mat.T[3]>0) * 0.6 :
genes.pop(gene)
else :
cfl = conflicts.get(int(gene), {})
for id, m in enumerate(mat) :
if m[5] not in used2 :
used2.update( { int(k/10) for k in cfl.get(m[5],[]) } )
if np.any(mat.T[3] < 0) :
mat[np.where(mat.T[3]< 0)[0][::3], 3] *= -1
tmpSet[gene] = mat[mat.T[3] > 0]
if params['orthology'] in ('ml', 'nj') :
for gene, score in genes.items() :
if gene not in new_groups :
mat = tmpSet.get(gene)
cfl = conflicts.get(int(gene), {})
_, bestPerGenome, matInGenome = np.unique(mat.T[1], return_index=True, return_inverse=True)
region_score = mat.T[4]/mat[bestPerGenome[matInGenome], 4]
if region_score.size >= bestPerGenome.size * 2 :
mat = mat[np.argsort(-mat.T[2])]
used2, kept = set([]), np.ones(mat.shape[0], dtype=bool)
for id, m in enumerate(mat) :
if m[5] in used2 :
kept[id] = False
else :
used2.update( { int(k/10) for k in cfl.get(m[5],[]) } )
mat = mat[kept]
mat = mat[np.argsort(-mat.T[3])]
_, bestPerGenome, matInGenome = np.unique(mat.T[1], return_index=True, return_inverse=True)
region_score = mat.T[4]/mat[bestPerGenome[matInGenome], 4]
if region_score.size > bestPerGenome.size * 3 and len(region_score) > 1000 :
region_score2 = sorted(region_score, reverse=True)
cut = region_score2[bestPerGenome.size*3-1]
if cut >= params['clust_identity'] :
cut = region_score2[bestPerGenome.size*6] if len(region_score) > bestPerGenome.size * 6 else params['clust_identity']
mat = mat[region_score>=cut]
inparalog = np.max(np.unique(mat.T[1], return_counts=True)[1])>1
if (not inparalog and np.min(mat[:, 3]) >= 10000 * params['clust_identity']) or len(mat) <= 1 :
new_groups[gene] = mat
else :
to_run.append([mat, inparalog, len(clust_ref[ mat[0][0]*1000 ]), params['map_bsn']+'.seq.npz', global_file])
working_groups = pool2.imap_unordered(filt_per_group, sorted(to_run, key=lambda r:(r[1], r[0].shape[0]*r[0].shape[0]*r[2]), reverse=True))
#working_groups = list(map(filt_per_group, sorted(to_run, key=lambda r:(r[1], r[0].shape[0]*r[0].shape[0]*r[2]), reverse=True)))
for working_group in working_groups :
gene = working_group[0][0][0]*1000
new_groups[gene] = working_group[0]
if len(working_group) > 1 :
cfl = conflicts.get(gene, {})
for id, matches in enumerate(working_group[1:]) :
ng = gene + (id+2)
new_groups[ng] = matches
conflicts[ng] = { mid:cfl.pop(mid, {}) for mid in matches.T[5] }
scores[ng] = np.sum(np.abs(matches[np.unique(matches.T[1], return_index=True)[1]].T[2]))
priorities[ng] = priorities[gene][:]
priorities[ng][0] = lowest_p
else :
for gene, score in genes.items() :
if gene not in new_groups :
mat = tmpSet.get(gene)
cfl = conflicts.get(int(gene), {})
_, bestPerGenome, matInGenome = np.unique(mat.T[1], return_index=True, return_inverse=True)
region_score = np.min([mat.T[2]/mat[bestPerGenome[matInGenome], 2], mat.T[4]/mat[bestPerGenome[matInGenome], 4]], axis=0)
mat = mat[region_score>=params['clust_identity']]
used2, kept = set([]), np.ones(mat.shape[0], dtype=bool)
for id, m in enumerate(mat) :
if m[5] in used2 :
kept[id] = False
else :
used2.update( { int(k/10) for k in cfl.get(m[5],[]) + [m[5]*10] } )
mat = mat[kept]
new_groups[gene] = mat
if len(genes) :
for gene in genes :
matches = new_groups.get(gene)
scores[gene] = np.sum(np.abs(matches[np.unique(matches.T[1], return_index=True)[1]].T[2]))
while len(genes) :
tmp = [ [scores[gene], gene] for gene in genes ]
score, gene = max(tmp)
if score < min_score :
break
mat = new_groups.pop(gene)
# third, check its overlapping again
paralog = False
supergroup, used2 = {}, {}
idens = 0.
for m in mat :
gid = m[5]
conflict = used.get(gid, None) if gid in used else used2.get(gid, None)
if conflict is not None :
if conflict < 0 :
superC = pangenome[-(conflict+1000)]
if superC not in supergroup :
supergroup[superC] = 0
if m[4] >= params['clust_identity'] * 10000 :
supergroup[superC] += 2
else :
supergroup[superC] += 1
elif conflict >0 :
paralog = True
m[3] = -1
else :
if idens < m[4] : idens = m[4]
used2[gid] = 0
for gg in conflicts.get(gene, {}).get(gid, []) :
g2, gs = int(gg/10), gg % 10
if gs == 1 :
if g2 not in used :
used2[g2] = -(gene+1000)
else :
used2[g2] = gene+1000 if gs == 2 else 0
if idens < (params['clust_identity']-0.02)*10000 :
exclude_gene(gene, scores, genes, conflicts, conflicting)
continue
mat = mat[mat.T[3] > 0]
superR = [None, -999, 0]
if len(supergroup) :
for superC, cnt in sorted(supergroup.items(), key=lambda d:d[1], reverse=True) :
if cnt >= mat.shape[0] or cnt >= len(panList[superC]) :
gl1, gl2 = panList[superC], set(mat.T[1])
s = len( (gl1 | gl2) ^ gl1 ) - 2*len(gl1 & gl2)
if s < 0 :
s = -1
if [s, cnt] > superR[1:] :
superR = [superC, s, cnt]
if superR[1] > 0 or superR[2] > 0 :
pangene = superR[0]
elif paralog :
new_groups[gene] = mat
continue
else :
pangene = gene
exclude_gene(gene, scores, genes, conflicts, conflicting)
pangenome[gene] = pangene
used.update(used2)
panList[pangene] = panList.get(pangene, set([])) | set(mat.T[1])
pangene_name = (encodes[int(pangene/1000)] + '/' + str(pangene % 1000)) if pangene % 1000 > 0 else encodes[int(pangene/1000)]
gene_name = (encodes[int(gene/1000)] + '/' + str(gene % 1000)) if gene % 1000 > 0 else encodes[int(gene/1000)]
if len(pangenome) % 100 == 0 :
logger('{4} / {5}: pan gene "{3}" : "{0}" picked from rank {1} and score {2}'.format(gene_name, min_rank, score/10000., pangene_name, len(pangenome), len(scores)+len(pangenome)))
mat_out.append([pangene_name, gene_name, min_rank, mat])
mat_out.append([0, 0, 0, []])
return
def exclude_gene(gene, scores, genes, conflicts, conflicting) :
scores.pop(gene, None)
genes.pop(gene, None)
conflicts.pop(gene, None)
for g in conflicting[conflicting.T[0] == gene, 1]:
scores.pop(g, None)
genes.pop(g, None)
conflicts.pop(g, None)
def load_priority(priority_list, genes, encodes) :
file_priority = { encodes[fn]:id for id, fnames in enumerate(priority_list.split(',')) for fn in fnames.split(':') }
unassign_id = max(file_priority.values()) + 1
priorities = { n:[ file_priority.get(g[0], unassign_id), -len(g[6]), g[5] ] for n, g in genes.items() }
priorities.update({ g[1]:[file_priority.get(g[1], unassign_id), 0, 0] for g in genes.values() })
return priorities
def writeGenomes(fname, seqs) :
with open(fname, 'w') as fout :
for g, s in seqs.items() :
fout.write('>{0} {1}\n{2}\n'.format(g, s[0], s[-1]))
return fname
def iter_map_bsn(data) :
prefix, clust, id, taxon, seq, orthoGroup, old_prediction, params = data
stop = ['TAG', 'TAA', 'TGA'] if params['gtable'] != 4 else ['TAA', 'TAG']
gfile, out_prefix = '{0}.{1}.genome'.format(prefix, id), '{0}.{1}'.format(prefix, id)
with open(gfile, 'w') as fout :
for n, s in seq :
fout.write('>{0}\n{1}\n'.format(n, s) )
if params['noDiamond'] :
blastab, overlap = uberBlast('-r {0} -q {1} -f -m -O --blastn --min_id {2} --min_cov {3} --min_ratio {4} --merge_gap {5} --merge_diff {6} -t 1 -e 0,3 --gtable {7}'.format(\
gfile, clust, params['match_identity']-0.1, params['match_frag_len'], params['match_frag_prop'], params['link_gap'], params['link_diff'], params['gtable'] ).split())
else :
blastab, overlap = uberBlast('-r {0} -q {1} -f -m -O --blastn --diamond --min_id {2} --min_cov {3} --min_ratio {4} --merge_gap {5} --merge_diff {6} -t 1 -s 1 -e 0,3 --gtable {7}'.format(\
gfile, clust, params['match_identity']-0.1, params['match_frag_len'], params['match_frag_prop'], params['link_gap'], params['link_diff'], params['gtable'] ).split())
os.unlink(gfile)
blastab.T[:2] = blastab.T[:2].astype(int)
# compare with old predictions
blastab = compare_prediction(blastab, old_prediction)
groups, groups2 = [], {}
ids = np.zeros(np.max(blastab.T[15])+1, dtype=bool)
for tab in blastab :
if tab[16][1] >= params['match_identity'] and (tab[16][2] >= max(params['match_prop']*tab[12], params['match_len']) or \
tab[16][2] >= max(params['match_prop1']*tab[12], params['match_len1']) or \
tab[16][2] >= max(params['match_prop2']*tab[12], params['match_len2'])) :
ids[tab[15]] = True
if len(tab[16]) <= 4 :
groups.append(tab[:2].tolist() + tab[16][:2] + [None, 0, [tab[:16]]])
else :
length = tab[7]-tab[6]+1
if tab[2] >= params['match_identity'] and (length >= max(params['match_prop']*tab[12], params['match_len']) or \
length >= max(params['match_prop1']*tab[12], params['match_len1']) or \
length >= max(params['match_prop2']*tab[12], params['match_len2'])) :
groups.append(tab[:2].tolist() + [tab[11], tab[2], None, 0, [tab[:16]]])
if tab[16][3] not in groups2 :
groups2[tab[16][3]] = tab[:2].tolist() + tab[16][:2] + [None, 0, [[]]*(len(tab[16])-3)]
x = [i for i, t in enumerate(tab[16][3:]) if t == tab[15]][0]
groups2[tab[16][3]][6][x] = tab[:16]
else :
tab[2] = -1
groups.extend(list(groups2.values()))
overlap = overlap[ids[overlap.T[0]] & ids[overlap.T[1]], :2]
convA, convB = np.tile(-1, np.max(blastab.T[15])+1), np.tile(-1, np.max(blastab.T[15])+1)
seq = dict(seq)
for id, group in enumerate(groups) :
group[4] = np.zeros(group[6][0][12], dtype=np.uint8)
group[4].fill(0)
group[5] = id
group[6] = np.array(group[6])
if group[6].shape[0] == 1 :
convA[group[6].T[15].astype(int)] = id
else :
convB[group[6].T[15].astype(int)] = id
max_sc = []
for tab in group[6] :
matchedSeq = seq[tab[1]][tab[8]-1:tab[9]] if tab[8] < tab[9] else rc(seq[tab[1]][tab[9]-1:tab[8]])
ms, i, f, sc = [], 0, 0, [0, 0, 0]
for s, t in re.findall(r'(\d+)([A-Z])', tab[14]) :
s = int(s)
if t == 'M' :
ms.append(matchedSeq[i:i+s])
i += s
sc[f] += s
elif t == 'D' :
i += s
f = (f-s)%3
else :
ms.append('-'*s)
f = (f+s)%3
ms = ''.join(ms)
sc = np.max(sc)
sc2 = np.max(np.diff(np.concatenate([[0], np.where(in1d(re.findall('...', ms), stop))[0]*3, [len(ms)]])))
sc = np.min([sc, sc2+3])
x = baseConv[np.array(list(ms)).view(asc2int)]
group[4][tab[6]-1:tab[6]+len(x)-1] = x
r = np.sqrt(float(sc)/tab[12] * tab[10]) #|2./(1./(float(sc)/tab[12]) + 1./tab[10]) if float(sc)/tab[12] > tab[10] else float(sc)/tab[12]
msc = (sc * tab[2])*np.sqrt(sc*r)
amsc = float(msc)/(tab[7]-tab[6]+1)
max_sc.append([tab[6], tab[7], amsc, msc])
for i, c in enumerate(max_sc[1:]) :
p = max_sc[i]
if c[0] < p[1] :
if c[2] > p[2] :
p[1] = c[0] - 1
p[3] = np.max(p[2] * (p[1]-p[0]+1), 0)
else :
c[0] = p[1] + 1
c[3] = np.max(c[2] * (c[1]-c[0]+1), 0)
group[2] = np.sum([c[3] for c in max_sc])
overlap = np.vstack([np.vstack([m, n]).T[(m>=0) & (n >=0)] for m in (convA[overlap.T[0]], convB[overlap.T[0]]) \
for n in (convA[overlap.T[1]], convB[overlap.T[1]]) ] + [np.vstack([convA, convB]).T[(convA >= 0) & (convB >=0)]])
bsn=np.array(groups, dtype=object)
size = np.ceil(np.vectorize(lambda n:len(n))(bsn.T[4])/3).astype(int)
bsn.T[4] = [ (b[:s]*25+b[s:2*s]*5 + np.concatenate([b, np.zeros(-b.shape[0]%3, dtype=int)])[2*s:]).astype(np.uint8) for b, s in zip(bsn.T[4], size) ]
if overlap.shape[0] :
orthoGroup = np.load(orthoGroup, allow_pickle=True)
orthoGroup = orthoGroup[orthoGroup.T[2] != 0]
orthoGroup = dict(
[[(g[0], g[1]), 1 if g[2] > 0 else -1] for g in orthoGroup] + \
[[(g[1], g[0]), 1 if g[2] > 0 else -1] for g in orthoGroup])
ovl_score = np.vectorize(lambda m,n:0 if m == n else orthoGroup.get((m,n), 2))(bsn[overlap.T[0], 0], bsn[overlap.T[1], 0])
overlap = np.hstack([overlap, ovl_score[:, np.newaxis]])
overlap = overlap[ovl_score >= 0]
else :
overlap = np.zeros([0, 3], dtype=np.int64)
np.savez_compressed(out_prefix+'.bsn.npz', bsn=bsn, ovl=overlap)
return out_prefix
def compare_prediction(blastab, old_prediction) :
blastab = pd.DataFrame(blastab)
blastab = blastab.assign(s=np.min([blastab[8], blastab[9]], 0)).sort_values(by=[1, 's']).drop('s', axis=1).values
blastab.T[10] = 0.1
with MapBsn(old_prediction) as op :
curr = [None, -1, 0]
for bsn in blastab :
if curr[1] != bsn[1] :
curr = [op.get(bsn[1]), bsn[1], 0]
if bsn[8] < bsn[9] :
s, e, f = bsn[8], bsn[9], {(bsn[8] - bsn[6]+1)%3+1, (bsn[9] + (bsn[12] - bsn[7])+1)%3+1}
else :
s, e, f = bsn[9], bsn[8], {-(bsn[8] - bsn[6]+1)%3-1, -(bsn[9] + (bsn[12] - bsn[7])-1)%3-1}
while curr[2] < len(curr[0]) and s > curr[0][curr[2]][2] :
curr[2] += 1
for p in curr[0][curr[2]:] :
if e < p[1] :
break
elif p[3] == '+' :
if p[1]%3+1 not in f and (p[2]+1)%3+1 not in f :
continue
else :
if -(p[1] - 1)%3-1 not in f and -(p[2])%3-1 not in f :
continue
ovl = min(e, p[2]) - max(s, p[1]) + 1.
if ovl >= 0.6*(p[2]-p[1]+1) or ovl >= 0.6*(e-s+1) :
ovl = ovl/(p[2] - p[1]+1)
if ovl > bsn[10] :
bsn[10] = ovl
return pd.DataFrame(blastab).sort_values(by=[0, 1, 11]).values
baseConv = np.zeros(255, dtype=np.uint8)
baseConv[(np.array(['A', 'C', 'G', 'T']).view(asc2int),)] = (1, 2, 3, 4)
def get_map_bsn(prefix, clust, genomes, orthoGroup, old_prediction, conn, seq_conn, mat_conn, clf_conn, saveSeq) :
if len(genomes) == 0 :
sys.exit(1)
taxa = {}
for g, s in genomes.items() :
if s[0] not in taxa : taxa[s[0]] = []
taxa[s[0]].append([g, s[1]])
ids = 0
seqs, seq_cnts = [], 0
mats, mat_cnts = [], 0
blastab, overlaps = [], {}
for bId, bsnPrefix in enumerate(pool.imap_unordered(iter_map_bsn, [(prefix, clust, id, taxon, seq, orthoGroup, old_prediction, params) for id, (taxon, seq) in enumerate(taxa.items())])) :
#for bId, bsnPrefix in enumerate(map(iter_map_bsn, [(prefix, clust, id, taxon, seq, orthoGroup, old_prediction, params) for id, (taxon, seq) in enumerate(taxa.items())])) :
tmp = np.load(bsnPrefix + '.bsn.npz', allow_pickle=True)
bsn, ovl = tmp['bsn'], tmp['ovl']
bsn.T[5] += ids
ovl[:, :2] += ids
prev_id = ids
ids += bsn.shape[0]
bsn.T[1] = genomes.get(bsn[0, 1], [-1])[0]
if ovl.shape[0] :
overlaps.update({id:[] for id in np.unique((ovl[:, :2]/30000).astype(int)) if id not in overlaps})
ovl = np.vstack([ovl, ovl[:, (1,0,2)]])
ovl = ovl[np.argsort(ovl.T[0])]
ovl = np.hstack([(ovl[:, :1]/30000).astype(int), ovl[:, :1]%30000, ovl[:, 1:2]*10+ovl[:, 2:]])
ovl = np.split(ovl, np.cumsum(np.unique(ovl.T[0], return_counts=True)[1])[:-1])
for ovl2 in ovl :
overlaps[ovl2[0, 0]].append(ovl2[:, 1:])
for id in np.arange(int(prev_id/30000), int(ids/30000)) :
if id in overlaps :
ovl = np.vstack(overlaps.pop(id))
ovl = np.concatenate([np.cumsum(np.concatenate([[0], np.bincount(ovl.T[0], minlength=30000)]))+30001, ovl.T[1]])
clf_conn.save(id, ovl)
del ovl
if saveSeq :
seqs = np.concatenate([seqs, bsn.T[4]])
ss = np.split(seqs, np.arange(1000, seqs.shape[0], 1000))
seqs = ss[-1]
for s in ss[:-1] :
seq_conn.save(seq_cnts, s)
seq_cnts += 1
bsn.T[4] = bsn.T[3]
mats = np.concatenate([mats, bsn.T[6]])
mm = np.split(mats, np.arange(1000, mats.shape[0], 1000))
mats = mm[-1]
for m in mm[:-1] :
mat_conn.save(mat_cnts, m)
mat_cnts += 1
bsn.T[6] = np.array([ len(b) for b in bsn.T[6] ], dtype=np.uint8)
bsn.T[2:5] = bsn.T[2:5] * 10000
bsn = bsn[np.argsort(-bsn.T[2])].astype(int)
blastab.append(bsn)
del bsn
os.unlink(bsnPrefix + '.bsn.npz')
logger('Merged {0}'.format(bsnPrefix))
if bId % 500 == 499 or bId == len(taxa) - 1 :
blastab = np.vstack(blastab)
blastab = blastab[np.argsort(blastab.T[0], kind='mergesort')]
blastab = np.split(blastab, np.cumsum(np.unique(blastab.T[0], return_counts=True)[1])[:-1])
conn.update(blastab)
del blastab
blastab = []
pool.close()
pool.join()
if saveSeq and seqs.shape[0] :
seq_conn.save(seq_cnts, seqs)
if mats.shape[0] :
mat_conn.save(mat_cnts, mats)
for id in overlaps.keys() :
ovl = np.vstack(overlaps.get(id))
ovl = np.concatenate([np.cumsum(np.concatenate([[0], np.bincount(ovl.T[0], minlength=30000)]))+30001, ovl.T[1]])
clf_conn.save(id, ovl)
del ovl, overlaps
def checkPseu(n, s, gtable) :
if len(s) < params['min_cds'] :
#logger('{0} len={1} is too short'.format(n, len(s)))
return 1
if len(s) % 3 > 0 and 'f' not in params['incompleteCDS'] :
#logger('{0} is discarded due to frameshifts'.format(n))
return 2
aa = transeq({'n':s.upper()}, frame=1, transl_table=gtable, markStarts=True)['n'][0]