-
Notifications
You must be signed in to change notification settings - Fork 1
/
sqanti3_lrgasp.challenge1.py
executable file
·2404 lines (2101 loc) · 121 KB
/
sqanti3_lrgasp.challenge1.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 python3
# SQANTI: Structural and Quality Annotation of Novel Transcript Isoforms
# Authors: Lorena de la Fuente, Hector del Risco, Cecile Pereira and Manuel Tardaguila
# Modified by Liz ([email protected]) as SQANTI2/3 versions
# Modified by Fran ([email protected]) currently as SQANTI3 LRGASP challenge 1 version (07/21/2021)
__author__ = "[email protected]"
__version__ = 'LRGASP_v1.2' # Python 3.7
import pdb
import os, re, sys, subprocess, timeit, glob, copy
import shutil
import distutils.spawn
import itertools
import bisect
import argparse
import math
import numpy as np
from scipy import mean
from collections import defaultdict, Counter, namedtuple
from collections.abc import Iterable
from csv import DictWriter, DictReader
from multiprocessing import Process
utilitiesPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "utilities")
sys.path.insert(0, utilitiesPath)
from rt_switching import rts
from indels_annot import calc_indels_from_sam
from json_parser import json_parser
from read_model2counts import get_counts
try:
from Bio.Seq import Seq
from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
except ImportError:
print("Unable to import Biopython! Please make sure Biopython is installed.", file=sys.stderr)
sys.exit(-1)
try:
from bx.intervals import Interval, IntervalTree
except ImportError:
print("Unable to import bx-python! Please make sure bx-python is installed.", file=sys.stderr)
sys.exit(-1)
try:
from BCBio import GFF as BCBio_GFF
except ImportError:
print("Unable to import BCBio! Please make sure bcbiogff is installed.", file=sys.stderr)
sys.exit(-1)
try:
from err_correct_w_genome import err_correct
from sam_to_gff3 import convert_sam_to_gff3
from STAR import STARJunctionReader
from BED import LazyBEDPointReader
import coordinate_mapper as cordmap
except ImportError:
print("Unable to import err_correct_w_genome or sam_to_gff3.py! Please make sure cDNA_Cupcake/sequence/ is in $PYTHONPATH.", file=sys.stderr)
sys.exit(-1)
try:
from cupcake.tofu.compare_junctions import compare_junctions
from cupcake.tofu.filter_away_subset import read_count_file
from cupcake.io.BioReaders import GMAPSAMReader
from cupcake.io.GFF import collapseGFFReader, write_collapseGFF_format
except ImportError:
print("Unable to import cupcake.tofu! Please make sure you install cupcake.", file=sys.stderr)
sys.exit(-1)
# check cupcake version
import cupcake
v1, v2 = [int(x) for x in cupcake.__version__.split('.')]
if v1 < 8 or v2 < 6:
print("Cupcake version must be 8.6 or higher! Got {0} instead.".format(cupcake.__version__), file=sys.stderr)
sys.exit(-1)
GMAP_CMD = "gmap --cross-species -n 1 --max-intronlength-middle=2000000 --max-intronlength-ends=2000000 -L 3000000 -f samse -t {cpus} -D {dir} -d {name} -z {sense} {i} | samtools view -F2048 -h > {o}"
#MINIMAP2_CMD = "minimap2 -ax splice --secondary=no -C5 -O6,24 -B4 -u{sense} -t {cpus} {g} {i} > {o}"
MINIMAP2_CMD = "minimap2 -ax splice --secondary=no -C5 -u{sense} -t {cpus} {g} {i} | samtools view -F2048 -h > {o}"
DESALT_CMD = "deSALT aln {dir} {i} -t {cpus} -x ccs -o {o}"
GMSP_PROG = os.path.join(utilitiesPath, "gmst", "gmst.pl")
GMST_CMD = "perl " + GMSP_PROG + " -faa --strand direct --fnn --output {o} {i}"
GTF2GENEPRED_PROG = os.path.join(utilitiesPath,"gtfToGenePred")
GFFREAD_PROG = "gffread"
if distutils.spawn.find_executable(GTF2GENEPRED_PROG) is None:
print("Cannot find executable {0}. Abort!".format(GTF2GENEPRED_PROG), file=sys.stderr)
sys.exit(-1)
if distutils.spawn.find_executable(GFFREAD_PROG) is None:
print("Cannot find executable {0}. Abort!".format(GFFREAD_PROG), file=sys.stderr)
sys.exit(-1)
seqid_rex1 = re.compile('PB\.(\d+)\.(\d+)$')
seqid_rex2 = re.compile('PB\.(\d+)\.(\d+)\|\S+')
seqid_fusion = re.compile("PBfusion\.(\d+)\.(\d+)\S*")
FIELDS_JUNC = ['isoform', 'chrom', 'strand', 'junction_number', 'genomic_start_coord',
'genomic_end_coord', 'transcript_coord', 'junction_category',
'start_site_category', 'end_site_category', 'diff_to_Ref_start_site',
'diff_to_Ref_end_site', 'bite_junction', 'splice_site', 'canonical',
'RTS_junction', 'indel_near_junct',
'phyloP_start', 'phyloP_end', 'sample_with_cov', "total_coverage"] #+coverage_header
FIELDS_CLASS = ['isoform', 'chrom', 'strand', 'length', 'exons', 'structural_category',
'associated_gene', 'associated_transcript', 'ref_length', 'ref_exons',
'diff_to_TSS', 'diff_to_TTS', 'diff_to_gene_TSS', 'diff_to_gene_TTS',
'subcategory', 'RTS_stage', 'all_canonical',
'min_sample_cov', 'min_cov', 'min_cov_pos', 'sd_cov', 'FL', 'n_indels',
'n_indels_junc', 'bite', 'iso_exp', 'gene_exp', 'ratio_exp',
'FSM_class', 'coding', 'ORF_length', 'CDS_length', 'CDS_start',
'CDS_end', 'CDS_genomic_start', 'CDS_genomic_end', 'predicted_NMD',
'perc_A_downstream_TTS', 'seq_A_downstream_TTS',
'dist_to_cage_peak', 'within_cage_peak', 'pos_cage_peak',
'dist_to_polya_site', 'within_polya_site',
'polyA_motif', 'polyA_dist', 'ORF_seq', 'TSS_genomic_coord', 'TTS_genomic_coord',
'experiment_id', 'entry_id']
RSCRIPTPATH = distutils.spawn.find_executable('Rscript')
RSCRIPT_REPORT = 'SQANTI3_Evaluation_run.R'
if os.system( RSCRIPTPATH + " --version")!=0:
print("Rscript executable not found! Abort!", file=sys.stderr)
sys.exit(-1)
SPLIT_ROOT_DIR = 'splits/'
class genePredReader(object):
def __init__(self, filename):
self.f = open(filename)
def __iter__(self):
return self
def __next__(self):
line = self.f.readline().strip()
if len(line) == 0:
raise StopIteration
return genePredRecord.from_line(line)
class genePredRecord(object):
def __init__(self, id, chrom, strand, txStart, txEnd, cdsStart, cdsEnd, exonCount, exonStarts, exonEnds, gene=None):
self.id = id
self.chrom = chrom
self.strand = strand
self.txStart = txStart # 1-based start
self.txEnd = txEnd # 1-based end
self.cdsStart = cdsStart # 1-based start
self.cdsEnd = cdsEnd # 1-based end
self.exonCount = exonCount
self.exonStarts = exonStarts # 0-based starts
self.exonEnds = exonEnds # 1-based ends
self.gene = gene
self.length = 0
self.exons = []
for s,e in zip(exonStarts, exonEnds):
self.length += e-s
self.exons.append(Interval(s, e))
# junctions are stored (1-based last base of prev exon, 1-based first base of next exon)
self.junctions = [(self.exonEnds[i],self.exonStarts[i+1]) for i in range(self.exonCount-1)]
@property
def segments(self):
return self.exons
@classmethod
def from_line(cls, line):
raw = line.strip().split('\t')
return cls(id=raw[0],
chrom=raw[1],
strand=raw[2],
txStart=int(raw[3]),
txEnd=int(raw[4]),
cdsStart=int(raw[5]),
cdsEnd=int(raw[6]),
exonCount=int(raw[7]),
exonStarts=[int(x) for x in raw[8][:-1].split(',')], #exonStarts string has extra , at end
exonEnds=[int(x) for x in raw[9][:-1].split(',')], #exonEnds string has extra , at end
gene=raw[11] if len(raw)>=12 else None,
)
def get_splice_site(self, genome_dict, i):
"""
Return the donor-acceptor site (ex: GTAG) for the i-th junction
:param i: 0-based junction index
:param genome_dict: dict of chrom --> SeqRecord
:return: splice site pattern, ex: "GTAG", "GCAG" etc
"""
assert 0 <= i < self.exonCount-1
d = self.exonEnds[i]
a = self.exonStarts[i+1]
seq_d = genome_dict[self.chrom].seq[d:d+2]
seq_a = genome_dict[self.chrom].seq[a-2:a]
if self.strand == '+':
return (str(seq_d)+str(seq_a)).upper()
else:
return (str(seq_a.reverse_complement())+str(seq_d.reverse_complement())).upper()
class myQueryTranscripts:
def __init__(self, id, tss_diff, tts_diff, num_exons, length, str_class, subtype=None,
genes=None, transcripts=None, chrom=None, strand=None, bite ="NA",
RT_switching ="????", canonical="NA", min_cov ="NA",
min_cov_pos ="NA", min_samp_cov="NA", sd ="NA", FL ="NA", FL_dict={},
nIndels ="NA", nIndelsJunc ="NA", proteinID=None,
ORFlen="NA", CDS_start="NA", CDS_end="NA",
CDS_genomic_start="NA", CDS_genomic_end="NA",
ORFseq="NA",
is_NMD="NA",
isoExp ="NA", geneExp ="NA", coding ="non_coding",
refLen ="NA", refExons ="NA",
refStart = "NA", refEnd = "NA",
q_splicesite_hit = 0,
q_exon_overlap = 0,
FSM_class = None, percAdownTTS = None, seqAdownTTS=None,
dist_cage='NA', within_cage='NA', pos_cage_peak='NA',
dist_polya_site='NA', within_polya_site='NA',
polyA_motif='NA', polyA_dist='NA',
TSS_genomic_coord='NA', TTS_genomic_coord='NA',
experiment_id='NA', entry_id='NA'):
self.id = id
self.tss_diff = tss_diff # distance to TSS of best matching ref
self.tts_diff = tts_diff # distance to TTS of best matching ref
self.tss_gene_diff = 'NA' # min distance to TSS of all genes matching the ref
self.tts_gene_diff = 'NA' # min distance to TTS of all genes matching the ref
self.genes = genes if genes is not None else []
self.AS_genes = set() # ref genes that are hit on the opposite strand
self.transcripts = transcripts if transcripts is not None else []
self.num_exons = num_exons
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.ORFseq = ORFseq
self.CDS_start = CDS_start
self.CDS_end = CDS_end
self.coding = coding
self.CDS_genomic_start = CDS_genomic_start # 1-based genomic coordinate of CDS start - strand aware
self.CDS_genomic_end = CDS_genomic_end # 1-based genomic coordinate of CDS end - strand aware
self.is_NMD = is_NMD # (TRUE,FALSE) for NMD if is coding, otherwise "NA"
self.FL = FL # count for a single sample
self.FL_dict = FL_dict # dict of sample -> FL count
self.nIndels = nIndels
self.nIndelsJunc = nIndelsJunc
self.isoExp = isoExp
self.geneExp = geneExp
self.refLen = refLen
self.refExons = refExons
self.refStart = refStart
self.refEnd = refEnd
self.q_splicesite_hit = q_splicesite_hit
self.q_exon_overlap = q_exon_overlap
self.FSM_class = FSM_class
self.bite = bite
self.percAdownTTS = percAdownTTS
self.seqAdownTTS = seqAdownTTS
self.dist_cage = dist_cage
self.within_cage = within_cage
self.pos_cage_peak = pos_cage_peak
self.within_polya_site = within_polya_site
self.dist_polya_site = dist_polya_site # distance to the closest polyA site (--polyA_peak, BEF file)
self.polyA_motif = polyA_motif
self.polyA_dist = polyA_dist # distance to the closest polyA motif (--polyA_motif_list, 6mer motif list)
self.TSS_genomic_coord = TSS_genomic_coord # genomic coordinates of TSS
self.TTS_genomic_coord = TTS_genomic_coord # genomic coordinates of TTS
self.experiment_id = experiment_id
self.entry_id = entry_id
def get_total_diff(self):
return abs(self.tss_diff)+abs(self.tts_diff)
def modify(self, ref_transcript, ref_gene, tss_diff, tts_diff, refLen, refExons):
self.transcripts = [ref_transcript]
self.genes = [ref_gene]
self.tss_diff = tss_diff
self.tts_diff = tts_diff
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\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.num_exons),
str(self.str_class), "_".join(set(self.genes)),
self.id, 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.CDS_genomic_start), str(self.CDS_genomic_end), str(self.is_NMD),
str(self.percAdownTTS),
str(self.seqAdownTTS),
str(self.dist_cage),
str(self.within_cage),str(self.pos_cage_peak),
str(self.dist_polya_site),
str(self.within_polya_site),
str(self.polyA_motif),
str(self.polyA_dist), str(self.TSS_genomic_coord), str(self.TTS_genomic_coord),
str(self.experiment_id), str(self.entry_id))
def as_dict(self):
d = {'isoform': self.id,
'chrom': self.chrom,
'strand': self.strand,
'length': self.length,
'exons': self.num_exons,
'structural_category': self.str_class,
'associated_gene': "_".join(set(self.genes)),
'associated_transcript': "_".join(set(self.transcripts)),
'ref_length': self.refLen,
'ref_exons': self.refExons,
'diff_to_TSS': self.tss_diff,
'diff_to_TTS': self.tts_diff,
'diff_to_gene_TSS': self.tss_gene_diff,
'diff_to_gene_TTS': self.tts_gene_diff,
'subcategory': self.subtype,
'RTS_stage': self.RT_switching,
'all_canonical': self.canonical,
'min_sample_cov': self.min_samp_cov,
'min_cov': self.min_cov,
'min_cov_pos': self.min_cov_pos,
'sd_cov': self.sd,
'FL': self.FL,
'n_indels': self.nIndels,
'n_indels_junc': self.nIndelsJunc,
'bite': self.bite,
'iso_exp': self.isoExp,
'gene_exp': self.geneExp,
'ratio_exp': self.ratioExp(),
'FSM_class': self.FSM_class,
'coding': self.coding,
'ORF_length': self.ORFlen,
'ORF_seq': self.ORFseq,
'CDS_length': self.CDSlen(),
'CDS_start': self.CDS_start,
'CDS_end': self.CDS_end,
'CDS_genomic_start': self.CDS_genomic_start,
'CDS_genomic_end': self.CDS_genomic_end,
'predicted_NMD': self.is_NMD,
'perc_A_downstream_TTS': self.percAdownTTS,
'seq_A_downstream_TTS': self.seqAdownTTS,
'dist_to_cage_peak': self.dist_cage,
'within_cage_peak': self.within_cage,
'pos_cage_peak' : self.pos_cage_peak,
'dist_to_polya_site': self.dist_polya_site,
'within_polya_site': self.within_polya_site,
'polyA_motif': self.polyA_motif,
'polyA_dist': self.polyA_dist,
'TSS_genomic_coord': self.TSS_genomic_coord,
'TTS_genomic_coord': self.TTS_genomic_coord,
'experiment_id': self.experiment_id,
'entry_id': self.entry_id,
}
for sample,count in self.FL_dict.items():
d["FL."+sample] = count
return d
class myQueryProteins:
def __init__(self, cds_start, cds_end, orf_length, orf_seq=None, proteinID="NA"):
self.orf_length = orf_length
self.cds_start = cds_start # 1-based start on transcript
self.cds_end = cds_end # 1-based end on transcript (stop codon), ORF is seq[cds_start-1:cds_end].translate()
self.cds_genomic_start = None # 1-based genomic start of ORF, if - strand, is greater than end
self.cds_genomic_end = None # 1-based genomic end of ORF
self.orf_seq = orf_seq
self.proteinID = proteinID
def write_collapsed_GFF_with_CDS(isoforms_info, input_gff, output_gff):
"""
Augment a collapsed GFF with CDS information
*NEW* Also, change the "gene_id" field to use the classification result
:param isoforms_info: dict of id -> QueryTranscript
:param input_gff: input GFF filename
:param output_gff: output GFF filename
"""
with open(output_gff, 'w') as f:
reader = collapseGFFReader(input_gff)
for r in reader:
r.geneid = isoforms_info[r.seqid].geneName() # set the gene name
s = isoforms_info[r.seqid].CDS_genomic_start # could be 'NA'
e = isoforms_info[r.seqid].CDS_genomic_end # could be 'NA'
r.cds_exons = []
if s!='NA' and e!='NA': # has ORF prediction for this isoform
if r.strand == '+':
assert s < e
s = s - 1 # make it 0-based
else:
assert e < s
s, e = e, s
s = s - 1 # make it 0-based
for i,exon in enumerate(r.ref_exons):
if exon.end > s: break
r.cds_exons = [Interval(s, min(e,exon.end))]
for exon in r.ref_exons[i+1:]:
if exon.start > e: break
r.cds_exons.append(Interval(exon.start, min(e, exon.end)))
write_collapseGFF_format(f, r)
def get_corr_filenames(args, dir=None):
d = dir if dir is not None else args.dir
corrPathPrefix = os.path.join(d, args.output)
corrGTF = corrPathPrefix +"_corrected.gtf"
corrSAM = corrPathPrefix +"_corrected.sam"
corrFASTA = corrPathPrefix +"_corrected.fasta"
corrORF = corrPathPrefix +"_corrected.faa"
return corrGTF, corrSAM, corrFASTA, corrORF
def get_class_junc_filenames(args, dir=None):
d = dir if dir is not None else args.dir
outputPathPrefix = os.path.join(d, args.output)
outputClassPath = outputPathPrefix + "_classification.txt"
outputJuncPath = outputPathPrefix + "_junctions.txt"
return outputClassPath, outputJuncPath
def correctionPlusORFpred(args, genome_dict):
"""
Use the reference genome to correct the sequences (unless a pre-corrected GTF is given)
"""
global corrORF
global corrGTF
global corrSAM
global corrFASTA
corrGTF, corrSAM, corrFASTA, corrORF = get_corr_filenames(args)
n_cpu = max(1, args.cpus // args.chunks)
# Step 1. IF GFF or GTF is provided, make it into a genome-based fasta
# IF sequence is provided, align as SAM then correct with genome
if os.path.exists(corrFASTA):
print("Error corrected FASTA {0} already exists. Using it...".format(corrFASTA), file=sys.stderr)
else:
if not args.gtf:
if os.path.exists(corrSAM):
print("Aligned SAM {0} already exists. Using it...".format(corrSAM), file=sys.stderr)
else:
if args.aligner_choice == "gmap":
print("****Aligning reads with GMAP...", file=sys.stdout)
cmd = GMAP_CMD.format(cpus=n_cpu,
dir=os.path.dirname(args.gmap_index),
name=os.path.basename(args.gmap_index),
sense=args.sense,
i=args.isoforms,
o=corrSAM)
elif args.aligner_choice == "minimap2":
print("****Aligning reads with Minimap2...", file=sys.stdout)
cmd = MINIMAP2_CMD.format(cpus=n_cpu,
sense=args.sense,
g=args.genome,
i=args.isoforms,
o=corrSAM)
elif args.aligner_choice == "deSALT":
print("****Aligning reads with deSALT...", file=sys.stdout)
cmd = DESALT_CMD.format(cpus=n_cpu,
dir=args.gmap_index,
i=args.isoforms,
o=corrSAM)
if subprocess.check_call(cmd, shell=True)!=0:
print("ERROR running alignment cmd: {0}".format(cmd), file=sys.stderr)
sys.exit(-1)
# error correct the genome (input: corrSAM, output: corrFASTA)
err_correct(args.genome, corrSAM, corrFASTA, genome_dict=genome_dict)
# convert SAM to GFF --> GTF
convert_sam_to_gff3(corrSAM, corrGTF+'.tmp', source=os.path.basename(args.genome).split('.')[0]) # convert SAM to GFF3
cmd = "{p} {o}.tmp -T -o {o}".format(o=corrGTF, p=GFFREAD_PROG)
if subprocess.check_call(cmd, shell=True)!=0:
print("ERROR running cmd: {0}".format(cmd), file=sys.stderr)
sys.exit(-1)
else:
print("Skipping aligning of sequences because GTF file was provided.", file=sys.stdout)
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:
print("WARNING: GTF has {0} no annotation lines.".format(args.isoforms), file=sys.stderr)
# GFF to GTF (in case the user provides gff instead of gtf)
corrGTF_tpm = corrGTF+".tmp"
try:
subprocess.call([GFFREAD_PROG, 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 list(genome_dict.keys()):
sys.stderr.write("\nERROR: gtf \"%s\" chromosome not found in genome reference file.\n" % (chrom))
sys.exit()
elif type in ('transcript', '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 SQANTI3 without alignment step (SQANTI3 with gtf format as transcriptome input).\n")
# GTF to FASTA
subprocess.call([GFFREAD_PROG, corrGTF, '-g', args.genome, '-w', corrFASTA])
# ORF generation
print("**** Predicting ORF sequences...", file=sys.stdout)
gmst_dir = os.path.join(os.path.abspath(args.dir), "GMST")
gmst_pre = os.path.join(gmst_dir, "GMST_tmp")
if not os.path.exists(gmst_dir):
os.makedirs(gmst_dir)
# sequence ID example: PB.2.1 gene_4|GeneMark.hmm|264_aa|+|888|1682
gmst_rex = re.compile('(\S+\t\S+\|GeneMark.hmm)\|(\d+)_aa\|(\S)\|(\d+)\|(\d+)')
orfDict = {} # GMST seq id --> myQueryProteins object
if args.skipORF:
print("WARNING: Skipping ORF prediction. All isoforms will be non-coding!", file=sys.stderr)
elif os.path.exists(corrORF):
print("ORF file {0} already exists. Using it....".format(corrORF), file=sys.stderr)
for r in SeqIO.parse(open(corrORF), 'fasta'):
# now process ORFs into myQueryProtein objects
m = gmst_rex.match(r.description)
if m is None:
print("Expected GMST output IDs to be of format '<pbid> gene_4|GeneMark.hmm|<orf>_aa|<strand>|<cds_start>|<cds_end>' but instead saw: {0}! Abort!".format(r.description), file=sys.stderr)
sys.exit(-1)
orf_length = int(m.group(2))
cds_start = int(m.group(4))
cds_end = int(m.group(5))
orfDict[r.id] = myQueryProteins(cds_start, cds_end, orf_length, str(r.seq), proteinID=r.id)
else:
cur_dir = os.path.abspath(os.getcwd())
os.chdir(args.dir)
if args.orf_input is not None:
print("Running ORF prediction of input on {0}...".format(args.orf_input))
cmd = GMST_CMD.format(i=os.path.realpath(args.orf_input), o=gmst_pre)
else:
cmd = GMST_CMD.format(i=corrFASTA, o=gmst_pre)
if subprocess.check_call(cmd, shell=True, cwd=gmst_dir)!=0:
print("ERROR running GMST cmd: {0}".format(cmd), file=sys.stderr)
sys.exit(-1)
os.chdir(cur_dir)
# Modifying ORF sequences by removing sequence before ATG
with open(corrORF, "w") as f:
for r in SeqIO.parse(open(gmst_pre+'.faa'), 'fasta'):
m = gmst_rex.match(r.description)
if m is None:
print("Expected GMST output IDs to be of format '<pbid> gene_4|GeneMark.hmm|<orf>_aa|<strand>|<cds_start>|<cds_end>' but instead saw: {0}! Abort!".format(r.description), file=sys.stderr)
sys.exit(-1)
id_pre = m.group(1)
orf_length = int(m.group(2))
orf_strand = m.group(3)
cds_start = int(m.group(4))
cds_end = int(m.group(5))
pos = r.seq.find('M')
if pos!=-1:
# must modify both the sequence ID and the sequence
orf_length -= pos
cds_start += pos*3
newid = "{0}|{1}_aa|{2}|{3}|{4}".format(id_pre, orf_length, orf_strand, cds_start, cds_end)
newseq = str(r.seq)[pos:]
orfDict[r.id] = myQueryProteins(cds_start, cds_end, orf_length, str(r.seq), proteinID=newid)
f.write(">{0}\n{1}\n".format(newid, newseq))
else:
new_rec = r
orfDict[r.id] = myQueryProteins(cds_start, cds_end, orf_length, str(r.seq), proteinID=r.id)
f.write(">{0}\n{1}\n".format(new_rec.description, new_rec.seq))
if len(orfDict) == 0:
print("WARNING: All input isoforms were predicted as non-coding", file=sys.stderr)
return(orfDict)
def reference_parser(args, genome_chroms):
"""
Read the reference GTF file
:param args:
:param genome_chroms: list of chromosome names from the genome fasta, used for sanity checking
:return: (refs_1exon_by_chr, refs_exons_by_chr, junctions_by_chr, junctions_by_gene)
"""
global referenceFiles
referenceFiles = os.path.join(args.dir, "refAnnotation_"+args.output+".genePred")
print("**** Parsing Reference Transcriptome....", file=sys.stdout)
if os.path.exists(referenceFiles):
print("{0} already exists. Using it.".format(referenceFiles), file=sys.stdout)
else:
## gtf to genePred
if not args.genename:
subprocess.call([GTF2GENEPRED_PROG, args.annotation, referenceFiles, '-genePredExt', '-allErrors', '-ignoreGroupsWithoutExons'])
else:
subprocess.call([GTF2GENEPRED_PROG, args.annotation, referenceFiles, '-genePredExt', '-allErrors', '-ignoreGroupsWithoutExons', '-geneNameAsName2'])
## parse reference annotation
# 1. ignore all miRNAs (< 200 bp)
# 2. separately store single exon and multi-exon references
refs_1exon_by_chr = defaultdict(lambda: IntervalTree()) #
refs_exons_by_chr = defaultdict(lambda: IntervalTree())
# store donors as the exon end (1-based) and acceptor as the exon start (0-based)
# will convert the sets to sorted list later
junctions_by_chr = defaultdict(lambda: {'donors': set(), 'acceptors': set(), 'da_pairs': set()})
# dict of gene name --> set of junctions (don't need to record chromosome)
junctions_by_gene = defaultdict(lambda: set())
# dict of gene name --> list of known begins and ends (begin always < end, regardless of strand)
known_5_3_by_gene = defaultdict(lambda: {'begin':set(), 'end': set()})
for r in genePredReader(referenceFiles):
if r.length < args.min_ref_len and not args.is_fusion: continue # ignore miRNAs
if r.exonCount == 1:
refs_1exon_by_chr[r.chrom].insert(r.txStart, r.txEnd, r)
known_5_3_by_gene[r.gene]['begin'].add(r.txStart)
known_5_3_by_gene[r.gene]['end'].add(r.txEnd)
else:
refs_exons_by_chr[r.chrom].insert(r.txStart, r.txEnd, r)
# only store junctions for multi-exon transcripts
for d, a in r.junctions:
junctions_by_chr[r.chrom]['donors'].add(d)
junctions_by_chr[r.chrom]['acceptors'].add(a)
junctions_by_chr[r.chrom]['da_pairs'].add((d,a))
junctions_by_gene[r.gene].add((d,a))
known_5_3_by_gene[r.gene]['begin'].add(r.txStart)
known_5_3_by_gene[r.gene]['end'].add(r.txEnd)
# check that all genes' chromosomes are in the genome file
ref_chroms = set(refs_1exon_by_chr.keys()).union(list(refs_exons_by_chr.keys()))
diff = ref_chroms.difference(genome_chroms)
if len(diff) > 0:
print("WARNING: ref annotation contains chromosomes not in genome: {0}\n".format(",".join(diff)), file=sys.stderr)
# convert the content of junctions_by_chr to sorted list
for k in junctions_by_chr:
junctions_by_chr[k]['donors'] = list(junctions_by_chr[k]['donors'])
junctions_by_chr[k]['donors'].sort()
junctions_by_chr[k]['acceptors'] = list(junctions_by_chr[k]['acceptors'])
junctions_by_chr[k]['acceptors'].sort()
junctions_by_chr[k]['da_pairs'] = list(junctions_by_chr[k]['da_pairs'])
junctions_by_chr[k]['da_pairs'].sort()
return dict(refs_1exon_by_chr), dict(refs_exons_by_chr), dict(junctions_by_chr), dict(junctions_by_gene), dict(known_5_3_by_gene)
def isoforms_parser(args):
"""
Parse input isoforms (GTF) to dict (chr --> sorted list)
"""
global queryFile
queryFile = os.path.splitext(corrGTF)[0] +".genePred"
print("**** Parsing Isoforms....", file=sys.stderr)
# gtf to genePred
cmd = GTF2GENEPRED_PROG + " {0} {1} -genePredExt -allErrors -ignoreGroupsWithoutExons".format(\
corrGTF, queryFile)
if subprocess.check_call(cmd, shell=True)!=0:
print("ERROR running cmd: {0}".format(cmd), file=sys.stderr)
sys.exit(-1)
isoforms_list = defaultdict(lambda: []) # chr --> list to be sorted later
for r in genePredReader(queryFile):
isoforms_list[r.chrom].append(r)
for k in isoforms_list:
isoforms_list[k].sort(key=lambda r: r.txStart)
return isoforms_list
def STARcov_parser(coverageFiles): # just valid with unstrand-specific RNA-seq protocols.
"""
:param coverageFiles: comma-separated list of STAR junction output files or a directory containing junction files
:return: list of samples, dict of (chrom,strand) --> (0-based start, 1-based end) --> {dict of sample -> unique reads supporting this junction}
"""
if os.path.isdir(coverageFiles):
cov_files = glob.glob(coverageFiles + "/*SJ.out.tab")
elif coverageFiles.count(',') > 0:
cov_files = coverageFiles.split(",")
else:
cov_files = glob.glob(coverageFiles)
print("Input pattern: {0}.\nThe following files found and to be read as junctions:\n{1}".format(\
coverageFiles, "\n".join(cov_files) ), file=sys.stderr)
cov_by_chrom_strand = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: 0)))
undefined_strand_count = 0
all_read = 0
samples = []
for file in cov_files:
prefix = os.path.basename(file[:file.rfind('.')]) # use this as sample name
samples.append(prefix)
for r in STARJunctionReader(file):
if r.strand == 'NA':
# undefined strand, so we put them in BOTH strands otherwise we'll lose all non-canonical junctions from STAR
cov_by_chrom_strand[(r.chrom, '+')][(r.start, r.end)][prefix] = r.unique_count + r.multi_count
cov_by_chrom_strand[(r.chrom, '-')][(r.start, r.end)][prefix] = r.unique_count + r.multi_count
undefined_strand_count += 1
else:
cov_by_chrom_strand[(r.chrom, r.strand)][(r.start, r.end)][prefix] = r.unique_count + r.multi_count
all_read += 1
print("{0} junctions read. {1} junctions added to both strands because no strand information from STAR.".format(all_read, undefined_strand_count), file=sys.stderr)
return samples, cov_by_chrom_strand
EXP_KALLISTO_HEADERS = ['target_id', 'length', 'eff_length', 'est_counts', 'tpm']
EXP_RSEM_HEADERS = ['transcript_id', 'length', 'effective_length', 'expected_count', 'TPM']
def mergeDict(dict1, dict2):
""" Merge dictionaries to collect info from several files"""
dict3 = {**dict1, **dict2}
for key, value in dict3.items():
if key in dict1 and key in dict2:
dict3[key] = [value , dict1[key]]
return dict3
def flatten(lis):
for item in lis:
if isinstance(item, Iterable) and not isinstance(item, str):
for x in flatten(item):
yield x
else:
yield item
def expression_parser(expressionFile):
"""
Currently accepts expression format: Kallisto or RSEM
:param expressionFile: Kallisto or RSEM
:return: dict of PBID --> TPM
Include the possibility of providing an expression matrix --> first column must be "ID"
"""
if os.path.isdir(expressionFile)==True:
exp_paths = [os.path.join(expressionFile,fn) for fn in next(os.walk(expressionFile))[2]]
else:
exp_paths = expressionFile.split(",")
exp_all = {}
ismatrix = False
for exp_file in exp_paths:
reader = DictReader(open(exp_file), delimiter='\t')
if all(k in reader.fieldnames for k in EXP_KALLISTO_HEADERS):
print("Detected Kallisto expression format. Using 'target_id' and 'tpm' field.", file=sys.stderr)
name_id, name_tpm = 'target_id', 'tpm'
elif all(k in reader.fieldnames for k in EXP_RSEM_HEADERS):
print("Detected RSEM expression format. Using 'transcript_id' and 'TPM' field.", file=sys.stderr)
name_id, name_tpm = 'transcript_id', 'TPM'
elif reader.fieldnames[0]=="ID":
print("Detected expression matrix format")
ismatrix = True
name_id = 'ID'
else:
print("Expected Kallisto or RSEM file format from {0}. Abort!".format(expressionFile), file=sys.stderr)
exp_sample = {}
if ismatrix:
for r in reader:
exp_sample[r[name_id]] = np.average(list(map(float,list(r.values())[1:])))
else:
for r in reader:
exp_sample[r[name_id]] = float(r[name_tpm])
exp_all = mergeDict(exp_all, exp_sample)
exp_dict = {}
if len(exp_paths)>1:
for k in exp_all:
exp_all[k] = list(flatten(exp_all[k]))
exp_dict[k] = mean(exp_all[k])
return exp_dict
else:
exp_dict=exp_all
return exp_dict
def get_TSS_TTS_coordinates(trec):
"""
Get TSS genomic coordinate
"""
if trec.strand == '+':
tss = trec.txStart
tts = trec.txEnd
else:
tss = trec.txEnd
tts = trec.txStart
return(tss, tts)
def transcriptsKnownSpliceSites(refs_1exon_by_chr, refs_exons_by_chr, start_ends_by_gene, trec, genome_dict, nPolyA):
"""
:param refs_1exon_by_chr: dict of single exon references (chr -> IntervalTree)
:param refs_exons_by_chr: dict of multi exon references (chr -> IntervalTree)
:param trec: id record (genePredRecord) to be compared against reference
:param genome_dict: dict of genome (chrom --> SeqRecord)
:param nPolyA: window size to look for polyA
:return: myQueryTranscripts object that indicates the best reference hit
"""
def calc_overlap(s1, e1, s2, e2):
if s1=='NA' or s2=='NA': return 0
if s1 > s2:
s1, e1, s2, e2 = s2, e2, s1, e1
return max(0, min(e1,e2)-max(s1,s2))
def gene_overlap(ref1, ref2):
if ref1==ref2: return True # same gene, diff isoforms
# return True if the two reference genes overlap
s1, e1 = min(start_ends_by_gene[ref1]['begin']), max(start_ends_by_gene[ref1]['end'])
s2, e2 = min(start_ends_by_gene[ref2]['begin']), max(start_ends_by_gene[ref2]['end'])
if s1 <= s2:
return e1 <= s2
else:
return e2 <= s1
def calc_splicesite_agreement(query_exons, ref_exons):
q_sites = {}
for e in query_exons:
q_sites[e.start] = 0
q_sites[e.end] = 0
for e in ref_exons:
if e.start in q_sites: q_sites[e.start] = 1
if e.end in q_sites: q_sites[e.end] = 1
return sum(q_sites.values())
def calc_exon_overlap(query_exons, ref_exons):
q_bases = {}
for e in query_exons:
for b in range(e.start, e.end): q_bases[b] = 0
for e in ref_exons:
for b in range(e.start, e.end):
if b in q_bases: q_bases[b] = 1
return sum(q_bases.values())
def get_diff_tss_tts(trec, ref):
if trec.strand == '+':
diff_tss = trec.txStart - ref.txStart
diff_tts = ref.txEnd - trec.txEnd
else:
diff_tts = trec.txStart - ref.txStart
diff_tss = ref.txEnd - trec.txEnd
return diff_tss, diff_tts
def get_gene_diff_tss_tts(isoform_hit):
# now that we know the reference (isoform) it hits
# add the nearest start/end site for that gene (all isoforms of the gene)
nearest_start_diff, nearest_end_diff = float('inf'), float('inf')
for ref_gene in isoform_hit.genes:
for x in start_ends_by_gene[ref_gene]['begin']:
d = trec.txStart - x
if abs(d) < abs(nearest_start_diff):
nearest_start_diff = d
for x in start_ends_by_gene[ref_gene]['end']:
d = trec.txEnd - x
if abs(d) < abs(nearest_end_diff):
nearest_end_diff = d
if trec.strand == '+':
isoform_hit.tss_gene_diff = nearest_start_diff if nearest_start_diff!=float('inf') else 'NA'
isoform_hit.tts_gene_diff = nearest_end_diff if nearest_end_diff!=float('inf') else 'NA'
else:
isoform_hit.tss_gene_diff = -nearest_end_diff if nearest_start_diff!=float('inf') else 'NA'
isoform_hit.tts_gene_diff = -nearest_start_diff if nearest_end_diff!=float('inf') else 'NA'
def categorize_incomplete_matches(trec, ref):
"""
intron_retention --- at least one trec exon covers at least two adjacent ref exons
complete --- all junctions agree and is not IR
5prime_fragment --- all junctions agree but trec has less 5' exons. The isoform is a 5' fragment of the reference transcript
3prime_fragment --- all junctions agree but trec has less 3' exons. The isoform is a 3' fragment of the reference transcript
internal_fragment --- all junctions agree but trec has less 5' and 3' exons
"""
# check intron retention
ref_exon_tree = IntervalTree()
for i,e in enumerate(ref.exons): ref_exon_tree.insert(e.start, e.end, i)
for e in trec.exons:
if len(ref_exon_tree.find(e.start, e.end)) > 1: # multiple ref exons covered
return "intron_retention"
agree_front = trec.junctions[0]==ref.junctions[0]
agree_end = trec.junctions[-1]==ref.junctions[-1]
if agree_front:
if agree_end:
return "complete"
else: # front agrees, end does not
return ("5prime_fragment" if trec.strand=='+' else '3prime_fragment')
else:
if agree_end: # front does not agree, end agrees
return ("3prime_fragment" if trec.strand=='+' else '5prime_fragment')
else:
return "internal_fragment"
# Transcript information for a single query id and comparison with reference.
# Intra-priming: calculate percentage of "A"s right after the end
if trec.strand == "+":
pos_TTS = trec.exonEnds[-1]
seq_downTTS = str(genome_dict[trec.chrom].seq[pos_TTS:pos_TTS+nPolyA]).upper()
else: # id on - strand
pos_TTS = trec.exonStarts[0]
seq_downTTS = str(genome_dict[trec.chrom].seq[pos_TTS-nPolyA:pos_TTS].reverse_complement()).upper()
percA = float(seq_downTTS.count('A'))/nPolyA*100
isoform_hit = myQueryTranscripts(id=trec.id, tts_diff="NA", tss_diff="NA",\
num_exons=trec.exonCount,
length=trec.length,
str_class="", \
chrom=trec.chrom,
strand=trec.strand, \
subtype="no_subcategory",\
percAdownTTS=str(percA),\
seqAdownTTS=seq_downTTS)
##***************************************##
########### SPLICED TRANSCRIPTS ###########
##***************************************##
cat_ranking = {'full-splice_match': 5, 'incomplete-splice_match': 4, 'anyKnownJunction': 3, 'anyKnownSpliceSite': 2,
'geneOverlap': 1, '': 0}
#if trec.id.startswith('PB.1961.2'):
# pdb.set_trace()
if trec.exonCount >= 2:
hits_by_gene = defaultdict(lambda: []) # gene --> list of hits
best_by_gene = {} # gene --> best isoform_hit
if trec.chrom in refs_exons_by_chr:
for ref in refs_exons_by_chr[trec.chrom].find(trec.txStart, trec.txEnd):
hits_by_gene[ref.gene].append(ref)
if trec.chrom in refs_1exon_by_chr:
for ref in refs_1exon_by_chr[trec.chrom].find(trec.txStart, trec.txEnd):
hits_by_gene[ref.gene].append(ref)
if len(hits_by_gene) == 0: return isoform_hit
for ref_gene in hits_by_gene:
isoform_hit = myQueryTranscripts(id=trec.id, tts_diff="NA", tss_diff="NA", \
num_exons=trec.exonCount,
length=trec.length,
str_class="", \
chrom=trec.chrom,
strand=trec.strand, \