-
Notifications
You must be signed in to change notification settings - Fork 11
/
rna-seq-qc.py
executable file
·2348 lines (1968 loc) · 107 KB
/
rna-seq-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
__version__ = "rna-seq-qc v0.8.4"
__description__ = """
{version}
=================
RNA-seq pipeline for processing RNA sequence data from high throughput
sequencing.
Fabian Kilpert - March 08, 2017
email: kilpert@ie-freiburg.mpg.de
This software is distributed WITHOUT ANY WARRANTY!
--------------------------------------------------
Following steps are executed in succession: FASTQ subsampling (optional),
quality check with FASTQC, trimming of reads with Trim Galore (optional),
estimation of insert size and strand specificity with RSeQC, mapping with
STAR (default), counting of features with featureCounts (default) or
htseq-count, differential expression analysis with DESeq2 (optional).
The pipeline requires gzipped FASTQ files (.fastq.gz) for input, which are
loaded from an input directory (-i INDIR). Read files belonging together
require the exact same base name but ending either in "_R1" or "_R2" right
in front of the .fastq.gz extension (e.g. reads_R1.fastq.gz,
reads_R2.fastq.gz). In addition, a specific genome version argument must be
provided (e.g. -g mm10) to define the reference data used for annotation.
This loads a number of indexes for mapping programs (STAR (new!), Novoalign
(new!), TopHat2, HISAT2, etc.) from the corresponding configuration file of
the rna-seq-qc sub-folder (e.g. rna-seq-qc/mm10.cfg). Additional genomes
for selection can be provided as cfg-files by the user. The pipeline works
for single end and paired end sequences alike.
The DE analysis is only executed if a valid setup table is provided (e.g.
--DE sampleInfo.tsv), which defines the relationships of the samples.
More information on the pipeline can be found on the wiki page:
http://epicenter/wiki/index.php/RNA-seq_pipeline_(rna-seq-pc.py)
Example:
python rna-seq-qc.py -i /path/to/fastq_dir -o /path/to/ouput_dir -g mm10 -v --DE sampleInfo.tsv
""".format(version=__version__)
import argparse
from collections import OrderedDict
import datetime
# import gzip
import os
import os.path
from Queue import Queue
# import random
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import textwrap
from threading import Thread
import time
#### PATHS ####################################################################
temp_dir = tempfile.gettempdir()
script_path = os.path.dirname(os.path.realpath(__file__)) + "/"
python_path=sys.executable
#### Development settins ######################################################
if socket.gethostname() == "pc305.immunbio.mpg.de":
## Reading start options (if available)
start_options_file = os.path.join(script_path, "rna-seq-qc", "start_options.txt")
if os.path.isfile(start_options_file):
start_options = []
with open(start_options_file, "r") as f:
for line in f.readlines():
line = line.strip()
if not line.startswith("#"):
if line:
start_options.extend(line.split())
if start_options:
print "Using start options:", " ".join(start_options)
sys.argv = [sys.argv[0]] + start_options
if "--trim_galore" in sys.argv:
sys.argv2 = sys.argv
sys.argv2[sys.argv.index( '--trim_galore')+1] = "'" + sys.argv[sys.argv2.index( '--trim_galore')+1] + "'" # just to output all trim galore option as one string
print " ".join(sys.argv2) # output command line
if "--featureCounts" in sys.argv:
sys.argv2 = sys.argv
sys.argv2[sys.argv.index( '--featureCounts')+1] = "'" + sys.argv[sys.argv2.index( '--featureCounts')+1] + "'" # just to output all trim galore option as one string
print " ".join(sys.argv2) # output command line
else:
print " ".join(sys.argv) # output command line
## Path defaults to all needed scripts and programs + versions ################
fastqc_path = "/package/FastQC-0.11.3/"; fastqc_ver = "FastQC-0.11.3"
trim_galore_path = "/package/trim_galore_v0.4.0/"; trim_galore_ver = "TrimGalore-v0.4.0"
cutadapt_activate = "source /package/cutadapt-1.8.1/bin/activate &&"; cutadapt_ver = "Cutadapt-1.8.1"
rseqc_path = "/package/RSeQC-2.6.1/bin/"; rseqc_ver = "RSeQC-2.6.1"
rseqc_activate = "source /package/RSeQC-2.6.1/bin/activate &&"
bowtie2_path = "/package/bowtie2-2.2.3/"; bowtie2_ver = "Bowtie2-2.2.3"
bowtie2_export = "export PATH={}:$PATH &&".format(bowtie2_path)
picardtools_path = "/package/picard-tools-1.121/"; picardtools_ver = "Picard-tools-1.1.21"
tophat2_path = "/package/tophat-2.0.13.Linux_x86_64/"; tophat2_ver = "TopHat-2.0.13"
star_path = "/package/STAR-2.5.2b/bin/"; star_ver = "STAR_2.5.2b"
feature_counts_path = "/package/subread-1.5.0-p1/bin/"; feature_counts_ver = "featureCounts (subread-1.5.0-p1)"
novoalign_path="/package/novoalign-3.07.00/"; novoalign_ver = "3.07.00"
htseq_count_path = "/package/HTSeq-0.6.1/bin/"; htseq_count_ver = "HTSeq-0.6.1"
R_path = "/package/R-3.2.0/bin/"; R_ver = "R-3.2.0"
samtools_path = "/package/samtools-1.2/"; samtools_ver = "Samtools-1.2"
samtools_export = "export PATH={}:$PATH &&".format(samtools_path)
ucsctools_dir_path = "/package/UCSCtools/"
#hisat_path = "/package/hisat-0.1.5-beta/bin/hisat"
#hisat_path = "/package/hisat-0.1.6-beta/bin/"; hisat_ver = "HISAT-0.1.6-beta"
hisat_path = "/package/hisat2-2.0.0-beta/"; hisat_ver = "HISAT2-2.0.0-beta"
R_libraries_export = "export R_LIBS_USER=/data/manke/repository/scripts/R/rna-seq-qc_libraries/R/x86_64-redhat-linux-gnu-library/3.2_0.8.3 &&"
deseq2_ver = "DESeq2_1.10.1"
deeptools_path = "/package/deeptools-2.0.0/bin/"; deeptools_ver = "deepTools-2.0"
## Different configurations for other physical machines
if socket.gethostname() == "pc305.immunbio.mpg.de":
fastqc_path = "/home/kilpert/Software/bin/"; fastqc_ver = "FastQC"
trim_galore_path = "/home/kilpert/Software/trim_galore/trim_galore_v0.4.0/"; trim_galore_ver = "TrimGalore-v0.4.0"
cutadapt_activate = ""; cutadapt_ver = "Cutadapt"
rseqc_path = "/home/kilpert/Software/RSeQC/RSeQC-2.6.3/build/scripts-2.7/"; rseqc_ver = "RSeQC-2.6.3"
rseqc_activate = ""
bowtie2_path = ""; bowtie2_ver = "Bowtie2"
bowtie2_export = ""
picardtools_path = "/home/kilpert/Software/picard-tools/picard-tools-1.115/"; picardtools_ver = "Picard-tools-1.115"
tophat2_path = ""; tophat2_ver = "TopHat-2"
star_path = ""; star_ver = ""
feature_counts_path = ""; feature_counts_ver = "featureCounts"
htseq_count_path = ""; htseq_count_ver = "HTSeq"
R_path = "/usr/bin/"; R_ver = "R-3.2.3"
samtools_path = ""; samtools_ver = "Samtools-1.2"
samtools_export = ""
ucsctools_dir_path = ""
#hisat_path = "/home/kilpert/Software/hisat/hisat-0.1.5-beta/"; hisat_ver = "HISAT"
hisat_path = "/home/kilpert/Software/hisat/hisat2-2.0.1-beta/"; hisat_ver = "HISAT2-2.0.1-beta"
R_libraries_export = "export R_LIBS_USER=/data/manke/repository/scripts/rna-seq-qc/R/x86_64-pc-linux-gnu-library/3.2 &&"
deseq2_ver = "DESeq2-1.8.1"
deeptools_path = "/home/kilpert/Software/deepTools_release-1.6/deepTools/bin/"; deeptools_ver = "deepTools-1.6"
#### DEFAULT VARIABLES #################################################################################################
is_error = False
default_threads = 3 # Threads per process
default_parallel = 1 # Parallel files
samtools_mem = 1
samtools_threads = 1
if socket.gethostname().startswith(("deep", "maximus", "minimus")):
temp_dir = "/data/extended"
default_threads = 4
default_parallel = 6
samtools_mem = 2
samtools_threads = 2
#### COMMAND LINE PARSING ##############################################################################################
def parse_args():
"""
Parse arguments from the command line.
"""
parser = argparse.ArgumentParser(
prog='rna-seq-qc.py',
formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent(__description__))
### Optional arguments
parser.add_argument('--version', action='version', version=__version__)
parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Verbose output")
parser.add_argument("-i", "--input-dir", dest="main_indir", required=True, help="Input dir containing (FASTQ)")
parser.add_argument("-o", "--output-dir", dest="main_outdir", required=True, help="Output directory")
parser.add_argument("-g", "--genome", dest="genome", required=True, help="Reference genome build")
parser.add_argument("--DE", dest="sample_info", help="Information on samples (required for DE analysis); see rna-seq-qc/example.setup_table.tsv for example. IMPORTANT: The first entry defines which group of samples are control. By this, the order of comparison and likewise the sign of values can be changed!")
parser.add_argument("--overwrite", dest="overwrite", action = "store_true", default=False, help="Overwrite results in existing folders!")
parser.add_argument("-p", "--parallel", dest="parallel", metavar="INT", help="Number of files in parallel processing (default: '%(default)s')", type=int, default=default_parallel)
parser.add_argument("-t", "--threads", dest="threads", metavar="INT", help="Maximum number of threads for a single process (default: '%(default)s')", type=int, default=default_threads)
parser.add_argument("--fastq-downsample", dest="fastq_downsample", metavar="INT", help="Use first n sequences in fastq only (for TESTING!!!)", type=int, default=None)
parser.add_argument("--no-fastqc", dest="no_fastqc", action="store_true", default=False, help="Deactivate FastQC")
parser.add_argument("--trim", dest="trim", action="store_true", default=False, help="Activate trimming of fastq reads (default: no trimming)")
parser.add_argument("--trim_galore_opts", dest="trim_galore_opts", metavar="STR", help="Trim Galore! option string. The option '--paired' is always used for paired-end data. (default: '%(default)s')", type=str, default="--stringency 2")
parser.add_argument("--no-bam", dest="no_bam", action="store_true", default=False, help="First steps only. No alignment. No BAM file.")
parser.add_argument("--mapping-prg", dest="mapping_prg", metavar="STR", help="Program used for mapping: STAR, Novoalign, TopHat2 or HISAT2 (default: '%(default)s')", type=str, default="STAR")
parser.add_argument("--tophat_opts", dest="tophat_opts", metavar="STR", help="TopHat2 option string (default: '%(default)s')", type=str, default="") #--library-type fr-firststrand
parser.add_argument("--star_opts", dest="star_opts", metavar="STR", help="STAR option string, e.g.: '--twopassMode Basic' (default: '%(default)s')", type=str, default="")
parser.add_argument("--novoalign_opts", dest="novoalign_opts", metavar="STR", help="Novoalign option string, e.g.: '' (default: '%(default)s')", type=str, default="-k -r A 20")
parser.add_argument("--hisat_opts", dest="hisat_opts", metavar="STR", help="HISAT2 option string (default: '%(default)s')", type=str, default="")
parser.add_argument("--count-prg", dest="count_prg", metavar="STR", help="Program used for counting features: featureCounts or htseq-count (default: '%(default)s')", type=str, default="featureCounts")
parser.add_argument("--featureCounts_opts", dest="featureCounts_opts", metavar="STR", help="featureCounts option string. The options '-p -B' are always used for paired-end data. (default: '%(default)s')", type=str, default="-C -Q 10 --primary")
parser.add_argument("--htseq-count_opts", dest="htseq_count_opts", metavar="STR", help="HTSeq htseq-count option string (default: '%(default)s')", type=str, default="--mode union")
parser.add_argument("--bw", dest="bw", action="store_true", default=False, help="Generate BW (bigwig) files")
parser.add_argument("--library-type", dest="library_type", metavar="STR", help="Library type following TopHat naming scheme, e.g. fr-firstrand (default: '%(default)s')", type=str, default="auto")
# parser.add_argument("--insert-metrics", dest="insert_metrics", metavar="STR", help="Calculate insert size metrics (mean, sd) using Picard or RSeQC (default: '%(default)s')", type=str, default="Picard")
parser.add_argument("--bowtie_opts", dest="bowtie_opts", metavar="STR", help="Bowtie2 option string. For parameter estimation step only (NO direct effect on Tophat2 mapping!) (default: '%(default)s')", type=str, default="--end-to-end --fast")
parser.add_argument("--report-secondary-alignments", dest="report_secondary_alignments", action="store_true", default=False, help="Output secondary alignments in BAM file. Default is to keep PRIMARY alignments only!!! WARNING: Caution using TopHat2 BAM files in downstream analysis, as the MAPQ scores are always set to 0 for multi-mapping reads!!!")
parser.add_argument("--rseqc", dest="rseqc", action="store_true", default=False, help="Run RSeQC")
parser.add_argument("--rseqc-preselection", dest="rseqc_preselection", help="Preselection of RSeQC programs; 1 for minimum selection or 2 for maximum output (default: '%(default)s')", type=int, default="1")
# parser.add_argument("--no-trim", dest="no_trim", action="store_true", default=False, help="Do not trim FASTQ reads. Default: Use Trim Galore! with default settings.")
### Positional arguments (required!)
args = parser.parse_args()
## Tools path for report
args.script_path = script_path
### Add useful paths
args.cwd = os.getcwd()
args.now = datetime.datetime.now()
args.indir = args.main_indir
args.outdir = args.main_outdir
### Sanity checking
## Input dir
##print "indir:", args.indir
args.indir = os.path.expanduser(args.indir)
args.indir = os.path.realpath(args.indir)
if (not os.path.isdir(args.indir)):
print "Error: The specified input directory does not exist or is not a directory:\n", args.indir
exit(1)
if not args.sample_info is None:
args.sample_info = os.path.expanduser(args.sample_info)
args.sample_info = os.path.realpath(args.sample_info)
if (not os.path.isfile(args.sample_info)):
print "Error: The specified file does not exist or is not readable:\n", args.sample_info
exit(1)
## Output dir
args.outdir = os.path.join(args.cwd, os.path.expanduser(args.outdir))
args.error = 0
## Get reference data paths from config file
ref_cfg_file_path = os.path.join(script_path, "rna-seq-qc/{}.cfg".format(args.genome))
if not os.path.isfile(ref_cfg_file_path):
print "Error! Configuration file NOT found for {}: {}".format(args.genome, ref_cfg_file_path)
exit(1)
configs = parse_config(ref_cfg_file_path)
try:
args.fasta_index = configs["fasta_index"]
args.genome_index = configs["genome_index"]
args.transcriptome_index = configs["transcriptome_index"]
args.hisat_index = configs["hisat_index"]
args.star_index = configs["star_index"]
args.novoalign_index = configs["novoalign_index"]
args.gtf = configs["gtf"]
args.bed = configs["bed"]
args.known_splicesite_infile = configs["known_splicesite_infile"]
except:
print "Error! Unable to read paths from config file:", ref_cfg_file_path
exit(1)
## optional variables from config file
if args.tophat_opts:
#args.tophat_opts = re.sub( r'''^['"]+|['"]+$''', '', args.tophat_opts ) # strip quotes
args.tophat_opts = args.tophat_opts.strip('"')
args.tophat_opts = args.tophat_opts.strip("'")
if args.hisat_opts:
args.hisat_opts = args.hisat_opts.strip('"')
args.hisat_opts = args.hisat_opts.strip("'")
if args.star_opts:
args.star_opts = args.star_opts.strip('"')
args.star_opts = args.star_opts.strip("'")
try:
args.tophat_opts = args.tophat_opts + " " + configs["tophat_opts"]
args.hisat_opts = args.hisat_opts + " " + configs["hisat_opts"]
args.star_opts = args.star_opts + " " + configs["star_opts"]
except:
pass
## gene names, e.g. BioMart
args.gene_names = os.path.join(script_path, "rna-seq-qc/{}.gene_names".format(args.genome))
if not os.path.isfile(args.gene_names):
args.gene_names = ""
return args
#### GENERIC FUNCTIONS #################################################################################################
class Qjob():
def __init__(self, cmds=None, cwd=None, logfile=None, backcopy=True, shell=False, keep_temp=False):
self.cmds = cmds
self.cwd = cwd
self.logfile = logfile
self.backcopy = backcopy
self.shell = shell
self.keep_temp = keep_temp
def run(self):
pass
def parse_config(file_path):
"""
Parse a configuration text file, e.g. *.cfg
"""
options = {}
for line in file(file_path):
line = line.rstrip("\r\n")
if not line.startswith("#"):
if "=" in line:
key, value = line.split('=', 1)
value = value.strip()
value = value.strip('"')
value = value.strip("'")
options[key] = value
return options
def check_for_paired_infiles(args, indir, ext, verbose=False):
"""
Read input files from given dir that have the user specified extension.
"""
infiles = sorted([os.path.join(indir, f) for f in os.listdir(os.path.abspath(indir)) if f.endswith(ext)])
bnames = sorted( set( map(lambda x: re.sub("_1.fastq.gz$|_2.fastq.gz$|_R1.fastq.gz$|_R2.fastq.gz$","", os.path.basename(x)), infiles) ) )
## single-end
if len(infiles) == len(bnames):
args.paired = False
## paired-end
elif len(infiles) == 2 * len(bnames):
args.paired = True
unpaired = []
paired_infiles = []
for b in bnames:
if os.path.isfile( os.path.join(indir, b+"_1.fastq.gz" )) and os.path.isfile( os.path.join(indir, b+"_2.fastq.gz" )):
paired_infiles.append( [ os.path.join(indir, b+"_1.fastq.gz"), os.path.join(indir, b+"_2.fastq.gz") ] )
if os.path.isfile( os.path.join(indir, b+"_R1.fastq.gz" )) and os.path.isfile( os.path.join(indir, b+"_R2.fastq.gz" )):
paired_infiles.append( [ os.path.join(indir, b+"_R1.fastq.gz"), os.path.join(indir, b+"_R2.fastq.gz") ] )
else:
unpaired.append(b)
if unpaired:
print "Check input files starting with:"
for u in unpaired:
print os.path.join(indir, u+"...")
exit(1)
infiles = paired_infiles
else:
print "Error! The inputs is a mixture of single-end and paired-end files!"
exit(1)
if args.paired:
print "Paired-end FASTQ files ({} pairs)".format(len(infiles))
if verbose:
for pair in infiles:
print " {} {}".format(os.path.basename(pair[0]), os.path.basename(pair[1]))
else:
print "Single-end FASTQ files ({})".format(len(infiles))
if verbose:
for infile in infiles:
print " {}".format(os.path.basename(infile))
return infiles
def run_subprocess(cmd, cwd, td, shell=False, logfile=None, backcopy=True, verbose=False, keep_temp=False):
"""
Run the subprocess.
"""
try:
if verbose:
print "Temp dir:", td, "\n"
print cmd, "\n"
sys.stdout.flush() # force printing
if shell == True:
return subprocess.check_call("cd {} && ".format(td)+cmd, shell=True, executable='/bin/bash')
else:
if type(cmd) is str:
cmd = cmd.split()
# print "CMD:", cmd
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=td)
try:
if verbose:
print "PID:", p.pid
(stdoutdata, stderrdata) = p.communicate()
if logfile:
with open(logfile, "a+") as log:
if stderrdata:
log.write("{}\n".format(stderrdata))
if stdoutdata:
log.write("{}\n".format(stdoutdata))
if stderrdata:
print stderrdata
if stdoutdata:
print stdoutdata
if p.returncode != 0:
print "Error! Command failed with return code:", p.returncode
print " ".join(cmd) + "\n"
finally:
# print "poll:", p.poll()
if p.poll() == None:
print "Error! Trying to terminate PID {}".format(p.pid)
p.terminate()
time.sleep(20)
if p.poll() == None:
print "Error! Trying to kill PID {}!".format(p.pid)
p.kill()
exit(1)
return p.wait()
finally:
if backcopy:
for f in os.listdir(td):
if verbose:
print "Backcopy:", os.path.join(td, f)
if os.path.isfile(os.path.join(cwd,f)) or os.path.isdir(os.path.join(cwd,f)): # delete existing files with the same name in cwd
os.remove(os.path.join(cwd,f))
#shutil.rmtree(os.path.join(cwd,f), ignore_errors=True)
shutil.move(os.path.join(td,f), cwd)
def queue_worker(q, verbose=False, rest=0.3):
"""
Worker executing jobs (command lines) sent to the queue.
"""
global is_error
while True:
job = q.get()
if job.logfile:
logfile = job.logfile
else:
logfile = None
td = tempfile.mkdtemp(prefix="rna-seq-qc.", dir=temp_dir)
try:
for cmd in job.cmds:
if job.logfile:
with open(job.logfile, "a+") as log:
log.write("{}\n\n".format(cmd))
return_code = run_subprocess(cmd, job.cwd, td, shell=job.shell, logfile=logfile, backcopy=job.backcopy, verbose=verbose, keep_temp=job.keep_temp)
if return_code:
is_error = True
finally:
if os.path.isdir(td):
if not job.keep_temp:
shutil.rmtree(td)
q.task_done()
time.sleep(rest)
def convert_library_type(library_type, prog, paired):
"""
Convert TopHat library type to other program naming convention.
"""
new = None
if prog == "TopHat2":
new == library_type
elif prog == "RSeQC":
if library_type == 'fr-firststrand' and paired==True:
new = '"1+-,1-+,2++,2--"'
elif library_type == 'fr-secondstrand' and paired==True:
new = '"1++,1--,2+-,2-+"'
elif library_type == 'fr-firststrand' and paired==False:
new = '"+-,-+"'
elif library_type == 'fr-secondstrand' and paired==False:
new = '"++,--"'
elif library_type == 'fr-unstranded':
new = ''
else:
new = ''
elif prog == "HISAT2":
if library_type == 'fr-firststrand' and paired==True:
new = 'RF'
elif library_type == 'fr-secondstrand' and paired==True:
new = 'FR'
elif library_type == 'fr-firststrand' and paired==False:
new = 'R'
elif library_type == 'fr-secondstrand' and paired==False:
new = 'F'
elif library_type == 'fr-unstranded':
new = 'unstranded'
elif prog == "htseq-count":
if library_type == 'fr-firststrand' and paired==True:
new = 'reverse'
elif library_type == 'fr-secondstrand' and paired==True:
new = 'yes'
elif library_type == 'fr-firststrand' and paired==False:
new = 'reverse'
elif library_type == 'fr-secondstrand' and paired==False:
new = 'yes'
elif library_type == 'fr-unstranded':
new = 'no'
elif prog == "featureCounts":
if library_type == 'fr-firststrand' and paired==True:
new = '2'
elif library_type == 'fr-secondstrand' and paired==True:
new = '1'
elif library_type == 'fr-firststrand' and paired==False:
new = '2'
elif library_type == 'fr-secondstrand' and paired==False:
new = '1'
elif library_type == 'fr-unstranded':
new = '0'
elif prog == "Novoalign":
if library_type == 'fr-firststrand' and paired==True:
new = '-+'
elif library_type == 'fr-secondstrand' and paired==True:
new = '+-'
elif library_type == 'fr-firststrand' and paired==False:
new = '-'
elif library_type == 'fr-secondstrand' and paired==False:
new = '+'
elif library_type == 'fr-unstranded':
new = ''
return new
def get_library_type_from_rseqc(infile):
"""
Infer strand-specificity.
"""
specificity_list = []
is_first_file = True
with open(infile, "r") as f:
strands = OrderedDict()
for line in f.readlines():
line = line.strip()
if line.startswith('Fraction of reads explained by "'):
values = line.replace('Fraction of reads explained by "','').split('": ')
strands[values[0]] = float(values[1])
if line.startswith('Fraction of reads explained by other combinations: '):
value = float(line.replace('Fraction of reads explained by other combinations: ',''))
if value >= 0.2:
print "Error! A larger fraction ({}) of reads is explained by uncommon strand combinations!".format(value)
print infile
exit(1)
if len(strands.keys()) != 2:
print "Error! Unclear strand-specificity in:"
print infile
exit(1)
threshold = 0.6 #min quotient threshold
k = strands.keys()
v = strands.values()
specificity = "fr-unstranded"
if '++,--' in strands.keys() and '+-,-+' in strands.keys():
if strands['++,--'] >= threshold and strands['+-,-+'] <= threshold:
specificity = "fr-secondstrand"
elif strands['++,--'] <= threshold and strands['+-,-+'] >= threshold:
specificity = "fr-firststrand"
if '1++,1--,2+-,2-+' in strands.keys() and '1+-,1-+,2++,2--' in strands.keys():
if strands['1++,1--,2+-,2-+'] >= threshold and strands['1+-,1-+,2++,2--'] <= threshold:
specificity = "fr-secondstrand"
elif strands['1++,1--,2+-,2-+'] <= threshold and strands['1+-,1-+,2++,2--'] >= threshold:
specificity = "fr-firststrand"
if is_first_file:
specificity_list.append(specificity)
else:
is_first_file = False
if specificity not in specificity_list:
print "Error! Multiple strand specificities detected within different samples."
print " ".join(specificity_list)
exit(1)
else:
specificity_list.append(specificity)
return specificity_list[0]
def get_my_vars(infile, *var_names):
"""
Read variables from file, return values.
"""
values = {}
with open(infile, "r") as f:
for line in f.readlines():
line = line.strip()
if line:
c = line.split()
if len(c) != 2:
continue
else:
if c[0] not in values:
values[c[0]] = c[1]
else:
print "Error! Variables names exist multiple times:", c[0]
exit(1)
values_list = []
for name in var_names:
if name in values.keys():
values_list.append(values[name])
else:
#print "Error! Requested variable does NOT exist in file:", name
#exit(1)
values_list.append(None)
if len(values_list) == 1:
return values_list[0]
else:
return values_list
#### TOOLS #############################################################################################################
#### FASTQ DOWNSAMPLING ################################################################################################
def run_fastq_downsampling(args, q, indir, analysis_name="FASTQ_downsampling"):
"""
Reduce the number of sequences in FASTQ file to n first sequences
"""
args.analysis_counter += 1
outdir = "{}".format(analysis_name.replace(" ", "_"))
print "\n{} {}) {}".format(datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]'), args.analysis_counter, analysis_name)
if args.overwrite and os.path.isdir(outdir):
shutil.rmtree(outdir)
print "Outdir:", outdir
if os.path.isdir(outdir):
print "Output folder already present: {}".format(outdir)
else:
os.mkdir(outdir)
os.chdir(outdir)
cwd = os.getcwd()
print "In:", os.path.abspath(indir)
infiles = check_for_paired_infiles(args, indir, ".fastq.gz", verbose=True)
logfile = os.path.join(cwd, "LOG")
with open(logfile, "w") as log:
log.write("Processing {} file(s) in parallel\n\n".format(args.parallel))
if args.paired:
for pair in infiles:
jobs = ["{downsample} {n} {threads} {in1} {out1} {in2} {out2}"\
.format(downsample=os.path.join(script_path, "rna-seq-qc", "tools", "downsample_se_pe.sh"),
n=args.fastq_downsample,
threads=args.threads,
in1=pair[0],
out1=os.path.join(cwd, os.path.basename(pair[0])),
in2=pair[1],
out2=os.path.join(cwd, os.path.basename(pair[1]))
)]
q.put(Qjob(jobs, cwd=cwd, logfile=logfile, shell=True,
backcopy=True))
else:
for infile in infiles:
jobs = ["{downsample} {n} {threads} {in1} {out1}"\
.format(downsample=os.path.join(script_path, "rna-seq-qc", "tools", "downsample_se_pe.sh"),
n=args.fastq_downsample,
threads=args.threads,
in1=infile,
out1=os.path.join(cwd, os.path.basename(infile))
)]
q.put(Qjob(jobs, cwd=cwd, logfile=logfile, shell=True,
backcopy=True))
q.join()
if is_error:
exit(is_error)
print "Out:", os.path.join(args.outdir, outdir)
os.chdir(args.outdir)
return os.path.join(args.outdir, outdir)
#### FASTQC ############################################################################################################
def run_fastqc(args, q, indir, analysis_name="FastQC"):
"""
Run FastQC on FASTQ files.
"""
args.analysis_counter += 1
outdir = "{}".format(analysis_name)
print "\n{} {}) {}".format(datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]'), args.analysis_counter, analysis_name)
if args.overwrite and os.path.isdir(outdir):
shutil.rmtree(outdir)
if os.path.isdir(outdir):
print "Output folder already present: {}".format(outdir)
else:
os.mkdir(outdir)
os.chdir(outdir)
cwd = os.getcwd()
print "In:", os.path.abspath(indir)
infiles = sorted([os.path.join(indir, f) for f in os.listdir(os.path.abspath(indir)) if f.endswith(".fastq.gz")])
logfile = os.path.join(cwd, "LOG")
with open(logfile, "w") as log:
log.write("Processing {} file(s) in parallel\n\n".format(args.parallel))
jobs = ["{}fastqc --version".format(fastqc_path)]
q.put(Qjob(jobs, cwd=cwd, logfile=logfile, backcopy=True))
q.join()
# FastQC
for infile in infiles:
jobs = ["{}fastqc --extract -o {} {}".format(fastqc_path, cwd, infile)]
q.put(Qjob(jobs, cwd=cwd, logfile=logfile, backcopy=True))
q.join()
if is_error:
exit(is_error)
print "Out:", os.path.join(args.outdir, outdir)
os.chdir(args.outdir)
return os.path.join(args.outdir, outdir)
#### Trim Galore! ######################################################################################################
def run_trim_galore(args, q, indir, analysis_name="Trim Galore"):
"""
Run Trim Galore! with user specified options.
"""
args.analysis_counter += 1
outdir = "{}".format(analysis_name.replace(" ", "_"))
print "\n{} {}) {}".format(datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]'), args.analysis_counter, analysis_name)
if args.overwrite and os.path.isdir(outdir):
shutil.rmtree(outdir)
#print "Outdir:", outdir
if os.path.isdir(outdir):
print "Output folder already present: {}".format(outdir)
else:
os.mkdir(outdir)
os.chdir(outdir)
cwd = os.getcwd()
print "In:", os.path.abspath(indir)
infiles = check_for_paired_infiles(args, indir, ".fastq.gz")
logfile = os.path.join(cwd, "LOG")
with open(logfile, "w") as log:
log.write("Processing {} file(s) in parallel\n\n".format(args.parallel))
for infile in infiles:
if args.paired:
bname = re.sub("[1|2].fastq.gz$","",os.path.basename(infile[0]))
jobs = ["{} {}trim_galore --paired {} {} {}".format(cutadapt_activate, trim_galore_path, args.trim_galore_opts, infile[0], infile[1]),
"mv {}1_val_1.fq.gz {}1.fastq.gz".format(os.path.join(cwd,bname), os.path.join(cwd,bname)),
"mv {}2_val_2.fq.gz {}2.fastq.gz".format(os.path.join(cwd,bname), os.path.join(cwd,bname))]
else:
bname = re.sub(".fastq.gz$","",os.path.basename(infile))
jobs = ["{} {}trim_galore {} {}".format(cutadapt_activate, trim_galore_path, args.trim_galore_opts, infile),
"mv {}_trimmed.fq.gz {}.fastq.gz".format(os.path.join(cwd,bname), os.path.join(cwd,bname))]
q.put(Qjob(jobs, cwd=cwd, logfile=logfile, shell=True, backcopy=True))
q.join()
if is_error:
exit(is_error)
print "Out:", os.path.join(args.outdir, outdir)
os.chdir(args.outdir)
return os.path.join(args.outdir, outdir)
#### library_type ###########################################################################
def run_library_type(args, q, indir):
"""
- Random downsampling to n=100,000 reads
- Bowtie2 mapping to genome -> library_type (infer_experiment; RSeQC)
- Save a file with settings for TopHat2 (*.TopHat.txt): library-type
"""
n = 100000 # number of downsampling reads
analysis_name = "library_type"
args.analysis_counter += 1
outdir = "{}".format(analysis_name)
print "\n{} {}) {}".format(datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]'), args.analysis_counter, analysis_name)
if args.overwrite and os.path.isdir(outdir):
shutil.rmtree(outdir)
if os.path.isdir(outdir):
print "Output folder already present: {}".format(outdir)
else:
os.mkdir(outdir)
os.chdir(outdir)
cwd = os.getcwd()
logfile = os.path.join(cwd, "LOG")
with open(logfile, "w") as log:
log.write("Processing {} file(s) in parallel\n\n".format(args.parallel))
print "In:", os.path.abspath(indir)
infiles = check_for_paired_infiles(args, indir, ".fastq.gz")
#######################################################################
## User defined library type
#######################################################################
if args.library_type != 'auto':
library_type = args.library_type
print "User defined library type:", library_type
with open(logfile, "a") as log:
log.write("User defined library type: {}\n\n".format(library_type))
#######################################################################
## Automatic detection of library type
#######################################################################
else:
print "Autodetecting library type..."
###################################################################
## downsampling
###################################################################
if args.paired:
for pair in infiles:
jobs = [
"{downsample} {n} {threads} {in1} {out1} {in2} {out2}" \
.format(
downsample=os.path.join(script_path, "rna-seq-qc",
"tools",
"downsample_se_pe.sh"),
n=n,
threads=args.threads,
in1=pair[0],
out1=os.path.join(cwd, os.path.basename(pair[0])),
in2=pair[1],
out2=os.path.join(cwd, os.path.basename(pair[1]))
)]
q.put(Qjob(jobs, cwd=cwd, logfile=logfile, shell=True,
backcopy=True))
else:
for infile in infiles:
jobs = ["{downsample} {n} {threads} {in1} {out1}" \
.format(
downsample=os.path.join(script_path, "rna-seq-qc",
"tools",
"downsample_se_pe.sh"),
n=n,
threads=args.threads,
in1=infile,
out1=os.path.join(cwd, os.path.basename(infile))
)]
q.put(Qjob(jobs, cwd=cwd, logfile=logfile, shell=True,
backcopy=True))
q.join()
if is_error:
exit(is_error)
######################################################################
## Bowtie2 mapping to genome (for esimating strand specificity only!!!)
######################################################################
print "CWD:", os.getcwd()
infiles = check_for_paired_infiles(args, os.getcwd(), ".fastq.gz")
if args.paired:
for pair in infiles:
bname = re.sub("_R*[1|2].fastq.gz$","",os.path.basename(pair[0]))
jobs = ["{}bowtie2 -x {} -1 {} -2 {} --threads {} {} | {}samtools view -Sb - | {}samtools sort -@ {} -m {}G - {}.genome_mapped"\
.format(bowtie2_path, args.genome_index, pair[0], pair[1], args.threads, args.bowtie_opts,
samtools_path,
samtools_path, samtools_threads, samtools_mem, bname),
"rm {} {}".format(pair[0], pair[1]),]
#q.put(Qjob(jobs, shell=True, logfile="LOG"))
q.put(Qjob(jobs, cwd=cwd, logfile=logfile, backcopy=True, shell=True))
else:
for infile in infiles:
bname = re.sub(".fastq.gz$","",os.path.basename(infile))
jobs = ["{}bowtie2 -x {} -U {} -p {} {} | {}samtools view -Sb - | {}samtools sort -@ {} -m {}G - {}.genome_mapped"\
.format(bowtie2_path, args.genome_index, infile, args.threads, args.bowtie_opts,
samtools_path,
samtools_path, samtools_threads, samtools_mem, bname),
"rm {}".format(infile),
]
q.put(Qjob(jobs, cwd=cwd, logfile=logfile, backcopy=True, shell=True))
q.join()
if is_error:
exit(is_error)
###################################################################
# RSeQC infer_experiment
###################################################################
if not os.path.isdir("infer_experiment"):
os.mkdir("infer_experiment")
jobs = ["{} {}infer_experiment.py --version".format(rseqc_activate, rseqc_path)]
q.put(Qjob(jobs, shell=True, logfile="LOG"))
q.join()
infiles = sorted([f for f in os.listdir(os.path.join(args.outdir, outdir)) if f.endswith(".genome_mapped.bam")])
for infile in infiles:
print infile
bname = re.sub(".genome_mapped.bam$","",os.path.basename(infile))
jobs = ["{} {}infer_experiment.py -i {} -r {} > {}"\
.format(rseqc_activate, rseqc_path, os.path.join(cwd, infile), args.bed, os.path.join(cwd, "infer_experiment", bname+".infer_experiment.txt")),
"rm {}".format(os.path.join(args.outdir, outdir, infile)),
]
q.put(Qjob(jobs, cwd=cwd, logfile=logfile, backcopy=True, shell=True, keep_temp=False))
q.join()
###################################################################
## combining results
###################################################################
library_type_dic = {}
infiles = sorted([f for f in os.listdir(os.path.join(args.outdir, outdir, "infer_experiment")) if f.endswith(".infer_experiment.txt")])
for infile in infiles:
bname = re.sub(".infer_experiment.txt$","",os.path.basename(infile))
library_type = get_library_type_from_rseqc("infer_experiment/{}.infer_experiment.txt".format(bname))
if library_type not in library_type_dic:
library_type_dic[library_type] = [bname]
else:
library_type_dic[library_type].append(bname)
print "Using TopHat2 naming scheme"
for k,v in library_type_dic.iteritems():
print "{} ({}): {}".format(k, len(v), " ".join(sorted(v)))
library_type = sorted(library_type_dic.items(), key=lambda x: len(x[1]), reverse=True)[0][0]
print "Auto library type:", library_type
with open(logfile, "a") as log:
log.write("Auto library type: {}\n\n".format(library_type))
## write librariy type(s) to file
with open(os.path.join(cwd, "library_type.txt"), "w") as f:
f.write("TopHat2\t{}\n".format(library_type))
f.write("HISAT2\t{}\n".format(convert_library_type(library_type, 'HISAT2', args.paired)))
f.write("Novoalign\t{}\n".format(convert_library_type(library_type, 'Novoalign', args.paired)))
f.write("RSeQC\t{}\n".format(convert_library_type( library_type, 'RSeQC', args.paired ) ))
f.write("htseq-count\t{}\n".format(convert_library_type( library_type, 'htseq-count', args.paired ) ))
f.write("featureCounts\t{}\n".format(convert_library_type( library_type, 'featureCounts', args.paired ) ))
print "Out:", os.path.join(args.outdir, outdir)
os.chdir(args.outdir)
return os.path.join(args.outdir, outdir)
def run_distance_metrics(args, q, indir):
"""
- Random downsampling to 500,000 reads for TopHat2
- Bowtie2 mapping to transcriptome -> inner_distance (RSeQC) or InsertSizeMetrics (Picard) + CollectAlignmentSummaryMetrics (Picard)
- Save a setting file: mate_inner_dist, std_dev
"""
n = 500000 # number of downsampling reads
analysis_name = "distance_metrics"
args.analysis_counter += 1
outdir = "{}".format(analysis_name)
print "\n{} {}) {}".format(datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]'), args.analysis_counter, analysis_name)
if args.overwrite and os.path.isdir(outdir):
shutil.rmtree(outdir)