-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathProTECT.py
More file actions
2545 lines (2348 loc) · 118 KB
/
ProTECT.py
File metadata and controls
2545 lines (2348 loc) · 118 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright 2016 Arjun Arkal Rao
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Author : Arjun Arkal Rao
Affiliation : UCSC BME, UCSC Genomics Institute
File : protect/ProTECT.py
Program info can be found in the docstring of the main function.
Details can also be obtained by running the script with -h .
"""
import argparse
import errno
import gzip
import json
import shutil
import subprocess
import sys
import tarfile
import time
from collections import defaultdict, Counter
from multiprocessing import cpu_count
from urllib.parse import urlparse
from pysam import Samfile
import os
import re
from attic.encrypt_files_in_dir_to_s3 import write_to_s3
from toil.job import Job
def parse_config_file(job, config_file):
"""
This module will parse the config file withing params and set up the variables that will be
passed to the various tools in the pipeline.
ARGUMENTS
config_file: string containing path to a config file. An example config
file is available at
https://s3-us-west-2.amazonaws.com/pimmuno-references
/input_parameters.list
RETURN VALUES
None
"""
job.fileStore.logToMaster('Parsing config file')
config_file = os.path.abspath(config_file)
if not os.path.exists(config_file):
raise ParameterError('The config file was not found at specified location. Please verify ' +
'and retry.')
# Initialize variables to hold the sample sets, the universal options, and the per-tool options
sample_set = defaultdict()
univ_options = defaultdict()
tool_options = defaultdict()
# Read through the notes and the
with open(config_file, 'r') as conf:
for line in conf:
line = line.strip()
if line.startswith('##') or len(line) == 0:
continue
if line.startswith('BEGIN'):
break
# The generator function tool_specific_param_generator will yield one group name at a time
# along with it's parameters.
for groupname, group_params in tool_specific_param_generator(job, conf):
if groupname == 'patient':
if 'patient_id' not in list(group_params.keys()):
raise ParameterError('A patient group is missing the patient_id flag.')
sample_set[group_params['patient_id']] = group_params
elif groupname == 'Universal_Options':
univ_options = group_params
required_options = {'java_Xmx', 'output_folder', 'storage_location'}
missing_opts = required_options.difference(set(univ_options.keys()))
if len(missing_opts) > 0:
raise ParameterError(' The following options have no arguments in the config '
'file :\n' + '\n'.join(missing_opts))
if univ_options['sse_key_is_master']:
assert univ_options['sse_key_is_master'] in ('True', 'true', 'False', 'false')
univ_options['sse_key_is_master'] = \
univ_options['sse_key_is_master'] in ('True', 'true')
# If it isn't any of the above, it's a tool group
else:
tool_options[groupname] = group_params
# Ensure that all tools have been provided options.
required_tools = {'cutadapt', 'bwa', 'star', 'phlat', 'transgene', 'mut_callers', 'rsem',
'mhci', 'mhcii', 'snpeff', 'rank_boost'}
# 'fusion', 'indels'}
missing_tools = required_tools.difference(set(tool_options.keys()))
if len(missing_tools) > 0:
raise ParameterError(' The following tools have no arguments in the config file : \n' +
'\n'.join(missing_tools))
# Start a job for each sample in the sample set
for patient_id in list(sample_set.keys()):
job.addFollowOnJobFn(pipeline_launchpad, sample_set[patient_id], univ_options, tool_options)
return None
def pipeline_launchpad(job, fastqs, univ_options, tool_options):
"""
The precision immuno pipeline begins at this module. The DAG can be viewed in Flowchart.txt
This module corresponds to node 0 on the tree
"""
# Add Patient id to univ_options as is is passed to every major node in the DAG and can be used
# as a prefix for the logfile.
univ_options['patient'] = fastqs['patient_id']
# Ascertain the number of available CPUs. Jobs will be given fractions of this value.
ncpu = cpu_count()
tool_options['star']['n'] = tool_options['bwa']['n'] = tool_options['phlat']['n'] = \
tool_options['rsem']['n'] = ncpu / 3
# Define the various nodes in the DAG
# Need a logfile and a way to send it around
sample_prep = job.wrapJobFn(prepare_samples, fastqs, univ_options, disk='140G')
cutadapt = job.wrapJobFn(run_cutadapt, sample_prep.rv(), univ_options, tool_options['cutadapt'],
cores=1, disk='80G')
star = job.wrapJobFn(run_star, cutadapt.rv(), univ_options, tool_options['star'],
cores=tool_options['star']['n'], memory='40G', disk='120G').encapsulate()
bwa_tumor = job.wrapJobFn(run_bwa, sample_prep.rv(), 'tumor_dna', univ_options,
tool_options['bwa'], cores=tool_options['bwa']['n'],
disk='120G').encapsulate()
bwa_normal = job.wrapJobFn(run_bwa, sample_prep.rv(), 'normal_dna', univ_options,
tool_options['bwa'], cores=tool_options['bwa']['n'],
disk='120G').encapsulate()
phlat_tumor_dna = job.wrapJobFn(run_phlat, sample_prep.rv(), 'tumor_dna', univ_options,
tool_options['phlat'], cores=tool_options['phlat']['n'],
disk='60G')
phlat_normal_dna = job.wrapJobFn(run_phlat, sample_prep.rv(), 'normal_dna', univ_options,
tool_options['phlat'], cores=tool_options['phlat']['n'],
disk='60G')
phlat_tumor_rna = job.wrapJobFn(run_phlat, sample_prep.rv(), 'tumor_rna', univ_options,
tool_options['phlat'], cores=tool_options['phlat']['n'],
disk='60G')
fastq_deletion = job.wrapJobFn(delete_fastqs, sample_prep.rv())
rsem = job.wrapJobFn(run_rsem, star.rv(), univ_options, tool_options['rsem'],
cores=tool_options['rsem']['n'], disk='80G')
mhc_pathway_assessment = job.wrapJobFn(assess_mhc_genes, rsem.rv(), phlat_tumor_rna.rv(),
univ_options, tool_options['mhc_pathway_assessment'])
fusions = job.wrapJobFn(run_fusion_caller, star.rv(), univ_options, 'fusion_options')
Sradia = job.wrapJobFn(spawn_radia, star.rv(), bwa_tumor.rv(),
bwa_normal.rv(), univ_options, tool_options['mut_callers']).encapsulate()
Mradia = job.wrapJobFn(merge_radia, Sradia.rv())
Smutect = job.wrapJobFn(spawn_mutect, bwa_tumor.rv(), bwa_normal.rv(), univ_options,
tool_options['mut_callers']).encapsulate()
Mmutect = job.wrapJobFn(merge_mutect, Smutect.rv())
indels = job.wrapJobFn(run_indel_caller, bwa_tumor.rv(), bwa_normal.rv(), univ_options,
'indel_options')
merge_mutations = job.wrapJobFn(run_mutation_aggregator, fusions.rv(), Mradia.rv(),
Mmutect.rv(), indels.rv(), univ_options)
snpeff = job.wrapJobFn(run_snpeff, merge_mutations.rv(), univ_options, tool_options['snpeff'],
disk='30G')
transgene = job.wrapJobFn(run_transgene, snpeff.rv(), univ_options, tool_options['transgene'],
disk='5G')
merge_phlat = job.wrapJobFn(merge_phlat_calls, phlat_tumor_dna.rv(), phlat_normal_dna.rv(),
phlat_tumor_rna.rv(), disk='5G')
spawn_mhc = job.wrapJobFn(spawn_antigen_predictors, transgene.rv(), merge_phlat.rv(),
univ_options, (tool_options['mhci'],
tool_options['mhcii'])).encapsulate()
merge_mhc = job.wrapJobFn(merge_mhc_peptide_calls, spawn_mhc.rv(), transgene.rv(), disk='5G')
rank_boost = job.wrapJobFn(boost_ranks, rsem.rv(), merge_mhc.rv(), transgene.rv(), univ_options,
tool_options['rank_boost'], disk='5G')
# Define the DAG in a static form
job.addChild(sample_prep) # Edge 0->1
# A. The first step is running the alignments and the MHC haplotypers
sample_prep.addChild(cutadapt) # Edge 1->2
sample_prep.addChild(bwa_tumor) # Edge 1->3
sample_prep.addChild(bwa_normal) # Edge 1->4
sample_prep.addChild(phlat_tumor_dna) # Edge 1->5
sample_prep.addChild(phlat_normal_dna) # Edge 1->6
sample_prep.addChild(phlat_tumor_rna) # Edge 1->7
# B. cutadapt will be followed by star
cutadapt.addChild(star) # Edge 2->9
# Ci. gene expression and fusion detection follow start alignment
star.addChild(rsem) # Edge 9->10
star.addChild(fusions) # Edge 9->11
# Cii. Radia depends on all 3 alignments
star.addChild(Sradia) # Edge 9->12
bwa_tumor.addChild(Sradia) # Edge 3->12
bwa_normal.addChild(Sradia) # Edge 4->12
# Ciii. mutect and indel calling depends on dna to have been aligned
bwa_tumor.addChild(Smutect) # Edge 3->13
bwa_normal.addChild(Smutect) # Edge 4->13
bwa_tumor.addChild(indels) # Edge 3->14
bwa_normal.addChild(indels) # Edge 4->14
# D. MHC haplotypes will be merged once all 3 samples have been PHLAT-ed
phlat_tumor_dna.addChild(merge_phlat) # Edge 5->15
phlat_normal_dna.addChild(merge_phlat) # Edge 6->15
phlat_tumor_rna.addChild(merge_phlat) # Edge 7->15
# E. Delete the fastqs from the job store since all alignments are complete
sample_prep.addChild(fastq_deletion) # Edge 1->8
cutadapt.addChild(fastq_deletion) # Edge 2->8
bwa_normal.addChild(fastq_deletion) # Edge 3->8
bwa_tumor.addChild(fastq_deletion) # Edge 4->8
phlat_normal_dna.addChild(fastq_deletion) # Edge 5->8
phlat_tumor_dna.addChild(fastq_deletion) # Edge 6>8
phlat_tumor_rna.addChild(fastq_deletion) # Edge 7->8
# F. Mutation calls need to be merged before they can be used
Sradia.addChild(Mradia) # Edge 12->16
Smutect.addChild(Mmutect) # Edge 13->17
# G. All mutations get aggregated when they have finished running
fusions.addChild(merge_mutations) # Edge 11->18
Mradia.addChild(merge_mutations) # Edge 16->18
Mmutect.addChild(merge_mutations) # Edge 17->18
indels.addChild(merge_mutations) # Edge 14->18
# H. Aggregated mutations will be translated to protein space
merge_mutations.addChild(snpeff) # Edge 18->19
# I. snpeffed mutations will be converted into peptides
snpeff.addChild(transgene) # Edge 19->20
# J. Merged haplotypes and peptides will be converted into jobs and submitted for mhc:peptide
# binding prediction
merge_phlat.addChild(spawn_mhc) # Edge 15->21
transgene.addChild(spawn_mhc) # Edge 20->21
# K. The results from all the predictions will be merged. This is a follow-on job because
# spawn_mhc will spawn an undetermined number of children.
spawn_mhc.addFollowOn(merge_mhc) # Edges 21->XX->22 and 21->YY->22
# L. Finally, the merged mhc along with the gene expression will be used for rank boosting
rsem.addChild(rank_boost) # Edge 10->23
merge_mhc.addChild(rank_boost) # Edge 22->23
# M. Assess the status of the MHC genes in the patient
phlat_tumor_rna.addChild(mhc_pathway_assessment) # Edge 7->24
rsem.addChild(mhc_pathway_assessment) # Edge 10->24
return None
def delete_fastqs(job, fastqs):
"""
This module will delete the fastqs from teh job Store once their purpose has been achieved (i.e.
after all mapping steps)
ARGUMENTS
1. fastqs: Dict of list of input fastqs
fastqs
+- 'tumor_rna': [<JSid for 1.fastq> , <JSid for 2.fastq>]
+- 'tumor_dna': [<JSid for 1.fastq> , <JSid for 2.fastq>]
+- 'normal_dna': [<JSid for 1.fastq> , <JSid for 2.fastq>]
"""
for fq_type in ['tumor_rna', 'tumor_dna', 'normal_dna']:
for i in range(0,2):
job.fileStore.deleteGlobalFile(fastqs[fq_type][i])
return None
def run_cutadapt(job, fastqs, univ_options, cutadapt_options):
"""
This module runs cutadapt on the input RNA fastq files and then calls the RNA aligners.
ARGUMENTS
1. fastqs: Dict of list of input RNA-Seq fastqs
fastqs
+- 'tumor_rna': [<JSid for 1.fastq> , <JSid for 2.fastq>]
2. univ_options: Dict of universal arguments used by almost all tools
univ_options
+- 'dockerhub': <dockerhub to use>
3. cutadapt_options: Dict of parameters specific to cutadapt
cutadapt_options
|- 'a': <sequence of 3' adapter to trim from fwd read>
+- 'A': <sequence of 3' adapter to trim from rev read>
RETURN VALUES
1. output_files: Dict of cutadapted fastqs
output_files
|- 'rna_cutadapt_1.fastq': <JSid>
+- 'rna_cutadapt_2.fastq': <JSid>
This module corresponds to node 2 on the tree
"""
job.fileStore.logToMaster('Running cutadapt on %s' %univ_options['patient'])
work_dir = job.fileStore.getLocalTempDir()
fq_extn = '.gz' if fastqs['gzipped'] else ''
input_files = {
'rna_1.fastq' + fq_extn: fastqs['tumor_rna'][0],
'rna_2.fastq' + fq_extn: fastqs['tumor_rna'][1]}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=True)
parameters = ['-a', cutadapt_options['a'], # Fwd read 3' adapter
'-A', cutadapt_options['A'], # Rev read 3' adapter
'-m', '35', # Minimum size of read
'-o', docker_path('rna_cutadapt_1.fastq'), # Output for R1
'-p', docker_path('rna_cutadapt_2.fastq'), # Output for R2
input_files['rna_1.fastq'],
input_files['rna_2.fastq']]
docker_call(tool='cutadapt', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'])
output_files = defaultdict()
for fastq_file in ['rna_cutadapt_1.fastq', 'rna_cutadapt_2.fastq']:
output_files[fastq_file] = job.fileStore.writeGlobalFile('/'.join([work_dir, fastq_file]))
return output_files
def run_star(job, fastqs, univ_options, star_options):
"""
This module uses STAR to align the RNA fastqs to the reference
ARGUMENTS
1. fastqs: REFER RETURN VALUE of run_cutadapt()
2. univ_options: Dict of universal arguments used by almost all tools
univ_options
+- 'dockerhub': <dockerhub to use>
3. star_options: Dict of parameters specific to STAR
star_options
|- 'index_tar': <JSid for the STAR index tarball>
+- 'n': <number of threads to allocate>
RETURN VALUES
1. output_files: Dict of aligned bams
output_files
|- 'rnaAligned.toTranscriptome.out.bam': <JSid>
+- 'rnaAligned.sortedByCoord.out.bam': Dict of genome bam + bai
|- 'rna_fix_pg_sorted.bam': <JSid>
+- 'rna_fix_pg_sorted.bam.bai': <JSid>
This module corresponds to node 9 on the tree
"""
assert star_options['type'] in ('star', 'starlong')
job.fileStore.logToMaster('Running STAR on %s' %univ_options['patient'])
work_dir = job.fileStore.getLocalTempDir()
input_files = {
'rna_cutadapt_1.fastq': fastqs['rna_cutadapt_1.fastq'],
'rna_cutadapt_2.fastq': fastqs['rna_cutadapt_2.fastq'],
'star_index.tar.gz': star_options['index_tar']}
input_files = get_files_from_filestore(job, input_files, work_dir,
docker=True)
parameters = ['--runThreadN', str(star_options['n']),
'--genomeDir', input_files['star_index'],
'--outFileNamePrefix', 'rna',
'--readFilesIn',
input_files['rna_cutadapt_1.fastq'],
input_files['rna_cutadapt_2.fastq'],
'--outSAMattributes', 'NH', 'HI', 'AS', 'NM', 'MD',
'--outSAMtype', 'BAM', 'SortedByCoordinate',
'--quantMode', 'TranscriptomeSAM',
'--outSAMunmapped', 'Within']
if star_options['type'] == 'star':
docker_call(tool='star', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'])
else:
docker_call(tool='starlong', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'])
output_files = defaultdict()
for bam_file in ['rnaAligned.toTranscriptome.out.bam',
'rnaAligned.sortedByCoord.out.bam']:
output_files[bam_file] = job.fileStore.writeGlobalFile('/'.join([
work_dir, bam_file]))
job.fileStore.deleteGlobalFile(fastqs['rna_cutadapt_1.fastq'])
job.fileStore.deleteGlobalFile(fastqs['rna_cutadapt_2.fastq'])
index_star = job.wrapJobFn(index_bamfile,
output_files['rnaAligned.sortedByCoord.out.bam'],
'rna', univ_options, disk='120G')
job.addChild(index_star)
output_files['rnaAligned.sortedByCoord.out.bam'] = index_star.rv()
return output_files
def run_bwa(job, fastqs, sample_type, univ_options, bwa_options):
"""
This module aligns the SAMPLE_TYPE dna fastqs to the reference
ARGUMENTS -- <ST> depicts the sample type. Substitute with 'tumor'/'normal'
1. fastqs: Dict of list of input WGS/WXS fastqs
fastqs
+- '<ST>_dna': [<JSid for 1.fastq> , <JSid for 2.fastq>]
2. sample_type: string of 'tumor_dna' or 'normal_dna'
3. univ_options: Dict of universal arguments used by almost all tools
univ_options
+- 'dockerhub': <dockerhub to use>
4. bwa_options: Dict of parameters specific to bwa
bwa_options
|- 'index_tar': <JSid for the bwa index tarball>
+- 'n': <number of threads to allocate>
RETURN VALUES
1. output_files: Dict of aligned bam + reference (nested return)
output_files
|- '<ST>_fix_pg_sorted.bam': <JSid>
+- '<ST>_fix_pg_sorted.bam.bai': <JSid>
This module corresponds to nodes 3 and 4 on the tree
"""
job.fileStore.logToMaster('Running bwa on %s:%s' % (univ_options['patient'], sample_type))
work_dir = job.fileStore.getLocalTempDir()
fq_extn = '.gz' if fastqs['gzipped'] else ''
input_files = {
'dna_1.fastq' + fq_extn: fastqs[sample_type][0],
'dna_2.fastq' + fq_extn: fastqs[sample_type][1],
'bwa_index.tar.gz': bwa_options['index_tar']}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=True)
parameters = ['mem',
'-t', str(bwa_options['n']),
'-v', '1', # Don't print INFO messages to the stderr
'/'.join([input_files['bwa_index'], 'hg19.fa']),
input_files['dna_1.fastq'],
input_files['dna_2.fastq']]
with open(''.join([work_dir, '/', sample_type, '_aligned.sam']), 'w') as samfile:
docker_call(tool='bwa', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'], outfile=samfile)
# samfile.name retains the path info
output_file = job.fileStore.writeGlobalFile(samfile.name)
samfile_processing = job.wrapJobFn(bam_conversion, output_file, sample_type, univ_options,
disk='60G')
job.addChild(samfile_processing)
# Return values get passed up the chain to here. The return value will be a dict with
# SAMPLE_TYPE_fix_pg_sorted.bam: jobStoreID
# SAMPLE_TYPE_fix_pg_sorted.bam.bai: jobStoreID
return samfile_processing.rv()
def bam_conversion(job, samfile, sample_type, univ_options):
"""
This module converts SAMFILE from sam to bam
ARGUMENTS
1. samfile: <JSid for a sam file>
2. sample_type: string of 'tumor_dna' or 'normal_dna'
3. univ_options: Dict of universal arguments used by almost all tools
univ_options
+- 'dockerhub': <dockerhub to use>
RETURN VALUES
1. output_files: REFER output_files in run_bwa()
"""
job.fileStore.logToMaster('Running sam2bam on %s:%s' % (univ_options['patient'], sample_type))
work_dir = job.fileStore.getLocalTempDir()
input_files = {
'aligned.sam': samfile}
input_files = get_files_from_filestore(job, input_files, work_dir,
docker=True)
bamfile = '/'.join([work_dir, 'aligned.bam'])
parameters = ['view',
'-bS',
'-o', docker_path(bamfile),
input_files['aligned.sam']
]
docker_call(tool='samtools', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'])
output_file = job.fileStore.writeGlobalFile(bamfile)
job.fileStore.deleteGlobalFile(samfile)
reheader_bam = job.wrapJobFn(fix_bam_header, output_file, sample_type, univ_options, disk='60G')
job.addChild(reheader_bam)
return reheader_bam.rv()
def fix_bam_header(job, bamfile, sample_type, univ_options):
"""
This module modified the header in BAMFILE
ARGUMENTS
1. bamfile: <JSid for a bam file>
2. sample_type: string of 'tumor_dna' or 'normal_dna'
3. univ_options: Dict of universal arguments used by almost all tools
univ_options
+- 'dockerhub': <dockerhub to use>
RETURN VALUES
1. output_files: REFER output_files in run_bwa()
"""
job.fileStore.logToMaster('Running reheader on %s:%s' % (univ_options['patient'], sample_type))
work_dir = job.fileStore.getLocalTempDir()
input_files = {
'aligned.bam': bamfile}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=True)
parameters = ['view',
'-H',
input_files['aligned.bam']]
with open('/'.join([work_dir, 'aligned_bam.header']), 'w') as headerfile:
docker_call(tool='samtools', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'], outfile=headerfile)
with open(headerfile.name, 'r') as headerfile, \
open('/'.join([work_dir, 'output_bam.header']), 'w') as outheaderfile:
for line in headerfile:
if line.startswith('@PG'):
line = '\t'.join([x for x in line.strip().split('\t') if not x.startswith('CL')])
print(line.strip(), file=outheaderfile)
parameters = ['reheader',
docker_path(outheaderfile.name),
input_files['aligned.bam']]
with open('/'.join([work_dir, 'aligned_fixPG.bam']), 'w') as fixpg_bamfile:
docker_call(tool='samtools', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'], outfile=fixpg_bamfile)
output_file = job.fileStore.writeGlobalFile(fixpg_bamfile.name)
job.fileStore.deleteGlobalFile(bamfile)
add_rg = job.wrapJobFn(add_readgroups, output_file, sample_type, univ_options, disk='60G')
job.addChild(add_rg)
return add_rg.rv()
def add_readgroups(job, bamfile, sample_type, univ_options):
"""
This module adds the appropriate read groups to the bam file
ARGUMENTS
1. bamfile: <JSid for a bam file>
2. sample_type: string of 'tumor_dna' or 'normal_dna'
3. univ_options: Dict of universal arguments used by almost all tools
univ_options
|- 'dockerhub': <dockerhub to use>
+- 'java_Xmx': value for max heap passed to java
RETURN VALUES
1. output_files: REFER output_files in run_bwa()
"""
job.fileStore.logToMaster('Running add_read_groups on %s:%s' % (univ_options['patient'],
sample_type))
work_dir = job.fileStore.getLocalTempDir()
input_files = {
'aligned_fixpg.bam': bamfile}
get_files_from_filestore(job, input_files, work_dir, docker=True)
parameters = ['AddOrReplaceReadGroups',
'CREATE_INDEX=false',
'I=/data/aligned_fixpg.bam',
'O=/data/aligned_fixpg_sorted_reheader.bam',
'SO=coordinate',
'ID=1',
''.join(['LB=', univ_options['patient']]),
'PL=ILLUMINA',
'PU=12345',
''.join(['SM=', sample_type.rstrip('_dna')])]
docker_call(tool='picard', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'], java_opts=univ_options['java_Xmx'])
output_file = job.fileStore.writeGlobalFile('/'.join([work_dir,
'aligned_fixpg_sorted_reheader.bam']))
job.fileStore.deleteGlobalFile(bamfile)
bam_index = job.wrapJobFn(index_bamfile, output_file, sample_type, univ_options, disk='60G')
job.addChild(bam_index)
return bam_index.rv()
def index_bamfile(job, bamfile, sample_type, univ_options):
"""
This module indexes BAMFILE
ARGUMENTS
1. bamfile: <JSid for a bam file>
2. sample_type: string of 'tumor_dna' or 'normal_dna'
3. univ_options: Dict of universal arguments used by almost all tools
univ_options
+- 'dockerhub': <dockerhub to use>
RETURN VALUES
1. output_files: REFER output_files in run_bwa(). This module is the one is
the one that generates the files.
"""
job.fileStore.logToMaster('Running samtools-index on %s:%s' % (univ_options['patient'],
sample_type))
work_dir = job.fileStore.getLocalTempDir()
in_bamfile = '_'.join([sample_type, 'fix_pg_sorted.bam'])
input_files = {
in_bamfile: bamfile}
input_files = get_files_from_filestore(job, input_files, work_dir,
docker=True)
parameters = ['index',
input_files[in_bamfile]]
docker_call(tool='samtools', tool_parameters=parameters,
work_dir=work_dir, dockerhub=univ_options['dockerhub'])
output_files = {in_bamfile: bamfile,
in_bamfile + '.bai': job.fileStore.writeGlobalFile('/'.join([work_dir,
in_bamfile +
'.bai']))}
return output_files
def run_rsem(job, star_bams, univ_options, rsem_options):
"""
This module will run rsem on the RNA Bam file.
ARGUMENTS
1. star_bams: Dict of input STAR bams
star_bams
+- 'rnaAligned.toTranscriptome.out.bam': <JSid>
2. univ_options: Dict of universal arguments used by almost all tools
univ_options
+- 'dockerhub': <dockerhub to use>
3. rsem_options: Dict of parameters specific to rsem
rsem_options
|- 'index_tar': <JSid for the rsem index tarball>
+- 'n': <number of threads to allocate>
RETURN VALUES
1. output_file: <Jsid of rsem.isoforms.results>
This module corresponds to node 9 on the tree
"""
job.fileStore.logToMaster('Running rsem index on %s' % univ_options['patient'])
work_dir = job.fileStore.getLocalTempDir()
input_files = {
'star_transcriptome.bam': star_bams['rnaAligned.toTranscriptome.out.bam'],
'rsem_index.tar.gz': rsem_options['index_tar']}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=True)
parameters = ['--paired-end',
'-p', str(rsem_options['n']),
'--bam',
input_files['star_transcriptome.bam'],
'--no-bam-output',
'/'.join([input_files['rsem_index'], 'hg19']),
'rsem']
docker_call(tool='rsem', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'])
output_file = \
job.fileStore.writeGlobalFile('/'.join([work_dir, 'rsem.isoforms.results']))
return output_file
def assess_mhc_genes(job, isoform_expression, rna_haplotype, univ_options, mhc_genes_options):
"""
This module will assess the prevalence of the various genes in the MHC pathway and return a
report in the tsv format
:param isoform_expression: Isoform expression from run_rsem
:param rna_haplotype: PHLAT output from running on rna
:param univ_options: Universal options for the pipeline
:param mhc_genes_options: options specific to this module
"""
job.fileStore.logToMaster('Running mhc gene assessment on %s' % univ_options['patient'])
work_dir = job.fileStore.getLocalTempDir()
input_files = {
'rsem_quant.tsv': isoform_expression,
'rna_haplotype.sum': rna_haplotype,
'mhc_genes.json': mhc_genes_options['genes_file']}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=False)
# Read in the MHC genes
with open(input_files['mhc_genes.json']) as mhc_file:
mhc_genes = json.load(mhc_file)
# Parse the rna phlat file
with open(input_files['rna_haplotype.sum']) as rna_mhc:
mhc_alleles = {'HLA_A': [], 'HLA_B': [], 'HLA_C': [], 'HLA_DPA': [], 'HLA_DQA': [],
'HLA_DPB': [], 'HLA_DQB': [], 'HLA_DRB': []}
mhc_alleles = parse_phlat_file(rna_mhc, mhc_alleles)
# Process the isoform expressions
gene_expressions = Counter()
with open(input_files['rsem_quant.tsv']) as rsem_file:
line = rsem_file.readline()
line = line.strip().split()
assert line == ['transcript_id', 'gene_id', 'length', 'effective_length', 'expected_count',
'TPM', 'FPKM', 'IsoPct']
for line in rsem_file:
line = line.strip().split()
gene_expressions[line[1]] += float(line[5])
with open(os.path.join(work_dir, 'mhc_pathway_report.txt'), 'w') as mpr:
for section in mhc_genes:
print(section.center(48, ' '), file=mpr)
print("{:12}{:12}{:12}{:12}".format("Gene", "Threshold", "Observed", "Result"),
file=mpr)
if section == 'MHCI loading':
for mhci_allele in 'HLA_A', 'HLA_B', 'HLA_C':
num_alleles = len(mhc_alleles[mhci_allele])
print("{:12}{:12}{:12}{:12}".format(mhci_allele, '2', num_alleles,
'FAIL' if num_alleles == 0
else 'LOW' if num_alleles == 1
else 'PASS'), file=mpr)
elif section == 'MHCII loading':
#TODO DP alleles
for mhcii_allele in ('HLA_DQA', 'HLA_DQB', 'HLA_DRA', 'HLA_DRB'):
if mhcii_allele != 'HLA_DRA':
num_alleles = len(mhc_alleles[mhcii_allele])
print("{:12}{:12}{:12}{:12}".format(mhcii_allele, 2, num_alleles,
'FAIL' if num_alleles == 0 else 'LOW' if num_alleles == 1 else 'PASS'),
file=mpr)
else:
# FIXME This is hardcoded for now. We need to change this.
print("{:12}{:<12}{:<12}{:12}".format(
'HLA_DRA', gene_expressions['ENSG00000204287.9'], '69.37',
'LOW' if gene_expressions['ENSG00000204287.9'] <= 69.37
else 'PASS'), file=mpr)
for gene, ensgene, first_quart in mhc_genes[section]:
print("{:12}{:<12}{:<12}{:12}".format(
gene, float(first_quart), gene_expressions[ensgene],
'LOW' if gene_expressions[ensgene] <= float(first_quart) else 'PASS'),
file=mpr)
print('', file=mpr)
export_results(mpr.name, univ_options)
output_file = job.fileStore.writeGlobalFile(mpr.name)
return output_file
def spawn_radia(job, rna_bam, tumor_bam, normal_bam, univ_options, radia_options):
"""
This module will spawn a radia job for each chromosome, on the RNA and DNA.
ARGUMENTS
1. rna_bam: Dict of input STAR bams
rna_bam
|- 'rnaAligned.sortedByCoord.out.bam': REFER run_star()
|- 'rna_fix_pg_sorted.bam': <JSid>
+- 'rna_fix_pg_sorted.bam.bai': <JSid>
2. tumor_bam: Dict of input tumor WGS/WSQ bam + bai
tumor_bam
|- 'tumor_fix_pg_sorted.bam': <JSid>
+- 'tumor_fix_pg_sorted.bam.bai': <JSid>
3. normal_bam: Dict of input normal WGS/WSQ bam + bai
normal_bam
|- 'normal_fix_pg_sorted.bam': <JSid>
+- 'normal_fix_pg_sorted.bam.bai': <JSid>
4. univ_options: Dict of universal arguments used by almost all tools
univ_options
+- 'dockerhub': <dockerhub to use>
5. radia_options: Dict of parameters specific to radia
radia_options
|- 'genome_fasta': <JSid for genome fasta file>
+- 'genome_fai': <JSid for genome fai file>
RETURN VALUES
1. perchrom_radia: Dict of results of radia per chromosome
perchrom_radia
|- 'chr1'
| |- 'radia_filtered_chr1.vcf': <JSid>
| +- 'radia_filtered_chr1_radia.log': <JSid>
|- 'chr2'
| |- 'radia_filtered_chr2.vcf': <JSid>
| +- 'radia_filtered_chr2_radia.log': <JSid>
etc...
This module corresponds to node 11 on the tree
"""
job.fileStore.logToMaster('Running spawn_radia on %s' % univ_options['patient'])
rna_bam_key = 'rnaAligned.sortedByCoord.out.bam' # to reduce next line size
bams = {'tumor_rna': rna_bam[rna_bam_key]['rna_fix_pg_sorted.bam'],
'tumor_rnai': rna_bam[rna_bam_key]['rna_fix_pg_sorted.bam.bai'],
'tumor_dna': tumor_bam['tumor_dna_fix_pg_sorted.bam'],
'tumor_dnai': tumor_bam['tumor_dna_fix_pg_sorted.bam.bai'],
'normal_dna': normal_bam['normal_dna_fix_pg_sorted.bam'],
'normal_dnai': normal_bam['normal_dna_fix_pg_sorted.bam.bai']}
# Make a dict object to hold the return values for each of the chromosome jobs. Then run radia
# on each chromosome.
chromosomes = [''.join(['chr', str(x)]) for x in list(range(1, 23)) + ['X', 'Y']]
perchrom_radia = defaultdict()
for chrom in chromosomes:
perchrom_radia[chrom] = job.addChildJobFn(run_radia, bams, univ_options, radia_options,
chrom, disk='60G', memory='6G').rv()
return perchrom_radia
def merge_radia(job, perchrom_rvs):
"""
This module will merge the per-chromosome radia files created by spawn_radia into a genome vcf.
It will make 2 vcfs, one for PASSing non-germline calls, and one for all calls.
ARGUMENTS
1. perchrom_rvs: REFER RETURN VALUE of spawn_radia()
RETURN VALUES
1. output_files: Dict of outputs
output_files
|- radia_calls.vcf: <JSid>
+- radia_parsed_filter_passing_calls.vcf: <JSid>
This module corresponds to node 11 on the tree
"""
job.fileStore.logToMaster('Running merge_radia')
work_dir = job.fileStore.getLocalTempDir()
# We need to squash the input dict of dicts to a single dict such that it can be passed to
# get_files_from_filestore
input_files = {filename: jsid for perchrom_files in list(perchrom_rvs.values())
for filename, jsid in list(perchrom_files.items())}
input_files = get_files_from_filestore(job, input_files, work_dir,
docker=False)
chromosomes = [''.join(['chr', str(x)]) for x in list(range(1, 23)) + ['X', 'Y']]
with open('/'.join([work_dir, 'radia_calls.vcf']), 'w') as radfile, \
open('/'.join([work_dir, 'radia_filter_passing_calls.vcf']), 'w') as radpassfile:
for chrom in chromosomes:
with open(input_files[''.join(['radia_filtered_', chrom, '.vcf'])], 'r') as filtradfile:
for line in filtradfile:
line = line.strip()
if line.startswith('#'):
if chrom == 'chr1':
print(line, file=radfile)
print(line, file=radpassfile)
continue
else:
print(line, file=radfile)
line = line.split('\t')
if line[6] == 'PASS' and 'MT=GERM' not in line[7]:
print('\t'.join(line), file=radpassfile)
# parse the PASS radia vcf for multiple alt alleles
with open(radpassfile.name, 'r') as radpassfile, \
open('/'.join([work_dir, 'radia_parsed_filter_passing_calls.vcf']),
'w') as parsedradfile:
parse_radia_multi_alt(radpassfile, parsedradfile)
output_files = defaultdict()
for radia_file in [radfile.name, parsedradfile.name]:
output_files[os.path.basename(radia_file)] = job.fileStore.writeGlobalFile(radia_file)
return output_files
def run_radia(job, bams, univ_options, radia_options, chrom):
"""
This module will run radia on the RNA and DNA bams
ARGUMENTS
1. bams: Dict of bams and their indexes
bams
|- 'tumor_rna': <JSid>
|- 'tumor_rnai': <JSid>
|- 'tumor_dna': <JSid>
|- 'tumor_dnai': <JSid>
|- 'normal_dna': <JSid>
+- 'normal_dnai': <JSid>
2. univ_options: Dict of universal arguments used by almost all tools
univ_options
+- 'dockerhub': <dockerhub to use>
3. radia_options: Dict of parameters specific to radia
radia_options
|- 'dbsnp_vcf': <JSid for dnsnp vcf file>
+- 'genome': <JSid for genome fasta file>
4. chrom: String containing chromosome name with chr appended
RETURN VALUES
1. Dict of filtered radia output vcf and logfile (Nested return)
|- 'radia_filtered_CHROM.vcf': <JSid>
+- 'radia_filtered_CHROM_radia.log': <JSid>
"""
job.fileStore.logToMaster('Running radia on %s:%s' %(univ_options['patient'], chrom))
work_dir = job.fileStore.getLocalTempDir()
input_files = {
'rna.bam': bams['tumor_rna'],
'rna.bam.bai': bams['tumor_rnai'],
'tumor.bam': bams['tumor_dna'],
'tumor.bam.bai': bams['tumor_dnai'],
'normal.bam': bams['normal_dna'],
'normal.bam.bai': bams['normal_dnai'],
'genome.fasta': radia_options['genome_fasta'],
'genome.fasta.fai': radia_options['genome_fai']}
input_files = get_files_from_filestore(job, input_files, work_dir,
docker=True)
radia_output = ''.join([work_dir, '/radia_', chrom, '.vcf'])
radia_log = ''.join([work_dir, '/radia_', chrom, '_radia.log'])
parameters = [univ_options['patient'], # shortID
chrom,
'-n', input_files['normal.bam'],
'-t', input_files['tumor.bam'],
'-r', input_files['rna.bam'],
''.join(['--rnaTumorFasta=', input_files['genome.fasta']]),
'-f', input_files['genome.fasta'],
'-o', docker_path(radia_output),
'-i', 'hg19_M_rCRS',
'-m', input_files['genome.fasta'],
'-d', 'aarjunrao@soe.ucsc.edu',
'-q', 'Illumina',
'--disease', 'CANCER',
'-l', 'INFO',
'-g', docker_path(radia_log)]
docker_call(tool='radia', tool_parameters=parameters, work_dir=work_dir,
dockerhub=univ_options['dockerhub'])
output_files = defaultdict()
for radia_file in [radia_output, radia_log]:
output_files[os.path.basename(radia_file)] = \
job.fileStore.writeGlobalFile(radia_file)
filterradia = job.wrapJobFn(run_filter_radia, bams,
output_files[os.path.basename(radia_output)],
univ_options, radia_options, chrom, disk='60G', memory='6G')
job.addChild(filterradia)
return filterradia.rv()
def run_filter_radia(job, bams, radia_file, univ_options, radia_options, chrom):
"""
This module will run filterradia on the RNA and DNA bams.
ARGUMENTS
1. bams: REFER ARGUMENTS of run_radia()
2. univ_options: REFER ARGUMENTS of run_radia()
3. radia_file: <JSid of vcf generated by run_radia()>
3. radia_options: REFER ARGUMENTS of run_radia()
4. chrom: REFER ARGUMENTS of run_radia()
RETURN VALUES
1. Dict of filtered radia output vcf and logfile
|- 'radia_filtered_CHROM.vcf': <JSid>
+- 'radia_filtered_CHROM_radia.log': <JSid>
"""
job.fileStore.logToMaster('Running filter-radia on %s:%s' % (univ_options['patient'], chrom))
work_dir = job.fileStore.getLocalTempDir()
input_files = {
'rna.bam': bams['tumor_rna'],
'rna.bam.bai': bams['tumor_rnai'],
'tumor.bam': bams['tumor_dna'],
'tumor.bam.bai': bams['tumor_dnai'],
'normal.bam': bams['normal_dna'],
'normal.bam.bai': bams['normal_dnai'],
'radia.vcf': radia_file,
'genome.fasta': radia_options['genome_fasta'],
'genome.fasta.fai': radia_options['genome_fai']
}
input_files = get_files_from_filestore(job, input_files, work_dir,
docker=True)
filterradia_output = ''.join(['radia_filtered_', chrom, '.vcf'])
filterradia_log = ''.join([work_dir, '/radia_filtered_', chrom, '_radia.log'
])
parameters = [univ_options['patient'], # shortID
chrom.lstrip('chr'),
input_files['radia.vcf'],
'/data',
'/home/radia/scripts',
'-b', '/home/radia/data/hg19/blacklists/1000Genomes/phase1/',
'-d', '/home/radia/data/hg19/snp135',
'-r', '/home/radia/data/hg19/retroGenes/',
'-p', '/home/radia/data/hg19/pseudoGenes/',
'-c', '/home/radia/data/hg19/cosmic/',
'-t', '/home/radia/data/hg19/gaf/2_1',
'--noSnpEff',
'--rnaGeneBlckFile', '/home/radia/data/rnaGeneBlacklist.tab',
'--rnaGeneFamilyBlckFile',
'/home/radia/data/rnaGeneFamilyBlacklist.tab',
'-f', input_files['genome.fasta'],
'--log=INFO',
'-g', docker_path(filterradia_log)]
docker_call(tool='filterradia', tool_parameters=parameters,
work_dir=work_dir, dockerhub=univ_options['dockerhub'])
output_files = defaultdict()
output_files[filterradia_output] = \
job.fileStore.writeGlobalFile(''.join([work_dir, '/',
univ_options['patient'], '_',
chrom, '.vcf']))
output_files[os.path.basename(filterradia_log)] = \
job.fileStore.writeGlobalFile(filterradia_log)
return output_files
def spawn_mutect(job, tumor_bam, normal_bam, univ_options, mutect_options):
"""
This module will spawn a mutect job for each chromosome on the DNA bams.
ARGUMENTS
1. tumor_bam: Dict of input tumor WGS/WSQ bam + bai
tumor_bam
|- 'tumor_fix_pg_sorted.bam': <JSid>
+- 'tumor_fix_pg_sorted.bam.bai': <JSid>
2. normal_bam: Dict of input normal WGS/WSQ bam + bai
normal_bam
|- 'normal_fix_pg_sorted.bam': <JSid>
+- 'normal_fix_pg_sorted.bam.bai': <JSid>
3. univ_options: Dict of universal arguments used by almost all tools
univ_options
+- 'dockerhub': <dockerhub to use>
4. mutect_options: Dict of parameters specific to mutect
mutect_options
|- 'dbsnp_vcf': <JSid for dnsnp vcf file>
|- 'dbsnp_idx': <JSid for dnsnp vcf index file>
|- 'cosmic_vcf': <JSid for cosmic vcf file>
|- 'cosmic_idx': <JSid for cosmic vcf index file>
+- 'genome_fasta': <JSid for genome fasta file>
RETURN VALUES
1. perchrom_mutect: Dict of results of mutect per chromosome
perchrom_mutect
|- 'chr1'
| +- 'mutect_chr1.vcf': <JSid>
| +- 'mutect_chr1.out': <JSid>
|- 'chr2'
| |- 'mutect_chr2.vcf': <JSid>
| +- 'mutect_chr2.out': <JSid>
etc...
This module corresponds to node 11 on the tree
"""
job.fileStore.logToMaster('Running spawn_mutect on %s' % univ_options['patient'])
# Make a dict object to hold the return values for each of the chromosome
# jobs. Then run mutect on each chromosome.
chromosomes = [''.join(['chr', str(x)]) for x in list(range(1, 23)) + ['X', 'Y']]
perchrom_mutect = defaultdict()
for chrom in chromosomes:
perchrom_mutect[chrom] = job.addChildJobFn(run_mutect, tumor_bam, normal_bam, univ_options,
mutect_options, chrom, disk='60G',
memory='6G').rv()
return perchrom_mutect
def merge_mutect(job, perchrom_rvs):
"""
This module will merge the per-chromosome mutect files created by spawn_mutect into a genome
vcf. It will make 2 vcfs, one for PASSing non-germline calls, and one for all calls.
ARGUMENTS
1. perchrom_rvs: REFER RETURN VALUE of spawn_mutect()
RETURN VALUES
1. output_files: <JSid for mutect_passing_calls.vcf>
This module corresponds to node 11 on the tree
"""
job.fileStore.logToMaster('Running merge_mutect')
work_dir = job.fileStore.getLocalTempDir()
# We need to squash the input dict of dicts to a single dict such that it can be passed to
# get_files_from_filestore
input_files = {filename: jsid for perchrom_files in list(perchrom_rvs.values())
for filename, jsid in list(perchrom_files.items())}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=False)
chromosomes = [''.join(['chr', str(x)]) for x in list(range(1, 23)) + ['X', 'Y']]
with open('/'.join([work_dir, 'mutect_calls.vcf']), 'w') as mutvcf, \
open('/'.join([work_dir, 'mutect_calls.out']), 'w') as mutout, \
open('/'.join([work_dir, 'mutect_passing_calls.vcf']), 'w') as mutpassvcf:
out_header_not_printed = True
for chrom in chromosomes:
with open(input_files[''.join(['mutect_', chrom, '.vcf'])], 'r') as mutfile:
for line in mutfile: