forked from mortazavilab/TranscriptClean
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTranscriptClean.py
More file actions
1677 lines (1362 loc) · 63 KB
/
TranscriptClean.py
File metadata and controls
1677 lines (1362 loc) · 63 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
# TranscriptClean
# Author: Dana Wyman
# 3/1/2018
# -----------------------------------------------------------------------------
# Mismatches and microindels in long reads are corrected in a variant-aware
# fashion using the reference genome and a VCF file of whitelisted variants.
# Noncanonical splice junctions can also be corrected using a file of reference
# splice sites.
# TC Classes
from transcript import Transcript
from transcript import check_seq_and_cigar_length
from spliceJunction import *
from intronBound import IntronBound
from optparse import OptionParser
import dstruct
# Other modules
from pyfasta import Fasta
import os
import multiprocessing as mp
from math import ceil
import re
from copy import copy
import warnings
# Runtime profiling
import cProfile
import time
from datetime import timedelta
def main():
options = getOptions()
sam_file = options.sam
n_threads = options.n_threads
header, sam_chroms, sam_chunks = split_SAM(sam_file, n_threads)
validate_chroms(options.refGenome, options.variantFile, sam_chroms)
# Run the processes. Outfiles are created within each process
processes = []
# run_chunk(sam_chunks[0], options, header)
for i in range(n_threads):
if options.dryRun == True:
t = mp.Process(target=run_chunk_dryRun,
args=(sam_chunks[i], options))
else:
t = mp.Process(target=run_chunk, args=(
sam_chunks[i], options, header))
# Run the process
processes.append(t)
t.start()
# Wait for all processes to finish
for one_process in processes:
one_process.join()
# When the processes have finished, combine the outputs together.
start_time = time.time()
combine_outputs(header, options)
end_time = time.time()
human_time = str(timedelta(seconds=int(end_time - start_time)))
print("Took %s to combine all outputs." % (human_time))
def getOptions():
parser = OptionParser()
parser.add_option("--sam", "-s", dest="sam",
help=("Input SAM file containing transcripts to "
"correct. Must contain a header."),
metavar="FILE", type="string", default="")
parser.add_option("--genome", "-g", dest="refGenome",
help=("Reference genome fasta file. Should be the "
"same one used during mapping to generate the "
"provided SAM file."),
metavar="FILE", type="string", default="")
parser.add_option("--threads", "-t", dest="n_threads",
help=("Number of threads to run program with."),
type="int", default=1)
parser.add_option("--spliceJns", "-j", dest="sjAnnotFile",
help=("Splice junction file obtained by mapping "
"Illumina reads to the genome using STAR, or "
"alternately, extracted from a GTF using the "
"accessory script. More formats may be "
"supported in the future."),
metavar="FILE", type="string", default=None)
parser.add_option("--variants", "-v", dest="variantFile",
help=("VCF formatted file of variants to avoid "
"correcting away in the data (optional)."),
metavar="FILE", type="string", default=None)
parser.add_option("--maxLenIndel", dest="maxLenIndel",
help="Maximum size indel to correct (Default: 5 bp)",
type="int", default=5)
parser.add_option("--maxSJOffset", dest="maxSJOffset",
help=("Maximum distance from annotated splice junction "
"to correct (Default: 5 bp)"),
type="int", default=5)
parser.add_option("--outprefix", "-o", dest="outprefix",
help=("Output file prefix. '_clean' plus a file "
"extension will be added to the end."),
metavar="FILE", type="string", default="TC")
parser.add_option("--correctMismatches", "-m", dest="correctMismatches",
help=("If set to false, TranscriptClean will skip "
"mismatch correction. Default: true"),
type="string", default="true")
parser.add_option("--correctIndels", "-i", dest="correctIndels",
help="If set to false, TranscriptClean will skip indel \
correction. Default: true", type="string",
default="true")
parser.add_option("--correctSJs", dest="correctSJs",
help=("If set to false, TranscriptClean will skip "
"splice junction correction. Default: true, but you must "
"provide a splice junction annotation file in order for "
"it to work."), type="string", default="true")
parser.add_option("--dryRun", dest="dryRun", action='store_true',
help=("If this option is set, TranscriptClean will "
"read in the sam file and record all insertions, "
"deletions, and mismatches, but it will skip "
"correction. This mode is useful for checking "
"the distribution of transcript errors in the "
"data before running correction."))
parser.add_option("--primaryOnly", dest="primaryOnly", action='store_true',
help="If this option is set, TranscriptClean will only \
output primary mappings of transcripts (ie it will filter \
out unmapped and multimapped lines from the SAM input.",
default=False)
parser.add_option("--canonOnly", dest="canonOnly", action='store_true',
help=("If this option is set, TranscriptClean will "
"output only canonical transcripts and transcripts "
"containing annotated noncanonical junctions to the "
"clean SAM file at the end of the run."), default=False)
parser.add_option("--tmpDir", dest="tmp_path",
help=("If you would like the tmp files to be written "
"somewhere different than the final output, "
"provide the path to that location here."),
default=None)
parser.add_option("--bufferSize", dest="buffer_size",
help=("Number of lines to output to file at once by "
"each thread during run. Default = 100"),
type="int", default=100)
parser.add_option("--deleteTmp", dest="delete_tmp", action='store_true',
help=("If this option is set, the temporary directory "
"generated by TranscriptClean (TC_tmp) will be "
"removed at the end of the run."))
(options, args) = parser.parse_args()
options = cleanup_options(options)
return options
def cleanup_options(options):
""" Clean up input options by casting to appropriate types etc. """
options.n_threads = int(options.n_threads)
options.buffer_size = int(options.buffer_size)
options.maxLenIndel = int(options.maxLenIndel)
options.maxSJOffset = int(options.maxSJOffset)
options.correctIndels = (options.correctIndels).lower()
options.correctMismatches = (options.correctMismatches).lower()
options.correctSJs = (options.correctSJs).lower()
# Screen options for correctness
if options.correctMismatches not in ["true", "false"]:
raise RuntimeError(("Invalid choice for --correctMismatches/-m option. "
"Valid choices are 'true' and 'false'"))
if options.correctIndels not in ["true", "false"]:
raise RuntimeError(("Invalid choice for --correctIndels/-i option. "
"Valid choices are 'true' and 'false'"))
if options.correctSJs not in ["true", "false"]:
raise RuntimeError(("Invalid choice for --correctSJs option. "
"Valid choices are 'true' and 'false'"))
# Use custom tmp dir location if provided
if options.tmp_path != None:
if os.path.isdir(options.tmp_path):
options.tmp_dir = "/".join(
(options.tmp_path).split("/") + ["TC_tmp/"])
else:
options.tmp_dir = "/".join((options.tmp_path).split("/")
[0:-1] + ["TC_tmp/"])
else:
options.tmp_dir = "/".join((options.outprefix).split("/")
[0:-1] + ["TC_tmp/"])
# If there is a tmp dir there already, remove it
if os.path.exists(options.tmp_dir):
os.system("rm -r %s" % options.tmp_dir)
os.system("mkdir -p %s" % options.tmp_dir)
# If the specified outprefix is a directory, add TC default prefix to it
if os.path.isdir(options.outprefix):
options.outprefix = "/".join((options.outprefix).split("/") + ["TC"])
return options
def prep_refs(options, transcripts, sam_header):
""" Process input files and store them in a reference dict.
SAM transcripts and header are needed if variants provided because
the variant file will be filtered to include only those that overlap
the SAM reads. """
tmp_dir = options.tmp_dir
os.system("mkdir -p %s" % tmp_dir)
genomeFile = options.refGenome
variantFile = options.variantFile
sjFile = options.sjAnnotFile
# Container for references
refs = dstruct.Struct()
# Read in the reference genome.
print("Reading genome ..............................")
refs.genome = Fasta(options.refGenome)
ref_chroms = sorted((refs.genome.keys()))
# Create a tmp SAM file for the provided reads
proc = str(os.getpid())
tmp_sam, sam_chroms = create_tmp_sam(
sam_header, transcripts, options.tmp_dir, process=proc)
# Read in splice junctions
refs.donors = None
refs.acceptors = None
refs.sjAnnot = set()
if options.correctSJs == "false":
print("SJ correction turned off in options. Skipping reference SJ parsing.")
elif sjFile != None:
print("Processing annotated splice junctions ...")
refs.donors, refs.acceptors, refs.sjAnnot = processSpliceAnnotation(sjFile,
tmp_dir, sam_chroms, process=proc)
else:
print("No splice annotation provided. Will skip splice junction correction.")
# Read in variants
if variantFile != None:
print("Processing variant file .................")
refs.snps, refs.insertions, refs.deletions = processVCF(variantFile,
options.maxLenIndel,
tmp_dir,
tmp_sam,
process=proc)
else:
print("No variant file provided. Transcript correction will not be variant-aware.")
refs["snps"] = refs["insertions"] = refs["deletions"] = {}
return refs
def create_tmp_sam(sam_header, transcripts, tmp_dir, process="1"):
""" Put the transcripts in the provided list into a temporary SAM file,
preceded by the provided header (list form). The file will be located in
a 'sams' subdir of the tmp_dir provided. Returns the name of the tmp
file as well as the chromosomes found within"""
sam_dir = tmp_dir + "split_uncorr_sams/"
sam_name = sam_dir + process + ".sam"
os.system("mkdir -p %s" % (sam_dir))
chroms = set()
with open(sam_name, 'w') as f:
for item in sam_header:
f.write("%s\n" % item)
for transcript in transcripts:
f.write("%s\n" % transcript)
chroms.add(transcript.split('\t')[2])
return sam_name, chroms
def setup_outfiles(options, process="1"):
""" Set up output files. If running in parallel, label with a process ID """
# Place files in a tmp directory
tmp_dir = options.tmp_dir
os.system("mkdir -p " + tmp_dir)
outfiles = dstruct.Struct()
# Open sam, fasta, and log outfiles
oSam = open(tmp_dir + "clean_" + process + ".sam", 'w')
oFa = open(tmp_dir + "clean_" + process + ".fa", 'w')
transcriptLog = open(tmp_dir + "clean_" + process + ".log", 'w')
transcriptErrorLog = open(tmp_dir + "clean_" + process + ".TElog", 'w')
outfiles.sam = oSam
outfiles.fasta = oFa
outfiles.log = transcriptLog
outfiles.TElog = transcriptErrorLog
return outfiles
def close_outfiles(outfiles):
""" Close all of the output files """
for f in list(outfiles.values()):
f.close()
return
def transcript_init(transcript_line, genome, sjAnnot):
""" Attempt to initialize a Transcript object from a SAM entry. First,
create a log object, and note the mapping status of the read. If the
transcript alignment is unmapped or non-primary, then create a log
entry for the transcript, but do not bother initializing a transcript
object. output that Otherwise, return the transcript object along with
the log.
Input:
- Transcript SAM line (string)
- Reference genome (needed to determine canonical-ness of jns
- Splice annot set object (needed to look up whether a junction
is annotated or not)
Returns:
- Transcript object if primary alignment, None if not
- logInfo object
"""
# Check mapping
sam_fields = transcript_line.split('\t')
logInfo = init_log_info(sam_fields)
if logInfo.Mapping != "primary":
return None, logInfo
try:
transcript = Transcript(sam_fields, genome, sjAnnot)
except Exception as e:
warnings.warn("Problem parsing transcript with ID '" +
logInfo.TranscriptID + "'")
print(e)
return None, logInfo
return transcript, logInfo
def batch_correct(sam_transcripts, options, refs, outfiles, buffer_size=100):
"""Correct and output n lines of transcript SAM file at a time in a batch.
The purpose is to stagger when the different threads are writing to disk.
For a given transcript, there can be only one sam, fasta, and log entry,
but there can be more than one transcript error (TE)."""
print("Correcting transcripts...")
outSam = outfiles.sam
outFa = outfiles.fasta
tL = outfiles.log
tE = outfiles.TElog
sam_lines = fasta_lines = log_lines = TE_log_lines = ""
counter = 0
for transcript_line in sam_transcripts:
transcript, logInfo, TE_entries = correct_transcript(transcript_line,
options, refs)
# If the transcript object returned is None, this means that the
# current read was not a primary mapper. Add to the log file,
# but do not output a fasta sequence. Only output the original
# SAM alignment if primaryOnly and canonOnly modes are off
if transcript == None:
log_lines += create_log_string(logInfo) + "\n"
if options.primaryOnly == False and options.canonOnly == False:
sam_lines += transcript_line + "\n"
# Output the transcript in SAM and Fasta format, plus output the logs
else:
canonical_or_annot = transcript.isCanonical or transcript.allJnsAnnotated
if options.canonOnly == False or canonical_or_annot == True:
sam_lines += transcript.printableSAM() + "\n"
fasta_lines += transcript.printableFa() + "\n"
log_lines += create_log_string(logInfo) + "\n"
TE_log_lines += TE_entries
# Check whether to empty the buffer
if counter > buffer_size:
outSam.write(sam_lines)
outFa.write(fasta_lines)
tL.write(log_lines)
tE.write(TE_log_lines)
sam_lines = fasta_lines = log_lines = TE_log_lines = ""
counter = 0
else:
counter += 1
# Write any remaining lines
outSam.write(sam_lines)
outFa.write(fasta_lines)
tL.write(log_lines)
tE.write(TE_log_lines)
return
def correct_transcript(transcript_line, options, refs):
""" Given a line from a SAM file, create a transcript object. If it's a
primary alignment, then perform the corrections specified in the
options.
"""
orig_transcript, logInfo = transcript_init(transcript_line, refs.genome,
refs.sjAnnot)
TE_entries = ""
if orig_transcript == None:
return orig_transcript, logInfo, TE_entries
# Correct the transcript
try:
upd_transcript = copy(orig_transcript)
upd_logInfo = logInfo
# Mismatch correction
if options.correctMismatches == "true":
mismatch_TE = correctMismatches(upd_transcript, refs.genome,
refs.snps, upd_logInfo)
if mismatch_TE != "":
TE_entries += mismatch_TE
if options.correctIndels == "true":
# Insertion correction
ins_TE = correctInsertions(upd_transcript, refs.genome, refs.insertions,
options.maxLenIndel, upd_logInfo)
if ins_TE != "":
TE_entries += ins_TE
# Deletion correction
del_TE = correctDeletions(upd_transcript, refs.genome, refs.deletions,
options.maxLenIndel, upd_logInfo)
if del_TE != "":
TE_entries += del_TE
# NCSJ correction
if len(refs.sjAnnot) > 0 and options.correctSJs == "true":
upd_transcript, ncsj_TE = cleanNoncanonical(upd_transcript, refs,
options.maxSJOffset,
upd_logInfo)
if ncsj_TE != "":
TE_entries += ncsj_TE
except Exception as e:
warnings.warn(("Problem encountered while correcting transcript "
"with ID %s. Will output original version.") %
orig_transcript.QNAME)
print(e)
TE_entries = ""
return orig_transcript, logInfo, TE_entries
# After successful correction, return transcript object, updated
# logInfo, and the TE log lines generated during correction
return upd_transcript, upd_logInfo, TE_entries
def validate_chroms(genome_file, vcf_file, sam_chroms):
""" Make sure that every chromosome in the SAM file also exists in the
reference genome. This is a common source of crashes. Also, make sure
that the VCF chromosome naming convention matches the SAM file if the
user has provided a VCF. """
genome = Fasta(genome_file)
fasta_chroms = set(genome.keys())
# Remove '*' from sam chromosome set if present
if "*" in sam_chroms:
sam_chroms.remove("*")
# Check whether all of the sam chromosomes are in the fasta file.
# If not, raise an error
if not sam_chroms.issubset(fasta_chroms):
sam_chroms = "{" + \
", ".join(['"' + str(x) + '"' for x in sam_chroms]) + '}'
fasta_chroms = "{" + \
", ".join(['"' + str(x) + '"' for x in fasta_chroms]) + '}'
error_msg = 'One or more SAM chromosomes were not found in the fasta reference.\n' + \
'SAM chromosomes:\n' + sam_chroms + '\n' + \
'FASTA chromosomes:\n' + fasta_chroms + '\n' + \
("One common cause of this problem is when the fasta headers "
"contain more than one word. If this is the case, try "
"trimming the headers to include only the chromosome name "
"(i.e. '>chr1').")
raise RuntimeError(error_msg)
# Check VCF chroms
if vcf_file != None:
try:
import pybedtools
vcf_obj = pybedtools.BedTool(vcf_file)
except Exception as e:
print(e)
raise RuntimeError(("Problem reading the provided VCF file. Please "
"make sure that the filename is correct, that "
"pybedtools is installed, and that your VCF "
"file is properly formatted, including a header."))
vcf_chroms = set([x.chrom for x in vcf_obj])
if len(sam_chroms.intersection(vcf_chroms)) == 0:
sam_chroms = "{" + \
", ".join(['"' + str(x) + '"' for x in sam_chroms]) + '}'
vcf_chroms = "{" + \
", ".join(['"' + str(x) + '"' for x in vcf_chroms]) + '}'
error_msg = ("None of the chromosomes included in the VCF file "
"matched the chromosomes in the provided SAM file.\n"
'SAM chromosomes:\n' + sam_chroms + '\n'
'VCF chromosomes:\n' + vcf_chroms + '\n')
raise RuntimeError(error_msg)
return
def split_SAM(samFile, n):
""" Given a sam file, separate the header line from the remaining entries,
record which chromosomes are present in the reads, and split the reads
into n chunks.
"""
header = []
chroms = set()
transcript_lines = []
with open(samFile, 'r') as f:
for line in f:
line = line.strip()
if line.startswith('@'):
header.append(line)
else:
transcript_lines.append(line)
chrom = line.split("\t")[2]
chroms.add(chrom)
# Now split the transcripts into n chunks
chunks = split_input(transcript_lines, n)
return header, chroms, chunks
def split_input(my_list, n):
""" Splits input into n sublists of roughly equal size"""
chunks = []
index = 0
batch_size = ceil(len(my_list)/n)
while index < len(my_list):
try:
batch = my_list[index:index + batch_size]
except:
batch = my_list[index:]
chunks.append(batch)
index += batch_size
return chunks
def run_chunk(transcripts, options, sam_header):
""" Contains everything needed to run a subset of the transcript input
on its own core """
# Prep the references (i.e. genome, sjs, variants)
start_time = time.time()
refs = prep_refs(options, transcripts, sam_header)
end_time = time.time()
time_slice = end_time - start_time
human_time = str(timedelta(seconds=int(time_slice)))
print("Reference file processing took %s" % (human_time))
# Set up the outfiles
outfiles = setup_outfiles(options, str(os.getpid()))
# Correct the transcripts
start_time = time.time()
batch_correct(transcripts, options, refs, outfiles,
buffer_size=options.buffer_size)
end_time = time.time()
human_time = str(timedelta(seconds=int(end_time - start_time)))
print("Took %s to process transcript batch." % (human_time))
# Close up the outfiles
close_outfiles(outfiles)
return
def run_chunk_dryRun(transcripts, options):
""" Run dryRun mode on a set of transcripts on one core """
# Set up the outfiles
outfiles = setup_outfiles(options, str(os.getpid()))
# Run dryRun mode
dryRun(transcripts, options, outfiles)
# Close up the outfiles
close_outfiles(outfiles)
return
def combine_outputs(sam_header, options):
""" Combine sam, fasta, and log outputs from separate sub-runs into the
final output files. Then, remove the temporary directory.
"""
outprefix = options.outprefix
tmp_dir = options.tmp_dir
# Make filenames
sam = outprefix + "_clean.sam"
fasta = outprefix + "_clean.fa"
log = outprefix + "_clean.log"
TElog = outprefix + "_clean.TE.log"
# Open log outfiles
if os.path.exists(log):
os.remove(log)
if os.path.exists(TElog):
os.remove(TElog)
transcriptLog = open(log, 'w')
transcriptErrorLog = open(TElog, 'w')
# Add headers to logs
transcriptLog.write("\t".join(["TranscriptID", "Mapping",
"corrected_deletions", "uncorrected_deletions",
"variant_deletions", "corrected_insertions",
"uncorrected_insertions", "variant_insertions",
"corrected_mismatches", "uncorrected_mismatches",
"corrected_NC_SJs", "uncorrected_NC_SJs"]) + "\n")
transcriptErrorLog.write("\t".join(["TranscriptID", "Position", "ErrorType",
"Size", "Corrected", "ReasonNotCorrected"]) + "\n")
# Add header to sam file
if options.dryRun != True:
if os.path.exists(sam):
os.remove(sam)
oSam = open(sam, 'w')
for line in sam_header:
oSam.write(line + "\n")
oSam.close()
# Close files
transcriptLog.close()
transcriptErrorLog.close()
# Now combine the subfiles
if options.dryRun != True:
os.system("cat %s/*.sam >> %s" % (tmp_dir, sam))
os.system("cat %s/*.fa > %s" % (tmp_dir, fasta))
os.system("cat %s/*.log >> %s" % (tmp_dir, log))
os.system("cat %s/*.TElog >> %s" % (tmp_dir, TElog))
# Clean up the temporary directory if requested
if options.delete_tmp:
os.system("rm -r %s" % tmp_dir)
return
def processSpliceAnnotation(annotFile, tmp_dir, read_chroms, process="1"):
""" Reads in the tab-separated STAR splice junction file and creates a
bedtools object. Also creates a dict (annot) to allow easy lookup
to find out if a splice junction is annotated or not. Only junctions
located on the provided chromosomes are included."""
bedstr = ""
annot = set()
tmp_dir = tmp_dir + "splice_files/"
os.system("mkdir -p %s" % (tmp_dir))
donor_file = tmp_dir + "%s_ref_splice_donors_tmp.bed" % (process)
acceptor_file = tmp_dir + "%s_ref_splice_acceptors_tmp.bed" % (process)
o_donor = open(donor_file, 'w')
o_acceptor = open(acceptor_file, 'w')
with open(annotFile, 'r') as f:
for line in f:
fields = line.strip().split("\t")
chrom = fields[0]
if chrom not in read_chroms:
continue
start = int(fields[1])
end = int(fields[2])
strand = "."
if fields[3] == "1":
strand = "+"
if fields[3] == "2":
strand = "-"
intronMotif = int(fields[4])
annotated = int(fields[5])
uniqueReads = fields[6]
multiReads = fields[7]
maxOverhang = fields[8]
# ID the splice donor/acceptor identity
if strand == "+":
file1 = o_donor
file2 = o_acceptor
type1 = "donor"
type2 = "acceptor"
elif strand == "-":
file1 = o_acceptor
file2 = o_donor
type1 = "acceptor"
type2 = "donor"
else:
continue
# Make one bed entry for each end of the junction and write to
# splice donor and acceptor files
bed1 = "\t".join(
[chrom, str(start - 1), str(start), ".", "name", strand])
bed2 = "\t".join(
[chrom, str(end - 1), str(end), ".", "name", strand])
file1.write(bed1 + "\n")
file2.write(bed2 + "\n")
# Add a record of the entire junction to the annot set to indicate
# that it is annotated
junction = "_".join([chrom, str(start), strand]) + "," + \
"_".join([chrom, str(end), strand])
annot.add(junction)
o_donor.close()
o_acceptor.close()
# Convert bed files into BedTool objects
# donor_sorted = tmp_dir + "%s_ref_splice_donors_tmp.sorted.bed" % (process)
# acceptor_sorted = tmp_dir + \
# "%s_ref_splice_acceptors_tmp.sorted.bed" % (process)
# os.system('sort -u %s | bedtools sort -i - > %s' %
# (donor_file, donor_sorted))
# os.system('sort -u %s | bedtools sort -i - > %s' %
# (acceptor_file, acceptor_sorted))
# splice_donor_bedtool = pybedtools.BedTool(donor_sorted)
# splice_acceptor_bedtool = pybedtools.BedTool(acceptor_sorted)
import pyranges as pr
# import pdb
# pdb.set_trace()
try:
splice_donor = pr.read_bed(donor_file).drop_duplicate_positions()
except IndexError:
splice_donor = pr.PyRanges()
try:
splice_acceptor = pr.read_bed(acceptor_file).drop_duplicate_positions()
except IndexError:
splice_acceptor = pr.PyRanges()
# Raise a warning if there are no splice donors or acceptors
if splice_donor.length == 0 or splice_acceptor.length == 0:
warnings.warn(("Warning: No splice donors or acceptors found on "
"chromosomes: %s. If this is unexpected, check your SJ "
"annotation file." % (", ".join(read_chroms))))
return splice_donor, splice_acceptor, annot
def processVCF(vcf, maxLen, tmp_dir, sam_file, process="1"):
""" This function reads in variants from a VCF file and stores them. SNPs
are stored in a dictionary by position. Indels are stored in their own
dictionary by start and end position. A pre-filtering step ensures that
variants are included only if they overlap with the input SAM reads.
This is a space-saving measure. If add_chr is set to 'True', the prefix
'chr' will be added to each chromosome name."""
SNPs = {}
insertions = {}
deletions = {}
# Create a temporary BAM version of the input reads
tmp_bam_dir = tmp_dir + "split_uncorr_bams/"
os.system("mkdir -p %s" % (tmp_bam_dir))
bam = tmp_bam_dir + "%s_tmp_reads.bam" % (process)
try:
os.system("samtools view -bS %s > %s" % (sam_file, bam))
except Exception as e:
print(e)
raise RuntimeError(("Problem converting SAM file to BAM for variant "
"prefiltering step. Please make sure that you have "
"Samtools installed, and that your SAM "
"file is properly formatted, including a header."))
# Create a BedTool object for the VCF
try:
import pybedtools
vcf_obj = pybedtools.BedTool(vcf)
except Exception as e:
print(e)
raise RuntimeError(("Problem reading the provided VCF file. Please make "
"sure that Bedtools is installed, and that your VCF "
"file is properly formatted, including a header. "))
# Filter the VCF file to include only those variants that overlap the reads
filtered_vcf = vcf_obj.intersect(bam, u=True, nonamecheck=True)
if len(filtered_vcf) == 0:
warnings.warn(("Warning: none of variants provided overlapped the"
"input reads."))
return SNPs, insertions, deletions
# Now parse the filtered VCF
for variant in filtered_vcf:
chrom = variant[0]
pos = int(variant[1])
ref = variant[3]
alt = variant[4].split(",")
refLen = len(ref)
# It is possible for a single position to have more than one
# type of alternate allele (ie mismatch or indel). So it is
# necessary to treat each alternate allele separately.
for allele in alt:
altLen = len(allele)
# SNP case
if refLen == altLen == 1:
ID = chrom + "_" + str(pos)
if ID not in SNPs:
SNPs[ID] = [allele]
else:
SNPs[ID].append(allele)
# Insertion/Deletion
else:
size = abs(refLen - altLen)
# Only store indels of correctable size
if size > maxLen:
continue
# Positions in VCF files are one-based.
# Inserton/deletion sequences always start with the
# preceding normal reference base
actPos = pos + 1
allele = allele[1:]
ID = "_".join([chrom, str(pos), str(actPos + size - 1)])
if refLen - altLen < 0: # Insertion
if ID not in insertions:
insertions[ID] = [allele]
else:
insertions[ID].append(allele)
elif refLen - altLen > 0: # Deletion
deletions[ID] = 1
return SNPs, insertions, deletions
def correctInsertions(transcript, genome, variants, maxLen, logInfo):
""" Corrects insertions up to size maxLen using the reference genome.
If a variant file was provided, correction will be SNP-aware. """
logInfo.uncorrected_insertions = 0
logInfo.corrected_insertions = 0
logInfo.variant_insertions = 0
TE_entries = ""
origSeq = transcript.SEQ
origCIGAR = transcript.CIGAR
transcript_ID = transcript.QNAME
cigarOps, cigarCounts = transcript.splitCIGAR()
# Check for insertions. If none are present, we can skip this transcript
if "I" not in origCIGAR:
return TE_entries
newCIGAR = ""
newSeq = ""
MVal = 0
seqPos = 0
# Start at position in the genome where the transcript starts.
genomePos = transcript.POS
# Iterate over operations to sequence and repair insertions
for op, ct in zip(cigarOps, cigarCounts):
currPos = transcript.CHROM + ":" + str(genomePos) + "-" + \
str(genomePos + ct - 1)
if op == "M":
newSeq = newSeq + origSeq[seqPos:seqPos + ct]
MVal += ct
seqPos += ct
genomePos += ct
if op == "I":
ID = "_".join([transcript.CHROM, str(genomePos - 1),
str(genomePos + ct - 1)])
# Only insertions of a given size are corrected
if ct <= maxLen:
# Check if the insertion is in the optional variant catalog.
if ID in variants:
# The insertion perfectly matches a variant position.
# Leave the sequence alone if it matches an allele sequence.
currSeq = origSeq[seqPos:seqPos + ct]
if currSeq in variants[ID]:
logInfo.variant_insertions += 1
errorEntry = "\t".join([transcript_ID, ID, "Insertion",
str(ct), "Uncorrected",
"VariantMatch"])
TE_entries += errorEntry + "\n"
# Leave insertion in
MVal, newCIGAR = endMatch(MVal, newCIGAR)
newSeq = newSeq + origSeq[seqPos:seqPos + ct]
newCIGAR = newCIGAR + str(ct) + op
seqPos += ct
continue
# Correct insertion
errorEntry = "\t".join([transcript_ID, ID, "Insertion", str(ct),
"Corrected", "NA"])
logInfo.corrected_insertions += 1
TE_entries += errorEntry + "\n"
# Subtract the inserted bases by skipping them.
# GenomePos stays the same, as does MVal
seqPos += ct
else: # Move on without correcting insertion because it is too big
errorEntry = "\t".join([transcript_ID, ID, "Insertion", str(ct),
"Uncorrected", "TooLarge"])
logInfo.uncorrected_insertions += 1
TE_entries += errorEntry + "\n"
MVal, newCIGAR = endMatch(MVal, newCIGAR)
newSeq = newSeq + origSeq[seqPos:seqPos + ct]
newCIGAR = newCIGAR + str(ct) + op
seqPos += ct
if op == "S":
# End any ongoing match
MVal, newCIGAR = endMatch(MVal, newCIGAR)
newSeq = newSeq + origSeq[seqPos:seqPos + ct]
newCIGAR = newCIGAR + str(ct) + op
seqPos += ct
# N, H, and D operations are cases where the transcript sequence
# is missing bases that are in the reference genome.
if op in ["N", "H", "D"]:
# End any ongoing match
MVal, newCIGAR = endMatch(MVal, newCIGAR)
genomePos += ct
newCIGAR = newCIGAR + str(ct) + op
# End any ongoing match
MVal, newCIGAR = endMatch(MVal, newCIGAR)
# Update transcript
transcript.CIGAR = newCIGAR
transcript.SEQ = newSeq
return TE_entries
def correctDeletions(transcript, genome, variants, maxLen, logInfo):
""" Corrects deletions up to size maxLen using the reference genome.
If a variant file was provided, correction will be variant-aware."""
logInfo.uncorrected_deletions = 0
logInfo.corrected_deletions = 0
logInfo.variant_deletions = 0
TE_entries = ""
transcript_ID = transcript.QNAME
chrom = transcript.CHROM
origSeq = transcript.SEQ
origCIGAR = transcript.CIGAR
cigarOps, cigarCounts = transcript.splitCIGAR()
# Check for deletions. If none are present, we can skip this transcript
if "D" not in origCIGAR:
return TE_entries
newCIGAR = ""
newSeq = ""
MVal = 0
seqPos = 0
# Start at position in the genome where the transcript starts.
genomePos = transcript.POS
# Iterate over operations to sequence and repair mismatches and microindels
for op, ct in zip(cigarOps, cigarCounts):
currPos = chrom + ":" + str(genomePos) + "-" + \
str(genomePos + ct - 1)
if op == "M":
newSeq = newSeq + origSeq[seqPos:seqPos + ct]