-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsqanti_qc.py
1980 lines (1563 loc) · 70.5 KB
/
sqanti_qc.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
# SQANTI: Structural and Quality Annotation of Novel Transcript Isoforms
# Authors: Lorena de la Fuente, Hector del Risco, Cecile Pereira and Manuel Tardaguila
from collections import defaultdict
import getopt
import sys
import os.path, os
import timeit
import subprocess
import argparse
utilitiesPath = os.path.dirname(os.path.realpath(__file__))+"/utilities/"
sys.path.insert(0, utilitiesPath)
from rt_switching import rts
from indels_annot import indels
import psutil
import gc
import distutils.spawn
class myQueryTranscripts:
def __init__(self, transcript, tss_diff, tts_diff, exon_number, length, str_class, subtype=None, genes=None, transcripts=None, chrom=None, strand=None, bite = "FALSE", RT_switching = "FALSE", canonical="canonical", min_cov = "NA", min_cov_pos = "NA", min_samp_cov="NA", sd = "NA", FL = "NA", nIndels = "NA", nIndelsJunc = "NA", proteinID=None, ORFlen="NA", CDS_start="NA", CDS_end="NA", isoExp = "NA", geneExp = "NA" , coding = "non_coding", refLen = "NA", refExons = "NA", FSM_class = None, percAdownTTS = None):
self.transcript = transcript
self.tss_diff = tss_diff
self.tts_diff = tts_diff
self.genes = []
self.transcripts = []
self.exon_number = exon_number
self.length = length
self.str_class = str_class # structural classification of the isoform.
self.chrom = chrom
self.strand = strand
self.subtype = subtype
self.RT_switching= RT_switching
self.canonical = canonical
self.min_samp_cov = min_samp_cov
self.min_cov = min_cov
self.min_cov_pos = min_cov_pos
self.sd = sd
self.proteinID = proteinID
self.ORFlen = ORFlen
self.CDS_start = CDS_start
self.CDS_end = CDS_end
self.coding = coding
self.FL = FL
self.nIndels = nIndels
self.nIndelsJunc = nIndelsJunc
self.isoExp = isoExp
self.geneExp = geneExp
self.refLen = refLen
self.refExons = refExons
self.FSM_class = FSM_class
self.bite = bite
self.percAdownTTS = percAdownTTS
def get_total_diff(self):
total_diff = abs(int(self.tss_diff))+abs(int(self.tts_diff))
return total_diff
def modify(self, transcript, gene, tss_diff, tts_diff, refLen, refExons):
self.transcript = transcript
self.genes.append(gene)
self.tss_diff = tss_diff
self.tts_diff = tts_diff
self.transcripts.append(self.transcript)
self.refLen = refLen
self.refExons = refExons
def geneName(self):
geneName = "_".join(set(self.genes))
return geneName
def ratioExp(self):
if self.geneExp == 0 or self.geneExp == "NA":
return "NA"
else:
ratio = float(self.isoExp)/float(self.geneExp)
return(ratio)
def CDSlen(self):
if self.coding == "coding":
return(str(int(self.CDS_end) - int(self.CDS_start) + 1))
else:
return("NA")
def __str__(self):
return "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s" % (self.chrom, self.strand, str(self.length), str(self.exon_number), str(self.str_class), "_".join(set(self.genes)), self.transcript, str(self.refLen), str(self.refExons), str(self.tss_diff), str(self.tts_diff), self.subtype, self.RT_switching, self.canonical, str(self.min_samp_cov),str(self.min_cov), str(self.min_cov_pos), str(self.sd), str(self.FL), str(self.nIndels), str(self.nIndelsJunc), self.bite, str(self.isoExp), str(self.geneExp), str(self.ratioExp()), self.FSM_class, self.coding, str(self.ORFlen), str(self.CDSlen()), str(self.CDS_start), str(self.CDS_end), str(self.percAdownTTS))
class myQueryProteins:
def __init__(self, cds_start, cds_end, orf_length, proteinID="NA"):
self.orf_length = orf_length
self.cds_start = cds_start
self.cds_end = cds_end
self.proteinID = proteinID
class myQueryJunctions:
def __init__(self, transcript, junctionNumber, chrom, strand, junc_class, donor, acceptor, diff_start, diff_end, genomCoordStart, genomCoordEnd, transcriptCoord, spliceSite, canonical, indel="NA", coverage=None):
self.transcript = transcript
self.junctionNumber = junctionNumber
self.chrom = chrom
self.strand = strand
self.junc_class = junc_class
self.donor = donor
self.acceptor = acceptor
self.diff_start = diff_start
self.diff_end = diff_end
self.genomCoordStart = genomCoordStart
self.genomCoordEnd = genomCoordEnd
self.transcriptCoord = transcriptCoord
self.spliceSite = spliceSite
self.canonical = canonical
self.coverage = []
self.indel = indel
def totalCov(self):
if "NA" in self.coverage or len(self.coverage)==0:
totalCov = "NA"
repCov = "NA"
else:
totalCov = sum([int(i) for i in self.coverage])
repCov = len([i for i in self.coverage if int(i) > 0])
return(totalCov, repCov)
def coverage_files(self):
if len(self.coverage)==0:
return("")
else:
return("\t"+("\t").join(self.coverage))
def biteDef(self):
#if self.diff_donor != 0 and self.diff_acceptor != 0 and self.diff_donor%3 != 0 and self.diff_donor%3 != 0:
if self.diff_start not in [0, "NA"] and self.diff_end not in [0, "NA"]:
return ("TRUE")
else:
return ("FALSE")
def __str__(self):
return "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s%s" % (self.transcript, self.chrom, self.strand, self.junctionNumber, self.genomCoordStart, self.genomCoordEnd, str(self.transcriptCoord), self.junc_class, self.donor, self.acceptor, self.diff_start, self.diff_end, self.biteDef(), self.spliceSite, self.canonical, self.indel, self.totalCov()[1], self.totalCov()[0], self.coverage_files())
class myQueries:
def __init__(self, line, coordToSort, assoc=None): #CoordToSort can be the start of the first exon or the start of the first junction
self.line = line
self.coordToSort = coordToSort
self.assoc = assoc
class refTranscripts:
def __init__(self, transcript, gene, chrom, strand, tss=None, tts=None):
self.transcript = transcript
self.chrom = chrom
self.strand = strand
self.junctions = [] #inside two list: starts of junctions and ends of junctions (sorted by coordinates)
self.tss = tss
self.tts = tts
self.gene = gene
self.exons = [] #inside two list: starts of exons and ends of exons (sorted by coordinates)
self.exons_coordinates = []
def add_information(self, line, strand):
exon_s = line[8].split(",")[0:-1]
exon_e = line[9].split(",")[0:-1]
exon_s = [int(i)+1 for i in exon_s]
#exons
self.exons.append(exon_s)
self.exons.append(exon_e)
# tss and tts
if strand == "+":
tss = exon_s[0]
tts = exon_e[-1]
else:
tts = exon_s[0]
tss = exon_e[-1]
self.tss = int(tss)
self.tts = int(tts)
#junctions
if len(exon_e) >= 2: #junctions only if multiple-exon isoforms
junctions_e = exon_s[1:]
junctions_e = [int(i)-1 for i in junctions_e]
junctions_s = exon_e[:-1]
junctions_s = [int(i)+1 for i in junctions_s]
self.junctions.append(junctions_s)
self.junctions.append(junctions_e)
def difference_fragment_transcript(self, coord_start, coord_end, ref_coord):
if int(coord_start) >= int(ref_coord[0]):
lack_start = ref_coord.index(int(coord_start))
else:
lack_start = int(coord_start) - int(ref_coord[0])
if int(coord_end) <= int(ref_coord[-1]):
lack_end = len(ref_coord) - ref_coord.index(int(coord_end)) -1
else:
lack_end = int(ref_coord[-1]) - int(coord_end)
return (lack_start, lack_end)
def transcriptLength(self):
length=0
for i in range(len(self.exons[0])):
length = length + (int(self.exons[1][i])-int(self.exons[0][i])+1)
return length
class refGenes:
def __init__(self, gene, chrom, strand):
self.chrom = chrom
self.junctions = [] #Here we'll save vectors of two elements (start and end of the junction). #The final junctions vector will have as many elements as different juctions exist in that gene.
self.strand = strand
self.tss = []
self.tts = []
self.exons = [] # inside each exon of the gene is in a list (start-end). #The final junctions vector will have as many elements as different exons exist in that gene.
self.last3junctions = [] #all last3junctions for that gene
self.last5junctions = [] #all last5junctions for that gene
self.last3exons = [] #all last3exons for that gene
self.last5exons = [] #all last3exons for that gene
self.gene = gene
self.transcripts = []
self.exonsTranscript = [] #[[[exon1_t1][exon2_t2]], [[exon1_t2][exon2_t2]],....) # Now you can see all the exons for each transcript of the gene
self.exonsTranscriptTog = []
def add_transcript(self, line, strand):
# exons in genomic coordinates
exon_s = line[8].split(",")[0:-1]
exon_e = line[9].split(",")[0:-1]
exon_s = [int(i)+1 for i in exon_s]
exon_e = [int(i) for i in exon_e]
subject = line[0]
exons_per_transcript = []
exons_per_transcript_total = []
for i in range(len(exon_s)):
self.exons.append([exon_s[i],exon_e[i]])
exons_per_transcript_total.append([exon_s[i],exon_e[i]]) #el primer y ultimo exon lo tenemos en cuenta. ##### Mirar para que lo necesitamos realmente
if i != 1 and i != len(exon_s):
exons_per_transcript.append([exon_s[i],exon_e[i]]) #el primer y ultimo exon no lo tenemos en cuenta. ##### Mirar para que lo necesitamos realmente
self.exonsTranscriptTog.append(exons_per_transcript_total) #el primer y ultimo exon se tienen en cuenta.
self.exonsTranscript.append(exons_per_transcript) #el primer y ultimo exon no se tienen en cuenta.
self.transcripts.append(subject) #adding transcripts names
if len(exon_s) >= 2: #last exons only if multiple-exon isoforms
if strand == "+":
self.last5exons.append([exon_s[0], exon_e[0]])
self.last3exons.append([exon_s[-1], exon_e[-1]])
if strand == "-":
self.last5exons.append([exon_s[-1], exon_e[-1]])
self.last3exons.append([exon_s[0], exon_e[0]])
# tss and tts
if strand == "+":
tss = exon_s[0]
tts = exon_e[-1]
else:
tts = exon_s[0]
tss = exon_e[-1]
self.tss.append(int(tss))
self.tts.append(int(tts))
#junctions
if len(exon_s) >= 2: #junctions only if multiple-exon isoforms
junctions_e = exon_s[1:]
junctions_e = [int(i)-1 for i in junctions_e]
junctions_s = exon_e[:-1]
junctions_s = [int(i)+1 for i in junctions_s]
for i in range(len(junctions_s)):
self.junctions.append([junctions_s[i],junctions_e[i]])
if strand == "+":
self.last5junctions.append([junctions_s[0], junctions_e[0]])
self.last3junctions.append([junctions_s[-1], junctions_e[-1]])
if strand == "-":
self.last5junctions.append([junctions_s[-1], junctions_e[-1]])
self.last3junctions.append([junctions_s[0], junctions_e[0]])
def __str__(self):
return "%s\t%s\t%s\t%s" % (self.gene, self.chrom, self.strand, self.exons)
def ReverseComplement(seq):
basecomplement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'}
seq = seq.upper()
RCseq = ""
for base in seq:
if base not in basecomplement:
sys.stderr.write("Error: %s NOT a DNA sequence" %(seq))
return None
break
RCseq = basecomplement[base]+RCseq
return (RCseq)
def transcriptLength(startExons, endExons):
length=0
for i in range(len(startExons)):
length = length + (int(endExons[i])-int(startExons[i])+1)
return length
def exons_together(starts, ends): #arguments: list of starts of exons and list of ends of exons
exons_together = []
for i in range(len(starts)):
exons_together = exons_together + range(int(starts[i]), int(ends[i])+1)
return exons_together
def getTranscriptJunctCoordinates(exons_starts, exons_ends, strand, junctions=None):
exons_unknown_together = []
starts_transcript = []
ends_transcript = []
for i in range(len(exons_starts)):
exons_unknown_together = exons_unknown_together + range(int(exons_starts[i]), int(exons_ends[i])+1)
if junctions==None:
junctions = exons_ends[:-1]
if strand=="+":
exons_unknown_together_sort = sorted(exons_unknown_together)
for l in junctions:
for k in range(len(exons_unknown_together_sort)):
if exons_unknown_together_sort[k] == int(l):
starts_transcript.append(k+1)
ends_transcript.append(k+1+1) #k+1+1
if strand=="-":
exons_unknown_together_sort = sorted(exons_unknown_together, reverse=True)
for l in junctions:
for k in range(len(exons_unknown_together_sort)):
if exons_unknown_together_sort[k] == int(l):
starts_transcript.append(str(k+1))
ends_transcript.append(str(k)) #k+1-1
start = min(starts_transcript, ends_transcript)
end = max(starts_transcript, ends_transcript)
return [start, end]
def fasta_parser(fastaFile):
try:
fasta = open(fastaFile, "r")
except IOError:
sys.stderr.write('ERROR: Unable to read %s file\n' % fastaFile)
raise SystemExit(1)
try:
seqDicc = {}
index = 0
for line in fasta:
if line.startswith(">"):
if index > 0:
seqDicc[name] = seq
index+=1
name = line[1:].rstrip()
#name = line[1:].split()[0].rstrip()
seq = ''
elif line.strip()!="":
seq += line.rstrip()
if index>0:
seqDicc[name] = seq
fasta.close()
except (RuntimeError, TypeError, NameError):
sys.stderr.write('ERROR: File %s without fasta format.\n' % fastaFile)
raise SystemExit(1)
return(seqDicc)
def genome_parser(fastaFile):
try:
fasta = open(fastaFile, "r")
except IOError:
sys.stderr.write('ERROR: Unable to read %s file.\n' % fastaFile)
raise SystemExit(1)
try:
seqDicc = {}
index = 0
for line in fasta:
if line.startswith(">"):
if index > 0:
seqDicc[name] = seq
index+=1
name = line[1:].rstrip().split()[0]
#name = line[1:].split()[0].rstrip()
seq = ''
elif line.strip()!="":
seq += line.rstrip()
seqDicc[name] = seq
fasta.close()
except (RuntimeError, TypeError, NameError):
sys.stderr.write('ERROR: File %s without fasta format.\n' % fastaFile)
raise SystemExit(1)
return(seqDicc)
def correctionPlusORFpred(args, chrom_names):
global corrORF
global corrGTF
global corrSAM
global corrFASTA
corrPathPrefix = args.dir+"/"+os.path.splitext(os.path.basename(args.isoforms))[0]
corrGFF_gmap = corrPathPrefix +"_corrected_gmap.gff"
corrGFF = corrPathPrefix +"_corrected.gff"
corrGTF = corrPathPrefix +"_corrected.gtf"
corrSAM = corrPathPrefix +"_corrected.sam"
corrFASTA = corrPathPrefix +"_corrected.fasta"
ORF = corrPathPrefix +"_corrected.faa"
corrORF = os.path.splitext(ORF)[0]+'_ATG.faa'
if not args.gtf:
if (os.path.isdir(os.path.dirname(args.gmap_index))): # check index folder
index_dir = os.path.dirname(args.gmap_index)
prefix = os.path.basename(args.gmap_index)
# modifiying fasta header to keep just transcript ID.
fastaDicc = fasta_parser(args.isoforms)
tmpFasta = os.path.splitext(args.isoforms)[0]+'.tmp'
tmpFasta_file = open(tmpFasta, "w")
for ID in fastaDicc:
if len(ID.split("|"))>2 and ID[0:2]=="PB": # PacBio fasta header (including chained format)
ID_mod = ID.split("|")[0].split(" ")[0]
elif len(ID.split("|"))>4: # Refseq fasta header
ID_mod = ID.split("|")[3]
else:
ID_mod = ID.split()[0] # Ensembl fasta header
tmpFasta_file.write(">"+ID_mod+"\n"+fastaDicc[ID]+"\n")
tmpFasta_file.close()
sys.stdout.write("\n****Aligning reads with gmap...\n")
# aligning sequences
threads=str(args.gmap_threads)
sense = str(args.sense)
print sense
try:
#with open(corrGFF_gmap, 'w') as corrGFF_out:
# subprocess.call(['gmap','-n', '1', '-t', threads, '--cross-species', '--gff3-add-separators=0','-f', '2', '-z', 'sense_force','-D', index_dir,'-d', prefix, tmpFasta], stdout=corrGFF_out)
with open(corrSAM, 'w') as corrSAM_out:
subprocess.call(['gmap','-n', '1', '-t', threads, '--cross-species', '--gff3-add-separators=0','-f', 'samse', '-z', sense, '-D', index_dir,'-d', prefix, tmpFasta], stdout=corrSAM_out)
with open(corrGFF_gmap, 'w') as corrGFF_out:
subprocess.call(['gmap','-n', '1', '-t', threads, '--cross-species', '--gff3-add-separators=0','-f', '2', '-z', sense,'-D', index_dir,'-d', prefix, tmpFasta], stdout=corrGFF_out)
os.remove(tmpFasta)
except (RuntimeError, TypeError, NameError):
sys.stderr.write('ERROR: Problem during alignment of sequences.\n')
raise SystemExit(1)
#GFF GMAP to accurate GFF
with open(corrGFF, 'w') as corrGFF_out:
with open(corrGFF_gmap, 'r') as corrGFF_in:
for i in corrGFF_in:
if i[0] != "#" and i.split("\t")[2] != "CDS":
if (".mrna1" in i) or (".path1" in i):
j = i.replace(".mrna1","")
k = j.replace(".path1", ".gene")
corrGFF_out.write(k)
# GFF to GTF
subprocess.call([utilitiesPath+"gffread", corrGFF , '-T', '-o', corrGTF])
os.remove(corrGFF_gmap)
os.remove(corrGFF)
del fastaDicc
else:
sys.stderr.write("ERROR: '%s' directory containing gmap indexes doesn't exist.\n" % (os.path.dirname(args.gmap_index)))
sys.exit()
if args.gtf:
sys.stdout.write("\nSkipping aligning of sequences because gtf file was provided.\n")
ind = 0
with open(args.isoforms, 'r') as isoforms_gtf:
for line in isoforms_gtf:
if line[0] != "#" and len(line.split("\t"))!=9:
sys.stderr.write("\nERROR: input isoforms file with not gtf format.\n")
sys.exit()
elif len(line.split("\t"))==9:
ind += 1
if ind==0:
sys.stderr.write("\nERROR: gtf has not annotation lines.\n")
sys.exit()
# GFF to GTF (in case the user provides gff instead of gtf)
corrGTF_tpm = corrGTF+".tmp"
try:
subprocess.call([utilitiesPath+"gffread", args.isoforms , '-T', '-o', corrGTF_tpm])
except (RuntimeError, TypeError, NameError):
sys.stderr.write('ERROR: File %s without gtf/gff format.\n' % args.isoforms)
raise SystemExit(1)
# check if gtf chromosomes inside genome file
with open(corrGTF, 'w') as corrGTF_out:
with open(corrGTF_tpm, 'r') as isoforms_gtf:
for line in isoforms_gtf:
if line[0] != "#":
chrom = line.split("\t")[0]
type = line.split("\t")[2]
if chrom not in chrom_names:
sys.stderr.write("\nERROR: gtf \"%s\" chromosome not found in genome reference file.\n" % (chrom))
sys.exit()
elif type=="exon":
corrGTF_out.write(line)
os.remove(corrGTF_tpm)
if not os.path.exists(corrSAM):
sys.stdout.write("\nIndels will be not calculated since you ran SQANTI without alignment step (SQANTI with gtf format as transcriptome input).\n")
# Corrected gtf to fasta
subprocess.call([utilitiesPath+"gffread", corrGTF, '-g', args.genome, '-w', corrFASTA])
# ORF generation
sys.stdout.write("\n**** Predicting ORF sequences...\n")
gmst_dir = args.dir+"/GMST/"
if not os.path.exists(gmst_dir):
os.makedirs(gmst_dir)
subprocess.call(["perl", utilitiesPath+"gmst/gmst.pl", corrFASTA , '-faa', '--strand','direct', '--fnn', '--output', os.path.splitext(os.path.basename(args.isoforms))[0]+"_corrected"], cwd=gmst_dir)
if os.path.isfile(gmst_dir+os.path.basename(ORF)):
os.rename(gmst_dir+os.path.basename(ORF), ORF)
# Modifying ORF sequences by removing sequence before ATG
ORFdicc = fasta_parser(ORF)
corrORF_file = open(corrORF, "w")
orfLenDicc = {}
for ID in ORFdicc:
seq = ORFdicc[ID]
l = len(ID.split("\t"))
pos = seq.find('M')
if pos != -1:
corr_seq = seq[pos:]
cds_start = int(ID.split("\t")[l-1].split("|")[4])+pos*3
cds_end = int(ID.split("\t")[l-1].split("|")[5])
strand = ID.split("\t")[l-1].split("|")[3]
ID_mod = ID.split()[0].strip()+"\t"+"isoform|GeneMark.hmm|"+ str(len(corr_seq)) + "_aa|" + strand + "|" + str(cds_start) +"|" + str(cds_end)
corrORF_file.write(">"+ID_mod+"\n"+corr_seq+"\n")
orfLenDicc[ID.split()[0].strip()] = myQueryProteins(cds_start, (cds_start+len(corr_seq)*3-1), len(corr_seq))
corrORF_file.close()
del ORFdicc
os.remove(ORF)
else:
corrORF_file = open(corrORF, "w")
corrORF_file.close()
orfLenDicc={}
if len(orfLenDicc)==0:
sys.stderr.write("WARNING: All input isoforms were predicted as non-coding")
os.rename(corrORF, ORF)
gc.collect()
return(orfLenDicc)
def reference_parser(args, chrom_names):
global referenceFiles
referenceFiles = args.dir+"/refAnnotation_"+args.output+".genePred"
sys.stdout.write("\n**** Parsing Reference Transcriptome...\n")
ind = 0
with open(args.annotation, 'r') as reference_gtf:
for line in reference_gtf:
if line[0] != "#" and len(line.split("\t"))!=9:
sys.stderr.write("\nERROR: reference annotation file with not gtf/gff format.\n")
sys.exit()
elif len(line.split("\t"))==9:
ind += 1
if ind==0:
sys.stderr.write("\nERROR: reference annotation file has not annotation lines.\n")
sys.exit()
## gtf to genePred
if args.name:
subprocess.call([utilitiesPath+"gtfToGenePred", args.annotation, referenceFiles, '-genePredExt', '-allErrors', '-ignoreGroupsWithoutExons', '-geneNameAsName2'])
else:
subprocess.call([utilitiesPath+"gtfToGenePred", args.annotation, referenceFiles, '-genePredExt', '-allErrors', '-ignoreGroupsWithoutExons'])
if not os.path.exists(referenceFiles):
sys.exit()
## parsing annotation while filtering miRNA RNAs
# dicc of transcripts. We differenciate between single-exon transcripts and multi-exon transcripts.
transcripts_chrom_1exon = {}
transcripts_chrom_exons = {}
# dicc of genes
transcripts_gene = {}
missingChroms = []
referenceFiles_tpm = referenceFiles+"notmiRNAtmp"
flag=True
with open(referenceFiles_tpm, 'w') as inputAnnotationNotmiRNAs:
with open(referenceFiles, 'r') as inputAnnotation:
for i in inputAnnotation:
line_split = i.split("\t")
if len(line_split[8].split(",")) < 3:
if (int(line_split[9].split(",")[0]) - int(line_split[8].split(",")[0])) > 200:
inputAnnotationNotmiRNAs.write(i)
flag=True
else:
flag=False
else:
inputAnnotationNotmiRNAs.write(i)
flag=True
if flag==True:
transcript_id = line_split[0]
chrom = line_split[1]
if (chrom not in chrom_names) and (chrom not in missingChroms):
missingChroms.append(chrom)
strand = line_split[2]
gene = line_split[11]
if gene == "":
continue
#add gene info
if gene not in transcripts_gene:
transcripts_gene[gene] = refGenes(gene, chrom, strand)
transcripts_gene[gene].add_transcript(line_split, strand)
#add transcript info
if len(line_split[8].split(",")) > 2: # multiple-exon isoform
if chrom not in transcripts_chrom_exons:
transcripts_chrom_exons[chrom]=[]
a = refTranscripts(transcript_id, gene, chrom, strand)
a.add_information(line_split, strand)
transcripts_chrom_exons[chrom].append(a)
else: #single-exon isoform
if chrom not in transcripts_chrom_1exon:
transcripts_chrom_1exon[chrom]=[]
a = refTranscripts(transcript_id, gene, chrom, strand)
a.add_information(line_split, strand)
transcripts_chrom_1exon[chrom].append(a)
os.rename(referenceFiles_tpm, referenceFiles)
if len(missingChroms)>0:
sys.stderr.write("\nWARNING: %s sequences not found in genome but containing annotated genes\n" %(",".join(missingChroms)))
## sorting transcript information by first junction (if mono-exon transcript we sort by first exon)
sum=0
for chrom in transcripts_chrom_exons:
transcripts_chrom_exons[chrom] = sorted(transcripts_chrom_exons[chrom], key = lambda tup:int(tup.junctions[0][0]))
sum = len(transcripts_chrom_exons[chrom]) + sum
for chrom in transcripts_chrom_1exon:
transcripts_chrom_1exon[chrom] = sorted(transcripts_chrom_1exon[chrom], key = lambda tup:int(tup.exons[0][0]))
sum = len(transcripts_chrom_1exon[chrom]) + sum
## dicc for chomosome and inside gene information. Got from transcripts_gene dicc.
transcripts_gene_chrom = {}
for gene in transcripts_gene.keys():
chrom = transcripts_gene[gene].chrom
if chrom not in transcripts_gene_chrom:
transcripts_gene_chrom[chrom]=[]
transcripts_gene_chrom[chrom].append(transcripts_gene[gene])
for chrom in transcripts_gene_chrom:
transcripts_gene_chrom[chrom] = sorted(transcripts_gene_chrom[chrom], key = lambda tup:min(tup.tss + tup.tts)) ##### COMPROBAR QUE ESTA BIEN!!!!
return (transcripts_chrom_1exon, transcripts_chrom_exons, transcripts_gene, transcripts_gene_chrom)
def isoforms_parser(args):
global queryFile
queryFile = os.path.splitext(corrGTF)[0] +".genePred"
sys.stdout.write("\n**** Parsing Isoforms...\n")
# gtf to genePred
try:
subprocess.call([utilitiesPath+"gtfToGenePred", corrGTF, queryFile , '-genePredExt', '-allErrors', '-ignoreGroupsWithoutExons'])
except (RuntimeError, TypeError, NameError):
sys.stderr.write('ERROR: Check isoforms file.\n' )
raise SystemExit(1)
## analysis of query transcripts
queryAnnotation = open(queryFile, 'r')
myQueryTranscripts_list = []
for line in queryAnnotation:
exon_s = line.split("\t")[8].split(",")[0:-1]
exon_e = line.split("\t")[9].split(",")[0:-1]
if len(exon_s) >= 2: #junctions only if multiple-exon isoforms
coordToSort = int(exon_e[0]) #first genomic splice site
else:
coordToSort = int(exon_s[0]) #first exon position
a = myQueries(line, coordToSort)
myQueryTranscripts_list.append(a)
queryAnnotation.close()
# sorting the subject transcript by start junction or start exon (depending if one or more exons)
myQueryTranscripts_list = sorted(myQueryTranscripts_list, key = lambda tup:int(tup.coordToSort))
return(myQueryTranscripts_list)
def STARcov_parser(coverageFiles): # just valid with unstrand-specific RNA-seq protocols.
#may be one file, files separated by comma or a directory where file are.
if os.path.isdir(coverageFiles)==True:
cov_paths = [os.path.join(coverageFiles,fn) for fn in next(os.walk(coverageFiles))[2]]
else:
cov_paths = coverageFiles.split(",")
cov_list_dicc = {}
for path in cov_paths:
dicc = {}
p = open(path.strip(), "r")
for line in p:
j = "_".join(line.split()[0:3])
dicc[j] = str(int(line.split()[6])+int(line.split()[7]))
cov_list_dicc[os.path.basename(path)] = dicc
p.close()
return(cov_list_dicc)
def expression_parser_old(expressionFile):
try:
p = open(expressionFile, "r")
except IOError:
sys.stderr.write('ERROR: Unable to read %s expression file\n' % expressionFile)
raise SystemExit(1)
try:
header = p.readline()
exp_dicc = {}
for line in p:
pbid = line.split()[0]
mean = sum([float(i) for i in line.rstrip().split()[1:]])/len(line.rstrip().split()[1:])
exp_dicc[pbid] = mean
p.close()
except IOError:
sys.stderr.write('File %s without expression matrix format' % expressionFile)
raise SystemExit(1)
return(exp_dicc)
def expression_parser(expressionFile):
try:
p = open(expressionFile, "r")
except IOError:
sys.stderr.write('ERROR: Unable to read %s expression file\n' % expressionFile)
raise SystemExit(1)
try:
header = p.readline()
exp_dicc = {}
for line in p:
pbid = line.split()[0]
if len(pbid.split("|"))>2 and pbid[0:2]=="PB": # PacBio fasta header (including chained format)
pbid_mod = pbid.split("|")[0].split(" ")[0]
elif len(pbid.split("|"))>4: # Refseq fasta header
pbid_mod = pbid.split("|")[3]
else:
pbid_mod = pbid.split()[0] # Ensembl fasta header
mean = sum([float(i) for i in line.rstrip().split()[1:]])/len(line.rstrip().split()[1:])
exp_dicc[pbid_mod] = mean
p.close()
except IOError:
sys.stderr.write('File %s without expression matrix format' % expressionFile)
raise SystemExit(1)
return(exp_dicc)
def transcriptsKnownSpliceSites(transcripts_chrom_1exon, transcripts_chrom_exons, line_split, index_chrom_exons, index_chrom_1exon, transcripts_gene, seq, nPolyA):
# Transcript information for a single query transcript and comparison with reference.
query_transcript = line_split[0]
CHROM = line_split[1]
STRAND = line_split[2]
EXON_s = [int(i)+1 for i in line_split[8].split(",")[0:-1]]
EXON_e = [int(i) for i in line_split[9].split(",")[0:-1]]
isoLength = transcriptLength(EXON_s, EXON_e)
JUNCTIONS_e = [int(i)-1 for i in EXON_s[1:] ]
JUNCTIONS_s = [int(i)+1 for i in EXON_e[:-1]]
ends_positions = []
myTranscript_Assoc=""
JUNCTIONS = []
[JUNCTIONS.append([JUNCTIONS_s[m],JUNCTIONS_e[m]]) for m in range(len(JUNCTIONS_s))]
EXONS_COORD = exons_together(EXON_s, EXON_e)
# # Intra-priming
# if STRAND == "+":
# TTS = int(EXON_e[-1])
# downTTS = str(seq[CHROM].seq[TTS:(int(EXON_e[-1])+nPolyA)])
# downTTS = downTTS.upper()
# if any([base not in ["A","T","C","G","N"] for base in downTTS]):
# sys.stderr.write("Error: %s in 3' TTS genomic downstream region is NOT a DNA sequence in genome file" %(downTTS))
# percA = 0
# elif STRAND == "-":
# TTS = int(EXON_s[0])
# downTTS = ReverseComplement(str(seq[CHROM].seq[int(EXON_s[0]-nPolyA):TTS]))
# percA = downTTS.count('A')/nPolyA*100
if STRAND == "+":
TTS = int(EXON_e[-1])
downTTS = str(seq[CHROM][TTS:(int(EXON_e[-1])+nPolyA)])
downTTS = downTTS.upper()
if any([base not in ["A","T","C","G","N"] for base in downTTS]):
sys.stderr.write("Error: %s in 3' TTS genomic downstream region is NOT a DNA sequence in genome file" %(downTTS))
percA = 0
elif STRAND == "-":
TTS = int(EXON_s[0])
downTTS = ReverseComplement(str(seq[CHROM][int(EXON_s[0]-(nPolyA+1)):(TTS-1)]))
percA = float(downTTS.count('A'))/nPolyA*100
myTranscript_Assoc = myQueryTranscripts("", "NA","NA",len(EXON_s),isoLength, "", chrom=CHROM, strand=STRAND, subtype="no_subcategory", percAdownTTS=str(percA))
##***************************************##
########### SPLICED TRANSCRIPTS ###########
##***************************************##
if len(EXON_s) >= 2: #junctions only if multiple-exon isoforms
if CHROM in transcripts_chrom_exons:
if CHROM not in index_chrom_exons:
index_chrom_exons[CHROM] = 0
for k in range(index_chrom_exons[CHROM], len(transcripts_chrom_exons[CHROM])):
subtype = "no_category"
ref_transcript = transcripts_chrom_exons[CHROM][k]
junctions_s = ref_transcript.junctions[0]
junctions_e = ref_transcript.junctions[1]
junctions = []
[junctions.append([junctions_s[n],junctions_e[n]]) for n in range(len(junctions_s))]
ends_positions.append(int(junctions_e[-1]))
########### SAME STRAND ###########
if ref_transcript.strand == STRAND:
if all(item < int(JUNCTIONS_s[0]) for item in ends_positions) :
index_chrom_exons[CHROM] = index_chrom_exons[CHROM] + 1
elif int(junctions_s[0]) > int(JUNCTIONS_e[-1]):
break
else:
#######################################
##### 1. Check full-splice match ######
#######################################
if (JUNCTIONS_e==junctions_e and JUNCTIONS_s==junctions_s): #splice junctions are identical
tss = int(ref_transcript.tss)
tts = int(ref_transcript.tts)
if STRAND == "+":
TSS = EXON_s[0]
TTS = EXON_e[-1]
tss_diff = int(TSS) - tss
tts_diff = tts - int(TTS)
else:
TTS = EXON_s[0]
TSS = EXON_e[-1]
tss_diff = tss - int(TSS)
tts_diff = int(TTS) - tts
if myTranscript_Assoc.str_class!="full-splice_match":
myTranscript_Assoc = myQueryTranscripts(ref_transcript.transcript, tss_diff, tts_diff, len(EXON_s), isoLength, "full-splice_match", subtype="multi-exon", chrom=CHROM, strand=STRAND, refLen = ref_transcript.transcriptLength(), refExons= len(ref_transcript.exons[0]), percAdownTTS=str(percA))
myTranscript_Assoc.transcripts = []
myTranscript_Assoc.transcripts.append(ref_transcript.transcript)
myTranscript_Assoc.genes = []
myTranscript_Assoc.genes.append(ref_transcript.gene)
elif (abs(tss_diff) + abs(tts_diff)) < myTranscript_Assoc.get_total_diff():
myTranscript_Assoc.genes = []
myTranscript_Assoc.modify(ref_transcript.transcript, ref_transcript.gene, tss_diff, tts_diff, ref_transcript.transcriptLength(), len(ref_transcript.exons[0]))
else:
myTranscript_Assoc.transcripts.append(ref_transcript.transcript)
####################################################################
##### 2. Check fragment-splice match if none full-splice match ######
####################################################################
elif myTranscript_Assoc.str_class!="full-splice_match" and all(s in junctions for s in JUNCTIONS): #check if it's a fragment of a reference transcript if not perfect match found. Just in case you have not found before another perfect match (because we don't break the loop if found a perfect match since we want the similar one (utr differences))
exons_coord = exons_together(ref_transcript.exons[0], ref_transcript.exons[1])
differential_nt = list(set(EXONS_COORD) - set(exons_coord))
longerUTRs = all((int(d) < int(ref_transcript.exons[0][0]) or int(d) > int(ref_transcript.exons[1][-1]) ) for d in differential_nt) # extra-nt in query are for differences in utrs
if len(differential_nt)==0 or longerUTRs:
if STRAND == "+":
(tss_diff, tts_diff) = ref_transcript.difference_fragment_transcript(EXON_s[0], EXON_e[-1], exons_coord)
LAST5JUNCTION = [JUNCTIONS_s[0], JUNCTIONS_e[0]]
LAST3JUNCTION = [JUNCTIONS_e[-1], JUNCTIONS_e[-1]]
last5junction = [junctions_s[0], junctions_e[0]]
last3junction = [junctions_s[-1], junctions_e[-1]]
else:
(tts_diff, tss_diff) = ref_transcript.difference_fragment_transcript(EXON_s[0], EXON_e[-1], exons_coord)
LAST3JUNCTION = [JUNCTIONS_s[0], JUNCTIONS_e[0]]
LAST5JUNCTION = [JUNCTIONS_e[-1], JUNCTIONS_e[-1]]
last3junction = [junctions_s[0], junctions_e[0]]
last5junction = [junctions_s[-1], junctions_e[-1]]
if (LAST5JUNCTION!=last5junction) and (LAST3JUNCTION != last3junction):
subtype = "internal_fragment"
elif LAST5JUNCTION != last5junction:
subtype = "5prime_fragment"
elif LAST3JUNCTION != last3junction:
subtype = "3prime_fragment"
else:
subtype = "complete"
if myTranscript_Assoc.str_class!="incomplete-splice_match":
myTranscript_Assoc = myQueryTranscripts(ref_transcript.transcript, tss_diff, tts_diff, len(EXON_s), isoLength,"incomplete-splice_match", subtype=subtype, chrom=CHROM, strand=STRAND, refLen = ref_transcript.transcriptLength(), refExons= len(ref_transcript.exons[0]), percAdownTTS=str(percA))
myTranscript_Assoc.transcripts.append(ref_transcript.transcript)
myTranscript_Assoc.genes = []
myTranscript_Assoc.genes.append(ref_transcript.gene)
elif (abs(tss_diff) + abs(tts_diff)) < myTranscript_Assoc.get_total_diff():
myTranscript_Assoc.genes = []
myTranscript_Assoc.modify(ref_transcript.transcript, ref_transcript.gene, tss_diff, tts_diff, ref_transcript.transcriptLength(), len(ref_transcript.exons[0]))
else:
myTranscript_Assoc.transcripts.append(ref_transcript.transcript)
########################################################################
##### 3. Association of transcripts to genes by sharing junctions ######
########################################################################