This repository was archived by the owner on Jun 18, 2026. It is now read-only.
forked from slncky/slncky
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathslncky.v1.0
More file actions
executable file
·1398 lines (1132 loc) · 46.6 KB
/
Copy pathslncky.v1.0
File metadata and controls
executable file
·1398 lines (1132 loc) · 46.6 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
import os
import sys
import argparse
import subprocess
import tempfile
import random
from multiprocessing import Lock, Process, Queue
import time
from copy import deepcopy
import math
REALPATH = ''
ALIGNTRANSCRIPTS = ''
LASTZ = 'lastz'
NEWBED = False
BEDTOOLS = 'bedtools'
FASTAFROMBED = 'fastaFromBed'
INTERSECTBED = 'intersectBed'
CLOSESTBED = 'closestBed'
SORTBED = 'sortBed'
MERGEBED = 'mergeBed'
SHUFFLEBED = 'shuffleBed'
SLOPBED = 'slopBed'
LIFTOVER = 'liftOver'
def checkDependencies():
global NEWBED
#check bedtools version
cmd = [BEDTOOLS, '--version']
try:
out = subprocess.check_output(cmd)
except:
sys.exit("ERROR: bedtools not installed! You must have bedtools v2.17.0 or higher in your path! Exiting...")
out = out.split()
version = out[1][1:].split(".")
if int(version[0]) < 2 or int(version[1]) < 17:
sys.exit("ERROR: The version of bedtools you have installed is too old. You must have bedtools v2.17.0 or higher in your path! Exiting...")
if int(version[1]) >=20:
NEWBED = True
#check lastz
cmd = [LASTZ, '--version']
try:
p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
except:
sys.exit("ERROR: lastz not installed! You must have lastz in your path! Exiting...")
out = p.stdout.read()
out = out.split()
if out[0].strip() != "lastz":
sys.exit("ERROR: lastz not installed! You must have lastz in your path! Exiting...")
#check lastz
cmd = [LIFTOVER]
try:
p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
except:
sys.exit("ERROR: liftOver not installed! You must have liftOver in your path! Exiting...")
out = p.stderr.read()
out = out.split()
if out[0].strip() != "liftOver":
sys.exit("ERROR: liftOver not installed! You must have liftOver in your path! Exiting...")
def readAnnots(config_path, assembly):
ANNOTS = {}
##READ IN CONFIG FILE##
try:
config = open(config_path, 'r')
except IOError:
print "ERROR: cannot open ", config_path
sys.exit(1)
config_abspath = os.path.abspath(config_path)
index = config_path.rfind("/")
CONFIG_BASE = config_path[:index]
flag = False
for line in config.readlines():
line = line.strip()
if line == "" or line[0]=="#": continue
if line[0] == ">" and line[1:] == assembly.strip():
flag=True
if line[0] == ">" and line[1:] != assembly.strip():
flag=False
if flag and line[0] != ">":
line = line.split("=")
file = line[1].strip()
if line[0] != "ORTHOLOG":
if not os.path.isfile(file):
ogFile = file
file = REALPATH+file
if not os.path.isfile(file):
file = CONFIG_BASE+ogFile
if not os.path.isfile(file):
print line[0]+" file "+ogFile+" does not exist! Please check your annotations.config file. Exiting..."
sys.exit(1)
if line[0].strip() in ANNOTS:
arr = ANNOTS[line[0].strip()]
arr.append(file)
ANNOTS[line[0].strip()] = arr
else:
ANNOTS[line[0].strip()] = [file]
#CHECK ANNOTS
if len(ANNOTS) == 0:
print "WARNING: no annotations found for %s" % assembly
else:
if 'CODING' not in ANNOTS:
print "WARNING: no coding file was supplied in annotations.config for %s. Cannot find overlap with coding genes." % assembly
if 'GENOME_FA' not in ANNOTS:
print "WARNING: no genome fasta file was supplied in annotations.config for %s. Cannot align to find duplications or matches to orthologous coding genes." %assembly
else:
if not os.path.isfile(ANNOTS['GENOME_FA'][0]+".fai"):
sys.exit("ERROR: fa index does not exist for %s. Please use samtools faidx to index .fa file." % ANNOTS[GENOME_FA][0])
return ANNOTS
def writeToTmp(dict):
tempFd, tempPath = tempfile.mkstemp()
temp = open(tempPath, 'w')
for key,entry in dict.iteritems():
temp.write(entry)
temp.close()
os.close(tempFd)
return tempPath
def removeLncs(lncs, remove):
counter = 0
for item in remove:
if item[0] in lncs:
del lncs[item[0]]
counter += 1
return lncs, counter
def splitToExons(lncs):
lncExonFd, lncExonPath = tempfile.mkstemp()
lncExon = os.fdopen(lncExonFd, 'w')
lncSize = {}
lncGeneSize = {}
for lnc, line in lncs.iteritems():
line = line.split()
chr = line[0]
start = int(line[1])
end = int(line[2])
name = line[3]
score = 0
strand = line[5]
numBlocks = int(line[9].strip())
blockSizes = line[10].split(",")
blockStarts = line[11].split(",")
geneSize = end - start
size = 0
for i in range(numBlocks):
size += int(blockSizes[i])
exonStart = start + int(blockStarts[i])
exonEnd = exonStart + int(blockSizes[i])
lncExon.write("%s\t%d\t%d\t%s\t%s\t%s\n" % (chr,exonStart,exonEnd,name,score, strand))
lncSize[lnc] = size
lncGeneSize[lnc] = geneSize
lncExon.close()
return lncExonPath, lncSize, lncGeneSize
def removeOverlap(lncs, annots, args, min):
FILTER = []
lncExonPath, lncSize, lncGeneSize = splitToExons(lncs)
cmdPre = INTERSECTBED
for arg in args:
cmdPre += " "+arg
pairToOverlap = {}
for file in annots:
cmd = cmdPre+" -wao -a %s -b %s" % (lncExonPath, file)
#intersect and get overlap
out = subprocess.check_output([cmd], shell=True)
out = out.split("\n")
for line in out:
if line.strip() == "": continue
line= line.split()
lnc = line[3].strip()
gene = line[9].strip()
if gene == ".":
overlap = 0
else:
overlap = int(line[18])
pair = lnc+"&"+gene
if pair in pairToOverlap:
newOverlap = pairToOverlap[pair] + overlap
pairToOverlap[pair] = newOverlap
else:
pairToOverlap[pair] = overlap
#filter top
lncToMax = {}
for pair, overlap in pairToOverlap.iteritems():
pair = pair.split("&")
lnc = pair[0]
gene = pair[1]
overlap = overlap*1.0 / lncSize[lnc]
if overlap > min:
if lnc in lncToMax:
arr = lncToMax[lnc]
if overlap > arr[2]:
lncToMax[lnc] = [lnc, gene, overlap, file]
else:
lncToMax[lnc] = [lnc, gene, overlap, file]
for lnc, entry in lncToMax.iteritems():
FILTER.append(entry)
os.remove(lncExonPath)
newLncs, numRemoved = removeLncs(lncs, FILTER)
FILTER.sort(key = lambda x: x[2], reverse=True)
return newLncs, FILTER, numRemoved
def pickCanonicalLnc(lncs):
global NEWBED
lncExonPath, lncSize, lncGeneSize = splitToExons(lncs)
for lnc in lncs:
strand = lncs[lnc].split()[5]
break
if strand == "*":
if NEWBED:
cmd = "%s -i %s | %s -i - -c 4 -o distinct -delim \";\"" % (SORTBED, lncExonPath, MERGEBED)
else:
cmd = "%s -i %s | %s -i - -nms" % (SORTBED, lncExonPath, MERGEBED)
else:
if NEWBED:
cmd = "%s -i %s | %s -s -i - -c 4 -o distinct -delim \";\"" % (SORTBED, lncExonPath, MERGEBED)
else:
cmd = "%s -i %s | %s -s -i - -nms" % (SORTBED, lncExonPath, MERGEBED)
out = subprocess.check_output([cmd], shell=True)
out = out.split("\n")
mergedSets = []
for line in out:
if line == "": continue
line = line.split()
newSet = set()
for gene in line[3].split(";"): newSet.add(gene.strip())
mergedSets.append(newSet)
lncClusters = makeClusters(mergedSets)
#out = open("testing.bed", 'w')
bestLncs = {}
bestLncToCluster = {}
for lncCluster in lncClusters:
bestLnc = ""
bestLncSize = 0
for lnc in lncCluster:
if lncGeneSize[lnc] > bestLncSize:
bestLnc = lnc
bestLncSize = lncGeneSize[lnc]
bestLncs[bestLnc] = lncs[bestLnc]
bestLncToCluster[bestLnc] = lncCluster
#out.write(lncs[bestLnc])
return bestLncs, bestLncToCluster
def alignTranscripts(lncPath, fa, orthPath, orthFa, tmpPath, FILTER, null, keep, gapOpen, gapExtend, shuffle, orf, orfQueue):
if BEDTOOLS[0:-9] != "" and LASTZ[0:-6] != "":
cmd = [ALIGNTRANSCRIPTS, lncPath, fa, orthPath, orthFa, tmpPath, '--bedtools_path', BEDTOOLS[0:-8], '--lastz_path', LASTZ[0:-5], '--gap_open', gapOpen, '--gap_extend', gapExtend]
elif BEDTOOLS[0:-8] != "":
cmd = [ALIGNTRANSCRIPTS, lncPath, fa, orthPath, orthFa, tmpPath, '--bedtools_path', BEDTOOLS[0:-8], '--gap_open', gapOpen, '--gap_extend', gapExtend]
elif LASTZ[0:-5] != "":
cmd = [ALIGNTRANSCRIPTS, lncPath, fa, orthPath, orthFa, tmpPath, '--lastz_path', LASTZ[0:-5], '--gap_open', gapOpen, '--gap_extend', gapExtend]
else:
cmd = [ALIGNTRANSCRIPTS, lncPath, fa, orthPath, orthFa, tmpPath, '--gap_open', gapOpen, '--gap_extend', gapExtend]
if shuffle:
#cmd.append('--unmask')
cmd.append('--shuffle_bg')
if orf:
cmd.append('--orf')
#print cmd
ret = -1
try:
ret = subprocess.check_call(cmd, stdout = null, stderr = null)
except subprocess.CalledProcessError as e:
print "Warning: alignTranscripts failed with error %s" % e
FILTER.put(0)
if ret == 0:
out = ""
if os.path.exists(tmpPath+".alignment_identity.txt"):
outFile = open(tmpPath+".alignment_identity.txt", 'r')
out = outFile.readlines()
outFile.close()
for line in out:
if line.strip() == "": continue
line = line.split()
if len(line)>1 and line[4].strip() != "exonID_A":
alignScore = line[1]
geneA = line[2].strip()
geneB = line[3].strip()
exonID = float(line[4])
seqID = float(line[5])
indelRate = line[8]
indelRateIntron = line[9]
spliceAligned = line[12]
spliceTotal = line[13]
exonsAlignedA = line[10]
exonsAlignedB = line[11]
FILTER.put([geneA, geneB, exonID, seqID, indelRate, indelRateIntron, exonsAlignedA, exonsAlignedB, alignScore, spliceAligned, spliceTotal])
if os.path.exists(tmpPath+".alignment_identity.txt"):
os.remove(tmpPath+".alignment_identity.txt")
if not keep:
os.remove(tmpPath+".maf")
if os.path.exists(tmpPath+".orfs.txt"):
orfFile = open(tmpPath+".orfs.txt")
orf = orfFile.readlines()
orfFile.close()
for line in orf:
if line.strip() == "": continue
if not line[0] == "#":
line = line.split()
orfQueue.put(line)
os.remove(tmpPath+".orfs.txt")
os.remove(lncPath)
os.remove(orthPath)
FILTER.put(0)
def blastToOrtholog(lncs, annots, orth_annots, blastTo, n, alignments_dir, minMatch, multiple, pad, gapOpen, gapExtend, shuffle, orf):
queue = Queue()
FILTER = []
orfQueue = Queue()
ORFS = []
FLUSHED = 0
lncFile = writeToTmp(lncs)
liftOverFd, liftOverPath = tempfile.mkstemp()
unmappedPath = liftOverPath+".unmapped"
#liftover
if multiple: cmd = "cut -f1-4 %s | %s -i - -g %s -b %d | %s -minMatch=%.3f -multiple /dev/stdin %s /dev/stdout %s" % (lncFile, SLOPBED, annots["GENOME_FA"][0]+".fai", pad, LIFTOVER, minMatch, annots["LIFTOVER"][0], unmappedPath)
else: cmd = "cut -f1-4 %s | %s -i - -g %s -b %d | %s -minMatch=%.3f /dev/stdin %s /dev/stdout %s" % (lncFile, SLOPBED, annots["GENOME_FA"][0]+".fai", pad, LIFTOVER, minMatch, annots["LIFTOVER"][0], unmappedPath)
if len(annots["LIFTOVER"]) > 1:
for i in range(1,len(annots["LIFTOVER"])):
cmd += " | %s -minMatch=%.3f -multiple /dev/stdin %s /dev/stdout %s" % (LIFTOVER, minMatch, annots["LIFTOVER"][i], unmappedPath)
cmd += " > %s" % liftOverPath
null = open("/dev/null", 'w')
#print cmd
proc = subprocess.check_call([cmd],shell=True, stdout=null, stderr=null)
null.close()
os.remove(lncFile)
processes = []
null = open("/dev/null", 'w')
for file in orth_annots[blastTo]:
numAligned = 0
if multiple: cmd = "%s -i %s -g %s -b %d | %s -wa -wb -a - -b %s | cut -f4,6- | sort -u " % (SLOPBED, liftOverPath, orth_annots["GENOME_FA"][0]+".fai", pad, INTERSECTBED, file)
else: cmd = "%s -i %s -g %s -b %d | %s -wa -wb -a - -b %s | cut -f4- | sort -u " % (SLOPBED, liftOverPath, orth_annots["GENOME_FA"][0]+".fai", pad, INTERSECTBED, file)
try:
out = subprocess.check_output(cmd, stderr=null, shell=True)
except subprocess.CalledProcessError as e:
return 0
out = out.split("\n")
for line in out:
numAligned += 1
if line.strip() == "": continue
line= line.split()
lnc = line[0].strip()
lncBed = lncs[lnc]
overlapBed = line[1]
for i in range(2, len(line)):
overlapBed += "\t"+line[i]
lncFd, lncPath = tempfile.mkstemp()
lncFile = os.fdopen(lncFd, 'w')
lncFile.write(lncBed)
lncFile.close()
orthPath = lncPath+".orth"
orthFile = open(orthPath, 'w')
orthFile.write(overlapBed)
orthFile.close()
if alignments_dir == "":
keep = False
tmpOutPath = lncPath+".maf"
else:
keep = True
tmpOutPath = alignments_dir+lnc+"-"+overlapBed.split()[3].strip()
#print lncPath, orthPath, "start"
p = Process(target=alignTranscripts, args=(lncPath, annots["GENOME_FA"][0], orthPath, orth_annots["GENOME_FA"][0], tmpOutPath, queue, null, keep, gapOpen, gapExtend, shuffle, orf, orfQueue))
processes.append(p)
p.start()
print "\r aligning %d / %d genes to ortholog in %s" % (numAligned, len(out)-1, file),
#print " aligning %d / %d genes to ortholog in %s" % (numAligned, len(out)-1, file)
sys.stdout.flush()
while True:
counter = 0
for p in processes:
if p.is_alive():
counter += 1
if counter < n: break
else:
#empty align queue
queue.put('STOP')
for item in iter(queue.get, 'STOP'):
if item == 0: FLUSHED += 1
else:
FILTER.append(item)
#empty orf queue
orfQueue.put('STOP')
for item in iter(orfQueue.get, 'STOP'):
ORFS.append(item)
time.sleep(1)
print ""
null.close()
#print "entering second while loop"
#print len(processes)
#print FLUSHED
while FLUSHED < len(processes):
queue.put('STOP')
for item in iter(queue.get, 'STOP'):
if item == 0: FLUSHED += 1
else:
FILTER.append(item)
for p in processes:
p.join()
while not orfQueue.empty():
ORFS.append(orfQueue.get())
os.remove(liftOverPath)
os.remove(unmappedPath)
return FILTER, ORFS
def readMaf(maf, FILTER):
selfBlast = {}
for i in range(16, len(maf)):
line = maf[i]
if line == "" or len(line.split(" ")) < 2: continue
if line.startswith("a score"):
score = line.split("=")[1]
if i % 8 == 0:
identity = line.split(" ")[2].strip()[1:-2]
if i % 8 == 1:
coverage = line.split(" ")[2].strip()[1:-2]
if i % 8 == 2:
continuity = line.split(" ")[2].strip()[1:-2]
if i % 8 == 5:
name = line.split(" ")[1].strip()
if i % 8 == 6:
queryName = line.split(" ")[1].strip()
pair = name.strip()+"&"+queryName.strip()
if pair in selfBlast:
if float(identity) > selfBlast[pair][0]:
selfBlast[pair] = [float(identity), float(coverage), int(score)]
else:
selfBlast[pair] = [float(identity), float(coverage), int(score)]
for pair, id in selfBlast.iteritems():
pair = pair.split("&")
FILTER.put([pair[0], pair[1], id[0], id[1], id[2]])
del selfBlast
def selfBlastOneLnc(curLnc, lncs, FILTER, tmpPath, remove):
cmd = [LASTZ, curLnc, lncs, '--strand=plus', '--format=maf+', '--output=%s' % tmpPath]
subprocess.call(cmd)
file = open(tmpPath, 'r')
out = file.readlines()
file.close()
readMaf(out, FILTER)
os.remove(curLnc)
os.remove(tmpPath)
if remove: os.remove(lncs)
FILTER.put(0)
def selfBlast(lncs, annots, file, n, no_collapse):
queue = Queue()
processes = []
numAligned = 0
FILTER = []
FLUSHED = 0
#make query fasta
if file == "shuffle":
#if number of lncs very large, just take subset for null distribution to save time
if len(lncs) > 50:
allLncList = []
for lnc in lncs: allLncList.append(lnc)
subLncList = random.sample(allLncList, 50)
subLncs = {}
for lnc, item in lncs.iteritems():
if lnc in subLncList:
subLncs[lnc] = item
lncFile = writeToTmp(subLncs)
else:
lncFile = writeToTmp(lncs)
queryLncFaPath = [lncFile+".query.fa"]
shuffleLncPath = lncFile+".shuffle.bed"
shuffleLncBed = open(shuffleLncPath, 'w')
#make shuffled target fasta
for i in range(200):
cmd = [SHUFFLEBED, '-i', lncFile, '-g', annots["GENOME_FA"][0]+".fai", '-excl', annots["CODING"][0]]
out = subprocess.check_output(cmd)
shuffleLncBed.write(out)
shuffleLncBed.close()
cmd = [FASTAFROMBED, '-s', '-fi', annots["GENOME_FA"][0], '-bed', shuffleLncPath, '-fo', queryLncFaPath[0], '-split', '-name']
subprocess.call(cmd)
cmd = ['rm', shuffleLncPath]
subprocess.call(cmd)
elif file == "self":
lncFile = writeToTmp(lncs)
queryLncFaPath = [lncFile+".query.fa"]
cmd = [FASTAFROMBED, '-s', '-fi', annots["GENOME_FA"][0], '-bed', lncFile, '-fo', queryLncFaPath[0], '-split', '-name']
subprocess.call(cmd)
else:
queryLncFaPath = annots[file]
for lnc, entry in lncs.iteritems():
numAligned += 1
#make target fasta
curLnc = {}
curLnc[lnc] = entry
for query in queryLncFaPath:
curLncFile = writeToTmp(curLnc)
#make query fasta
if file == "self" and no_collapse:
newQuery = curLncFile+".query.fa"
cmd = "%s -v -a %s -b %s | %s -split -name -s -fi %s -bed - -fo %s" % (INTERSECTBED, lncFile, curLncFile, FASTAFROMBED, annots["GENOME_FA"][0], newQuery)
#print cmd
out = subprocess.check_call([cmd], shell=True)
#make target fasta
curLncFaPath = curLncFile+".fa"
cmd = [FASTAFROMBED, '-s', '-fi', annots["GENOME_FA"][0], '-bed', curLncFile, '-fo', curLncFaPath, '-split', '-name']
#print cmd
subprocess.check_call(cmd)
os.remove(curLncFile)
mafBedPath = curLncFile+".maf"
if file == "self" and no_collapse: p = Process(target=selfBlastOneLnc, args=(curLncFaPath, newQuery, queue, mafBedPath, True))
else: p = Process(target=selfBlastOneLnc, args=(curLncFaPath, query, queue, mafBedPath, False))
p.start()
processes.append(p)
print "\r self-aligning %d / %d genes" % (numAligned, len(lncs)),
sys.stdout.flush()
while True:
counter = 0
for p in processes:
if p.is_alive(): counter += 1
if counter < n*8: break
else:
queue.put('STOP')
for item in iter(queue.get, 'STOP'):
if item == 0: FLUSHED += 1
else: FILTER.append(item)
time.sleep(1)
while (FLUSHED < len(processes)):
queue.put('STOP')
for item in iter(queue.get, 'STOP'):
if item == 0: FLUSHED += 1
else: FILTER.append(item)
for p in processes:
p.join()
if file == "shuffle" or file == "self":
cmd = ['rm', queryLncFaPath[0]]
subprocess.call(cmd)
os.remove(lncFile)
return FILTER
def selfBlastShuffle(lncs, ANNOTS, threads):
lncToScores = {}
selfBlastShuffleResults = selfBlast(lncs, ANNOTS, "shuffle", threads, False)
for item in selfBlastShuffleResults:
if item[0] in lncToScores:
arr = lncToScores[item[0]]
else:
arr = []
arr.append(item[4])
lncToScores[item[0]] = arr
#sort
for item, arr in lncToScores.iteritems():
arr.sort()
lncToScores[item] = arr
return lncToScores
def selfBlastFilter(lncs, lncToScores, ANNOTS, threads, min, no_collapse):
print "\n\n aligning transcripts to each other..."
selfBlastResults = selfBlast(lncs, ANNOTS, "self", threads, no_collapse)
selfBlastSets = []
selfBlastSig = []
for item in selfBlastResults:
if item[0].strip() == item[1].strip(): continue
if item[0] in lncToScores: arrA = lncToScores[item[0]]
if item[1] in lncToScores: arrB = lncToScores[item[1]]
if (item[0] in lncToScores and item[4] >= arrA[int(len(arrA)*0.05)]) or item[0] not in lncToScores:
if (item[1] in lncToScores and item[4] >= arrB[int(len(arrB)*0.04)]) or item[1] not in lncToScores:
selfBlastSig.append(item)
newSet = set()
newSet.add(item[0])
newSet.add(item[1])
selfBlastSets.append(newSet)
selfBlastClusters = makeClusters(selfBlastSets)
finalSet = set()
finalClusters = []
for curSet in selfBlastClusters:
if len(curSet) >= min:
finalClusters.append(curSet)
for lnc in curSet: finalSet.add(lnc)
FILTER = []
for item in selfBlastSig:
if item[0] in finalSet and item[1] in finalSet:
FILTER.append(item)
newLncs, numRemoved = removeLncs(lncs, FILTER)
return newLncs, FILTER, finalClusters
def dupFilter(lncs, lncToScores, ANNOTS, threads):
print "\n\n aligning transcripts to annotated duplications..."
selfBlastResults = selfBlast(lncs, ANNOTS, "DUPS", threads, False)
lncToMax = {}
for item in selfBlastResults:
lnc = item[0]
if lnc in lncToScores: arr = lncToScores[lnc]
if (lnc in lncToScores and item[4] >= arr[int(len(arr)*0.05)]) or lnc not in lncToScores:
if lnc in lncToMax:
if item[4] > lncToMax[lnc]:
lncToMax[lnc] = item
else:
lncToMax[lnc] = item
SET = set()
FILTER = []
for lnc, item in lncToMax.iteritems():
FILTER.append(item)
SET.add(lnc)
return FILTER, SET
def codingBlastFilter(coding_alignments_dir, coding_blast_min, minMatch, pad, gap_open, gap_extend, SENSE_FILTER, ogLncs, lncs, ANNOTS, ORTH_ANNOTS, threads):
#make directory for coding
if os.path.exists(coding_alignments_dir):
print " %s exists. overwriting..." % coding_alignments_dir
cmd = ['rm', '-rf', coding_alignments_dir]
subprocess.call(cmd)
os.mkdir(coding_alignments_dir)
if coding_blast_min is None:
#LEARN DISTRIBUTION OF CODING GENE ALIGNMENTS
coding_positive_dir = coding_alignments_dir + "true_positives/"
if not os.path.exists(coding_positive_dir):
os.mkdir(coding_positive_dir)
#take top 250 transcripts that overlap with coding gene to learn true positive distribution.
print " learning distribution of coding gene alignment scores"
if len(SENSE_FILTER) < 250: print " WARNING: too few transcripts to accurately learn distribution. Consider setting --min_coding parameter."
coding = {}
counter = 0
seen = set()
randIndices = range(0, len(SENSE_FILTER))
random.shuffle(randIndices)
for index in randIndices:
if counter > 250: break
item = SENSE_FILTER[index]
if item[1] not in seen:
coding[item[0]] = ogLncs[item[0]]
seen.add(item[1])
counter += 1
CODING_POSITIVES, NULL = blastToOrtholog(coding, ANNOTS, ORTH_ANNOTS, "CODING", threads, coding_positive_dir, minMatch, False, pad, gap_open, gap_extend, False, False)
cmd = ['rm', '-rf', coding_positive_dir]
subprocess.call(cmd)
if len(CODING_POSITIVES) == 0:
print " WARNING: not enough transcripts to learn distribution. Setting min_coding at .15"
cutoff=.15
else:
codingToMax = {}
CODING_POSITIVES_MAX = []
for item in CODING_POSITIVES:
if len(item) > 0 and item[0] in codingToMax:
entry = codingToMax[item[0]]
if item[2] > entry[2]:
codingToMax[item[0]] = item
elif item[2] > 0.00:
codingToMax[item[0]] = item
for item,entry in codingToMax.iteritems(): CODING_POSITIVES_MAX.append(entry)
CODING_POSITIVES_MAX.sort(key=lambda x: x[2])
cutoff = CODING_POSITIVES_MAX[int(len(CODING_POSITIVES_MAX) * 0.05)][2]
print "\n setting cutoff for positive coding alignment at exonic id = %.3f" % cutoff
else:
cutoff = coding_blast_min
print " cutoff for positive coding alignment set to exonic id = %.3f" % cutoff
CODING_BLAST, NULL = blastToOrtholog(lncs, ANNOTS, ORTH_ANNOTS, "CODING", threads, coding_alignments_dir, minMatch, False, pad, gap_open, gap_extend, False, False)
CODING_BLAST_FILTER = []
for item in CODING_BLAST:
if item[2] >= cutoff:
CODING_BLAST_FILTER.append(item)
newLncs, numRemoved = removeLncs(lncs, CODING_BLAST_FILTER)
print "\n Removing..."
print " ... %d transcripts that aligns >%.1f%% to ortholog coding transcript" % (numRemoved, cutoff*100)
return newLncs, CODING_BLAST_FILTER, numRemoved
#takes in an array of sets and collapses them into unique clusters
def makeClusters(sets):
merged = True
while merged:
merged = False
results = []
while sets:
common, rest = sets[0], sets[1:]
sets = []
for x in rest:
if x.isdisjoint(common):
sets.append(x)
else:
merged = True
common |= x
results.append(common)
sets = results
return sets
def categorizeLncsByAnnots(lncs, ANNOTS):
if "MIRNA" not in ANNOTS or "SNORNA" not in ANNOTS:
print "WARNING!: miRNA and snoRNA annotations not found for lnc categorization"
if "CODING" not in ANNOTS:
print "WARNING!: coding annotations not found for lnc categorization"
lncToCategory = {}
curLncFile = writeToTmp(lncs)
#sort curLncFile
cmd = "%s -i %s > %s.tmp" % (SORTBED, curLncFile, curLncFile)
subprocess.check_call([cmd], shell=True)
cmd = "mv %s.tmp %s" % (curLncFile, curLncFile)
subprocess.check_call([cmd], shell=True)
#check if snorna host
if "SNORNA" in ANNOTS:
cmd =[INTERSECTBED, '-a', curLncFile, '-b', ANNOTS["SNORNA"][0]]
out = subprocess.check_output(cmd)
for line in out.split("\n"):
if line.strip() == "": continue
line = line.split("\t")
lnc = line[3].strip()
lncToCategory[lnc] = "sno_host"
#check if mirna host
if "MIRNA" in ANNOTS:
cmd =[INTERSECTBED, '-split', '-a', curLncFile, '-b', ANNOTS["MIRNA"][0]]
out = subprocess.check_output(cmd)
for line in out.split("\n"):
if line.strip() == "": continue
line = line.split("\t")
lnc = line[3].strip()
if lnc not in lncToCategory: lncToCategory[lnc] = "mir_host_exon"
cmd =[INTERSECTBED, '-a', curLncFile, '-b', ANNOTS["MIRNA"][0]]
out = subprocess.check_output(cmd)
for line in out.split("\n"):
if line.strip() == "": continue
line = line.split("\t")
lnc = line[3].strip()
if lnc not in lncToCategory: lncToCategory[lnc] = "mir_host_intron"
#check if divergent
if "CODING" in ANNOTS:
out = ""
for file in ANNOTS["CODING"]:
cmd = "%s -i %s | %s -S -a %s -b -" % (SORTBED, file, CLOSESTBED, curLncFile)
#print cmd
out += subprocess.check_output([cmd], shell=True)
out = out.split("\n")
lncToTss = {}
for line in out:
if line == "": continue
line = line.split("\t")
lnc = line[3].strip()
if line[5] == "+":
lncTSS = int(line[1])
else:
lncTSS = int(line[2])
if line[17] == "+":
codingTSS = int(line[13])
else:
codingTSS = int(line[14])
dist = abs(lncTSS - codingTSS)
if (lnc not in lncToTss): lncToTss[lnc] = dist
else:
if (dist < lncToTss[lnc]): lncToTss[lnc] = dist
for lnc, dist in lncToTss.iteritems():
if dist <=500 and lnc not in lncToCategory:
lncToCategory[lnc] = "divergent"
for lnc in lncs:
if lnc not in lncToCategory: lncToCategory[lnc] = "intergenic"
#cleanup
cmd = ['rm', curLncFile]
subprocess.call(cmd)
return lncToCategory
def geneSymbol(lncs, ANNOTS):
lncToGeneSymbol = {}
GeneSymbol = {}
if "GENESYMBOL" in ANNOTS:
#load gene symbol file into dict
genesymbol = open(ANNOTS["GENESYMBOL"][0], 'r').readlines()
for line in genesymbol:
line = line.split()
GeneSymbol[line[0].strip()] = line[1].strip()
for lnc in lncs:
lncGeneSymbol = "Unannotated"
if "GENESYMBOL" in ANNOTS and "NONCODING" in ANNOTS:
curLncFile = writeToTmp({lnc: lncs[lnc]})
maxOverlap = 0
#for every noncoding file
for file in ANNOTS["NONCODING"]:
#intersect lnc with noncoding
cmd = [INTERSECTBED, '-split', '-s', '-wo', '-a', curLncFile, '-b', file]
out = subprocess.check_output(cmd)
#pick best intersecting and get gene symbol
out = out.split("\n")
for line in out:
if line.strip() == "": continue
line = line.split()
overlap = int(line[len(line)-1])
if overlap > maxOverlap and line[15].strip() in GeneSymbol:
lncGeneSymbol = GeneSymbol[line[15].strip()]
maxOverlap = overlap
os.remove(curLncFile)
lncToGeneSymbol[lnc] = lncGeneSymbol
return lncToGeneSymbol
def checkBedMatchesFa(bedfile, ANNOTS):
cmd = 'cut -f1 %s | sort -u' % bedfile
out = subprocess.check_output([cmd], shell=True)
out = out.split("\n")
bedChrs = set()
for chr in out:
if (chr != ""): bedChrs.add(chr.strip())
faFile = open(ANNOTS["GENOME_FA"][0]+".fai", 'r')
faChrs = set()
for line in faFile.readlines():
line = line.split()
faChrs.add(line[0].strip())
if not bedChrs.issubset(faChrs):
sys.exit("ERROR: bed file %s contains entries on chromosomes not included in genome fa %s. Are you sure you specificed the correct species?" % (bedfile, ANNOTS["GENOME_FA"][0]))
def main():
parser = argparse.ArgumentParser(description='sLNCky: a lncRNA discovery software for lncRNA annotation and ortholog discovery.')
parser.add_argument('bedfile', type=str, help='bed12 file of transcripts')
parser.add_argument('assembly', type=str, help='assembly')
parser.add_argument('out_prefix', type=str, help='out_prefix')
parser.add_argument('--config', '-c', type=str, help='path to assembly.config file. default uses config file in same directory as slncky')
parser.add_argument('--no_orth_search', '-1', action='store_true', help='flag if you only want to filter lncs but don\'t want to search for orthologs')
parser.add_argument('--no_filter', '-2', action='store_true', help='flag if you don\'t want lncs to be filtered before searching for ortholog')
parser.add_argument('--overwrite', '-o', action='store_true', help='forces overwrite of out_prefix.bed')
parser.add_argument('--threads', '-n', type=int, help='number of threads. default = 5', default=5)
parser.add_argument('--min_overlap', type=float, help='remove any transcript that overlap annotated coding gene > min_overlap%%. default = 0%%', default=0)
parser.add_argument('--min_cluster', type=int, help='min size of duplication clusters to remove. default=2', default=2)
parser.add_argument('--min_coding', type=float, help='min exonic identity to filter out transcript that aligns to orthologous coding gene. default is set by learning coding alignment distribution from data', default=None)
parser.add_argument('--no_overlap', action='store_true', help='flag if you don\'t want to overlap with coding')
parser.add_argument('--no_collapse', action='store_true', help='flag if you don\'t want to collapse isoforms')
parser.add_argument('--no_dup', action='store_true', help='flag if don\'t want to align to duplicates')
parser.add_argument('--no_self', action='store_true', help='flag if you don\'t want to self-align for duplicates')
parser.add_argument('--no_coding', action='store_true', help='flag if you don\'t want to align to orthologous coding')
parser.add_argument('--min_noncoding', type=float, help='min exonic identity to filter out transcript that aligns to orthologous noncoding gene. default=0', default=0.0)
parser.add_argument('--no_bg', action='store_true', help='flag if you don\'t want to compare lnc-to-ortholog alignments to a background. This flag may be useful if you want to do a \'quick-and-dirty\' run of the ortholog search.')
parser.add_argument('--no_orf', action='store_true', help='flag if you don\'t want to search for orfs')
parser.add_argument('--bedtools', type=str, help='path to bedtools')
parser.add_argument('--liftover', type=str, help='path to liftOver')
parser.add_argument('--minMatch', type=float, help='minMatch parameter for liftover. default=0.1', default=0.1)
parser.add_argument('--pad', type=int, help='# of basepairs to search up- and down-stream when lifting over lnc to ortholog', default=0)
parser.add_argument('--lastz', type=str, help='path to lastz')
parser.add_argument('--gap_open', type=str, default='200')
parser.add_argument('--gap_extend', type=str, default='40')
parser.add_argument('--web', action='store_true', help='flag if you don\'t want website written visualizing transcripts that were filtered out')
args = parser.parse_args()
global REALPATH
global ALIGNTRANSCRIPTS
REALPATH = os.path.realpath(__file__)[0:-11]
ALIGNTRANSCRIPTS = REALPATH+"alignTranscripts1.0"
if args.config is None: args.config = REALPATH+"annotations.config"
print args.config
if args.bedtools is not None:
global FASTAFROMBED
global INTERSECTBED
global CLOSESTBED
global SORTBED
global MERGEBED
global SHUFFLEBED
global SLOPBED