forked from edawson/bam-matcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbam-matcher.py
executable file
·1705 lines (1496 loc) · 63 KB
/
bam-matcher.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
'''
Created on 09/12/2014
@author: Paul Wang ([email protected])
This is the pretty-formatted version for general release.
Still need to:
- improve confliction-resolution, error-checking, etc
- have better output reporting and more report modes (console-only, and HTML output)
- need to deal with space in file paths ??? (not sure if this is resolved now)
- add batch mode-friendly stuff, e.g. simpler TSV output, cached genotype data
'''
from argparse import ArgumentParser
import os
import subprocess
import sys
import vcf
import random
import string
import configparser
import shutil
from Cheetah.Template import Template
from hashlib import md5
from fisher import pvalue
from bammatcher_methods import *
#============================================================================
def handle_args():
parser = ArgumentParser(description="Compare two BAM files to see if \
they are from the same samples, using frequently occuring SNPs \
reported in the 1000Genome database")
# these are always required
parser_grp1 = parser.add_argument_group("REQUIRED")
parser_grp1.add_argument("--bam1", "-B1", required=True,
help="First BAM file")
parser_grp1.add_argument("--bam2", "-B2", required=True,
help="Second BAM file")
parser_grp1.add_argument("--cram", "-C", required=False, action="store_true",
help="Use CRAM format instead of BAM. Default = False")
# if not specified, will always look into the same location
parser_grp2 = parser.add_argument_group("CONFIGURATION")
parser_grp2.add_argument("--config", "-c", required=False,
help="Specify configuration file (default = \
/dir/where/script/is/located/bam-matcher.conf)")
parser_grp2.add_argument("--generate-config", "-G", required=False,
help="Specify where to generate configuration \
file template")
# Output-related stuff cannot be specified by configuration file
parser_grp3 = parser.add_argument_group("OUTPUT REPORT")
parser_grp3.add_argument("--output", "-o", required=False,
help="Specify output report path (default = \
/current/dir/bam_matcher.SUBFIX)")
parser_grp3.add_argument("--short-output", "-so", required=False,
default = False, action="store_true",
help="Short output mode (tab-separated).")
parser_grp3.add_argument("--html", "-H", required=False,
action="store_true", help="Enable HTML output. HTML file name = report + '.html'")
parser_grp3.add_argument("--no-report", "-n", required=False,
action="store_true", help="Don't write output to file. Results output to command line only.")
parser_grp3.add_argument("--scratch-dir", "-s", required=False,
help="Scratch directory for temporary files. If not specified, the report output directory will be used (default = /tmp/[random_string])")
# Variants VCF file
parser_grp4 = parser.add_argument_group("VARIANTS")
parser_grp4.add_argument("--vcf", "-V", required=False,
help="VCF file containing SNPs to check (default can be specified in config file instead)")
# caller settings - setting these will override config
parser_grp5 = parser.add_argument_group("CALLERS AND SETTINGS (will override config values)")
parser_grp5.add_argument("--caller", "-CL", required=False,
default="none",
choices=('gatk3', 'gatk4', 'freebayes', 'varscan'),
help="Specify which caller to use (default = 'gatk4')")
parser_grp5.add_argument("--dp-threshold", "-DP", required=False,
type=int, help="Minimum required depth for comparing variants")
parser_grp5.add_argument("--number_of_snps", "-N", required=False,
type=int, help="Number of SNPs to compare.")
parser_grp5.add_argument("--fastfreebayes", "-FF", required=False,
action="store_true", help="Use --targets option for Freebayes.")
parser_grp5.add_argument("--gatk-mem-gb" , "-GM", required=False,
type=int, help="Specify Java heap size for GATK (GB, int)")
parser_grp5.add_argument("--gatk-nt" , "-GT", required=False,
type=int, help="Specify number of threads for GATK UnifiedGenotyper (-nt option)")
parser_grp5.add_argument("--varscan-mem-gb", "-VM", required=False,
type=int, help="Specify Java heap size for VarScan2 (GB, int)")
# Genome references
parser_grp6 = parser.add_argument_group("REFERENCES")
parser_grp6.add_argument("--reference", "-R", required=False,
help="Default reference fasta file. Needs to be \
indexed with samtools faidx. Overrides config settings.")
parser_grp6.add_argument("--ref-alternate", "-R2", required=False,
help="Alternate reference fasta file. Needs to be \
indexed with samtools faidx. Overrides config settings.")
parser_grp6.add_argument("--chromosome-map", "-M", required=False,
help="Required when using alternate reference. \
Run BAM-matcher with --about-alternate-ref for more details.")
parser_grp6.add_argument("--about-alternate-ref", "-A", required=False,
help="Print information about using --alternate-ref and --chromosome-map")
# for batch operations
parser_grp7 = parser.add_argument_group("BATCH OPERATIONS")
parser_grp7.add_argument("--do-not-cache", "-NC", required=False,
default=False, action="store_true",
help="Do not keep variant-calling output for future comparison. By default (False) data is written to /bam/filepath/without/dotbam.GT_compare_data")
parser_grp7.add_argument("--recalculate", "-RC", required=False,
default=False, action="store_true",
help="Don't use cached variant calling data, redo variant-calling. Will overwrite cached data unless told not to (-NC)")
parser_grp7.add_argument("--cache-dir", "-CD", required=False,
help="Specify directory for cached data. Overrides configuration")
# optional, not in config
parser.add_argument("--debug", "-d", required=False, action="store_true",
help="Debug mode. Temporary files are not removed")
parser.add_argument("--verbose", "-v", required=False, action="store_true",
help="Verbose reporting. Default = False")
return parser.parse_args()
#===============================================================================
# Parsing configuration file and command line options
#-------------------------------------------------------------------------------
# Before calling handle_args(), need to check if --generate-config was called
GENERATE_CONFIG_SYMS = ["--generate-config", "--generate_config", "-G"]
ALTERNATE_REF_SYMS = ["--about-alternate-ref", "--about_alternate_ref", "-A"]
for idx, arg in enumerate(sys.argv):
# generate config template
if arg in GENERATE_CONFIG_SYMS:
try:
config_template_output = os.path.abspath(sys.argv[idx+1])
except:
config_template_output = os.path.abspath("bam-matcher.conf.template")
print ("""
====================================
Generating configuration file template
====================================
Config template will be written to %s
""" % config_template_output)
# make sure that it doesn't overwrite anything!
if os.path.isfile(config_template_output):
print ("%s\nThe specified path ('%s') for config template exists already." % (FILE_ERROR, config_template_output))
print ("Write to another file.")
sys.exit(1)
fout = open(config_template_output, "w")
fout.write(CONFIG_TEMPLATE_STR)
fout.close()
exit()
# print information about alternate genome reference
if arg in ALTERNATE_REF_SYMS:
print (ABOUT_ALTERNATE_REF_MSG)
exit()
# okay to parse the arguments now
args = handle_args()
#-------------------------------------------------------------------------------
# Some random-related stuff, this is for temp files
random.seed()
random_str = ""
for _ in range(12):
random_str += random.choice(string.ascii_uppercase + string.digits)
temp_files = []
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
#-------------------------------------------------------------------------------
# Read in configuration file
config_file = ""
if args.config == None:
config_file = os.path.join(SCRIPT_DIR, "bam-matcher.conf")
else:
config_file = os.path.abspath(os.path.expanduser(args.config))
# Test if the config file exists
if check_file_read(config_file, "config", CONFIG_ERROR) == False: exit(1)
# Load config and check if all necessary bits are available
config = configparser.ConfigParser()
try:
config.read(config_file)
except ConfigParser.Error as e:
print ("%s\nUnspecified configuration file error. Please check configuration file.\n\nPython error msg:\n%s" % (CONFIG_ERROR, e))
exit(1)
# are all the sections there?
config_sections = config.sections()
REQUIRED_CONFIG_SECTIONS = ["GenomeReference", "VariantCallerParameters",
"ScriptOptions", "VariantCallers", "Miscellaneous",
"BatchOperations"]
for sect in REQUIRED_CONFIG_SECTIONS:
if sect not in config_sections:
print ("""%s
Missing required section in config file: %s)
""" % (CONFIG_ERROR, sect))
exit(1)
#-------------------------------------------------------------------------------
# setting variables using the config file
CONFIG_CALLER = fetch_config_value(config, "VariantCallers", "caller")
GATK3 = fetch_config_value(config, "VariantCallers", "gatk3")
GATK4 = fetch_config_value(config, "VariantCallers", "gatk4")
FREEBAYES = fetch_config_value(config, "VariantCallers", "freebayes")
SAMTOOLS = fetch_config_value(config, "VariantCallers", "samtools")
VARSCAN = fetch_config_value(config, "VariantCallers", "varscan")
JAVA = fetch_config_value(config, "VariantCallers", "java")
DP_THRESH = fetch_config_value(config, "ScriptOptions", "DP_threshold")
NUMBER_OF_SNPS = fetch_config_value(config, "ScriptOptions", "number_of_SNPs")
FAST_FREEBAYES = fetch_config_value(config, "ScriptOptions", "fast_freebayes")
VCF_FILE = fetch_config_value(config, "ScriptOptions", "VCF_file")
REFERENCE = fetch_config_value(config, "GenomeReference", "REFERENCE")
REF_ALTERNATE = fetch_config_value(config, "GenomeReference", "REF_ALTERNATE")
CHROM_MAP = fetch_config_value(config, "GenomeReference", "CHROM_MAP")
GATK_MEM = fetch_config_value(config, "VariantCallerParameters", "GATK_MEM")
GATK_NT = fetch_config_value(config, "VariantCallerParameters", "GATK_nt")
VARSCAN_MEM = fetch_config_value(config, "VariantCallerParameters", "VARSCAN_MEM")
CACHE_DIR = fetch_config_value(config, "BatchOperations", "CACHE_DIR")
BATCH_RECALCULATE = False
BATCH_USE_CACHED = True
BATCH_WRITE_CACHE = True
# don't write anything to standard output if not verbose
STDERR_ = open("/dev/null", "w")
if args.verbose:
STDERR_ = None
#-------------------------------------------------------------------------------
# Input and output files
if args.verbose:
print ("""
================================================================================
CHECKING INPUT AND OUTPUT
================================================================================
""")
BAM1 = os.path.abspath(os.path.expanduser(args.bam1))
BAM2 = os.path.abspath(os.path.expanduser(args.bam2))
FORMAT = "CRAM" if args.cram is True else "BAM"
sINDEX = "crai" if args.cram is True else "bai"
sFORMAT = FORMAT.lower()
# check input bams are readable and indexed
for bam_file in [BAM1, BAM2]:
if check_file_read(bam_file, FORMAT, FILE_ERROR) == False: exit(1)
# check bam files are indexed:
bam_index2 = bam_file.rstrip("." + sFORMAT) + "." + sINDEX
bam_index1 = bam_file + "." + sINDEX
if (os.access(bam_index1, os.R_OK) == False and
os.access(bam_index2, os.R_OK) == False):
print ("%s\nInput %s file (%s) is either missing index or the index \
file is not readable." % (FILE_ERROR, FORMAT, bam_file))
exit(1)
# ----------------------------
# resolving output report path
REPORT_PATH = ""
current_dir = os.path.abspath("./")
if args.output == None:
REPORT_PATH = os.path.join(current_dir, "bam_matcher_report")
bam1_name = os.path.basename(BAM1).rstrip("." + sFORMAT).replace(".", "_")
bam2_name = os.path.basename(BAM2).rstrip("." + sFORMAT).replace(".", "_")
REPORT_PATH = REPORT_PATH + ".%s_%s_%s" % (bam1_name, bam2_name, random_str)
else:
REPORT_PATH = os.path.abspath(os.path.expanduser(args.output))
if args.no_report:
REPORT_PATH = "/dev/null"
args.html = False
# ----------------------------
# check output directory is writable
REPORT_DIR = os.path.dirname(REPORT_PATH)
if REPORT_PATH != "/dev/null":
if not check_file_write(REPORT_DIR, "output report directory", FILE_ERROR): exit(1)
# ----------------------------
# HTML path
html_path = ""
if args.html:
html_path = REPORT_PATH + ".html"
# ----------------------------
# scratch dir
SCRATCH_DIR = "/tmp/%s" % random_str
if args.scratch_dir == None:
if args.verbose:
print ("Making scratch directory: %s" % SCRATCH_DIR)
os.mkdir(SCRATCH_DIR)
else:
SCRATCH_DIR = args.scratch_dir
# if specified scratch exists, check it's writeable
if os.path.isdir(SCRATCH_DIR):
if check_file_write(SCRATCH_DIR, "scratch directory", FILE_ERROR) == False:
exit(1)
# if not, make it
else:
if args.verbose:
print ("Creating scratch directory: %s" % SCRATCH_DIR)
try:
os.mkdir(SCRATCH_DIR)
except OSError as e:
print ("""%s
Unable to create specified scratch directory: %s
Python error: %s
""" % (FILE_ERROR, SCRATCH_DIR, e))
except Exception as e:
print ("""%s
Unknown error while trying to create scratch directory (%s)
Python error message: %s
""" % (FILE_ERROR, SCRATCH_DIR, e))
if args.verbose:
print ("""
Input BAM files:
BAM1: %s
BAM2: %s
Output and scratch:
scratch dir: %s
Output report: %s
Input and output seem okay
""" % (BAM1, BAM2, SCRATCH_DIR, REPORT_PATH))
#===============================================================================
# Checking and validating settings and parameters
if args.verbose:
print ("""
================================================================================
CHECKING SETTINGS AND PARAMETERS
================================================================================
""")
#-------------------------------------------
# which caller to use
CALLER = ""
# if set in config
if CONFIG_CALLER != "":
CALLER = CONFIG_CALLER
# but override with arguments
if args.caller != "none": CALLER = args.caller
# if not set in config, use argument
else:
CALLER = args.caller
# if not set in argument, default to Freebayes
if CALLER == "none":
CALLER = "freebayes"
print ("""%s
No default caller was specified in the configuration file nor at runtime.
Will default to Freebayes.
""")
elif CALLER not in ["gatk3", "gatk4", "freebayes", "varscan"]:
print ("""%s
Incorrect caller specified.
The only values accepted for the caller parameter are: 'gatk3', 'gatk4', 'freebayes', and 'varscan'
""" % (CONFIG_ERROR))
exit(1)
#-------------------------------------------
# Variants file
# is it overridden by args?
if args.vcf: VCF_FILE = os.path.abspath(os.path.expanduser(args.vcf))
# is it specified?
if VCF_FILE == "":
print ("""%s
No variants file (VCF) has been specified.
Use --vcf/-V at command line or VCF_FILE in the configuration file.
""" % CONFIG_ERROR)
exit(1)
# is it readable?
VCF_FILE = os.path.abspath(os.path.expanduser(VCF_FILE))
if check_file_read(VCF_FILE, "variants VCF", CONFIG_ERROR) == False: exit(1)
#-------------------------------------------
# DP threshold
# get from command line
if args.dp_threshold != None:
DP_THRESH = args.dp_threshold
# get from config file
else:
if DP_THRESH == "":
print ("""%s
DP_threshold value was not specified in the config file or arguments.
Default value (15) will be used instead.
Setting DP_threshold = 15
""" % WARNING_MSG)
DP_THRESH = 15
else:
try:
DP_THRESH = int(DP_THRESH)
except (ValueError) as e:
print ("""%s
DP_threshold value ('%s') in config file is not a valid integer.
""" % (CONFIG_ERROR, DP_THRESH))
exit(1)
#-------------------------------------------
# Number of SNPs
# get from command line
if args.number_of_snps != None:
NUMBER_OF_SNPS = args.number_of_snps
# get from config file
else:
if NUMBER_OF_SNPS == "":
NUMBER_OF_SNPS = 0
else:
try:
NUMBER_OF_SNPS = int(NUMBER_OF_SNPS)
except (ValueError) as e:
print ("""%s
number_of_SNPs value ('%s') in config file is not a valid integer.
""" % (CONFIG_ERROR, NUMBER_OF_SNPS))
sys.exit(1)
if NUMBER_OF_SNPS <= 200 and NUMBER_OF_SNPS > 0:
print ("""%s
Using fewer than 200 SNPs is not recommended, may not be sufficient to
correctly discriminate between samples.
""" % WARNING_MSG)
#-------------------------------------------
# Fast Freebayes
# only check if actually using Freebayes for variant calling
if CALLER == "freebayes":
# get from command line
if args.fastfreebayes:
FAST_FREEBAYES = args.fastfreebayes
# get from config file
else:
if FAST_FREEBAYES == "":
print ("""%s
fast_freebayes was not set in the configuration file.
Default value (False) will be used instead.
Setting fast_freebayes = False
""" % WARNING_MSG)
FAST_FREEBAYES = False
else:
if FAST_FREEBAYES in ["False", "false", "F", "FALSE"]:
FAST_FREEBAYES = False
elif FAST_FREEBAYES in ["True", "true", "T", "TRUE"]:
FAST_FREEBAYES = True
else:
print ("""%s
Invalid value ('%s') was specified for fast_freebayes in the configuration file.
Use 'False' or 'True'""" % (CONFIG_ERROR, FAST_FREEBAYES))
sys.exit(1)
#-------------------------------------------
# GATK3 parameters
if CALLER == "gatk3":
# GATK_MEM
if GATK_MEM == "":
print ("""%s
GATK_MEM was not specified in the configuration file.
Default value (4G) will be used instead.
Setting GATK_MEM = 4G
""" % WARNING_MSG)
GATK_MEM = 4
else:
try:
GATK_MEM = int(GATK_MEM)
except (ValueError) as e:
print ("""%s
GATK_MEM value ('%s') in the config file is not a valid integer.
""" % (CONFIG_ERROR, GATK_MEM))
sys.exit(1)
# GATK_nt
if GATK_NT == "":
print (""" %s GATK_nt was not specified in the configuration file.
Default value (1) will be used instead.
Setting GATK_nt = 1
""" % WARNING_MSG)
GATK_NT = 1
else:
try:
GATK_NT = int(GATK_NT)
except (ValueError) as e:
print ("""%s
GATK_nt value ('%s') in the config file is not a valid integer.
""" % (CONFIG_ERROR, GATK_NT))
sys.exit(1)
#-------------------------------------------
# VarScan parameters
if CALLER == "varscan":
# get from config file
if VARSCAN_MEM == "":
print ("""
VARSCAN_MEM was not specified in the configuration file.
Default value (4GB) will be used instead.
Setting VARSCAN_MEM = 4GB
""" % WARNING_MSG)
VARSCAN_MEM = 4
else:
try:
VARSCAN_MEM = int(VARSCAN_MEM)
except (ValueError) as e:
print ("""%s
VARSCAN_MEM value ('%s') in the config file is not a valid integer.
""" % (CONFIG_ERROR, VARSCAN_MEM))
exit(1)
#===============================================================================
# New reference matching
bam1_ref = ""
bam2_ref = ""
# No references are specified anywhere
if REFERENCE == "" and args.reference == None:
print ("""%s
No genome reference has been specified anywhere.
Need to do this in either the configuration file or at run time (--reference/-R).
ALTERNATE_REF (in config) or --alternate_ref/-A should only be used if there is
already a default genome reference speficied.
""" % CONFIG_ERROR)
exit(1)
# overriding config REFERENCE
if args.reference != None:
REFERENCE = os.path.abspath(os.path.expanduser(args.reference))
print ("""%s
--reference/-R argument overrides config setting (REFERENCE).
Default reference = %s
""" % (WARNING_MSG, REFERENCE))
# overriding config REF_ALTERNATE
if args.ref_alternate != None:
REF_ALTERNATE = os.path.abspath(os.path.expanduser(args.ref_alternate))
print ("""%s
--ref-alternate/-R2 argument overrides config setting (REF_ALTERNATE).
Alternate reference = %s
""" % (WARNING_MSG, REF_ALTERNATE))
# overriding config CHROM_MAP
if args.chromosome_map != None:
CHROM_MAP = os.path.abspath(os.path.expanduser(args.chromosome_map))
print ("""%s
--chromosome-map/-M argument overrides config setting (CHROM_MAP).
Chromosome map = %s
""" % (WARNING_MSG, CHROM_MAP))
# check that if ref_alternate is used, then chromosome_map is also supplied
if REF_ALTERNATE:
if not CHROM_MAP:
print ("""%s
When using an alternate genome reference (--ref-alternate), chromosome map
(--chromosome-map/-M or CHROM_MAP in config) must also be supplied.
For more details, run BAM-matcher with --about-alternate-ref/-A.
""" % (CONFIG_ERROR))
exit(1)
# ---------------------------------------------------------
using_default_reference = True
using_chrom_map = False
# When only 1 reference is available
if REF_ALTERNATE == "":
# just use REFERENCE
bam1_ref = REFERENCE
bam2_ref = REFERENCE
# check REFERENCE
if check_file_read(REFERENCE, "default reference", FILE_ERROR) == False: exit(1)
if not check_fasta_index(REFERENCE): exit(1)
# When need to match BAM to correct reference file
else:
# get BAM chroms
bam1_chroms = get_chrom_names_from_BAM(BAM1)
bam2_chroms = get_chrom_names_from_BAM(BAM2)
# expect to have REFERENCE and ALTERNATE_REF
# check ref files
if not check_file_read(REFERENCE, "default genome reference FASTA", FILE_ERROR): exit(1)
if not check_file_read(REF_ALTERNATE, "alternate genome reference FASTA", FILE_ERROR): exit(1)
if not check_fasta_index(REFERENCE): exit(1)
if not check_fasta_index(REF_ALTERNATE) : exit(1)
# get ref chroms
REF_CHROMS = get_chrom_names_from_REF(REFERENCE)
ALT_CHROMS = get_chrom_names_from_REF(REF_ALTERNATE)
# check chromsome_map
if not check_file_read(CHROM_MAP, "chromosome map", FILE_ERROR): exit(1)
# compare chromosomes
MAP_REF_CHROMS, MAP_ALT_CHROMS, MAP_DEF2ALT, MAP_ALT2DEF = get_chrom_data_from_map(CHROM_MAP)
n_chroms_expected = len(MAP_REF_CHROMS)
# expect all REF_CHROMS to be in ref_chroms
ref_chroms_diff = set(MAP_REF_CHROMS).difference(set(REF_CHROMS))
alt_chroms_diff = set(MAP_ALT_CHROMS).difference(set(ALT_CHROMS))
chrom_diffs = [ref_chroms_diff, alt_chroms_diff]
for rid, reftype in enumerate(["default", "alternate"]):
chrdiff = chrom_diffs[rid]
if len(chrdiff) > 0: # - n_chroms_expected < 0:
print ("""%s
Number of matching chromosomes in the %s reference genome (%d) is fewer than expected from the chromosome map (%d).\n
Missing chromosome: %s\n
Check that the correct genome reference files and chromosome map are used.
""" % (CONFIG_ERROR, reftype, n_chroms_expected-len(chrdiff), n_chroms_expected, ", ".join(chrdiff)))
exit(1)
if args.verbose:
print ("Matching BAM files and genome references")
bam1_REF_diff = set(MAP_REF_CHROMS).difference(set(bam1_chroms))
bam2_REF_diff = set(MAP_REF_CHROMS).difference(set(bam2_chroms))
bam1_ALT_diff = set(MAP_ALT_CHROMS).difference(set(bam1_chroms))
bam2_ALT_diff = set(MAP_ALT_CHROMS).difference(set(bam2_chroms))
if len(bam1_REF_diff) == 0:
bam1_ref = REFERENCE
if args.verbose:
print ("BAM1 (%s) is matched to default genome reference (%s)" % (BAM1, REFERENCE))
elif len(bam1_ALT_diff) == 0:
bam1_ref = REF_ALTERNATE
if args.verbose:
print ("BAM1 (%s) is matched to alternate genome reference (%s)" % (BAM2, REF_ALTERNATE))
# allow some missing chroms
elif len(bam1_ALT_diff) < n_chroms_expected/2 or len(bam1_ALT_diff) < n_chroms_expected/2:
if len(bam1_ALT_diff) < len(bam1_REF_diff):
bam1_ref = REF_ALTERNATE
else:
bam1_ref = REFERENCE
if args.verbose:
print ("""%s
BAM1 (%s) is missing:
- %d chromosomes against default reference (%s). Missing: %s
- %d chromosomes against alternate reference (%s). Missing: %s
BAM1 is more likely matched to: %s
""" % (CONFIG_ERROR, BAM1, len(bam1_REF_diff), REFERENCE, ", ".join(bam1_REF_diff),
len(bam1_ALT_diff), REF_ALTERNATE, ", ".join(bam1_ALT_diff), bam1_ref))
else:
print ("""%s
Cannot match BAM1 to a genome reference
BAM1 (%s) is missing:
- %d chromosomes against default reference (%s). Missing: %s
- %d chromosomes against alternate reference (%s). Missing: %s
""" % (WARNING_MSG, BAM1, len(bam1_REF_diff), REFERENCE, ", ".join(bam1_REF_diff),
len(bam1_ALT_diff), REF_ALTERNATE, ", ".join(bam1_ALT_diff)))
exit(1)
if len(bam2_REF_diff) == 0:
bam2_ref = REFERENCE
if args.verbose:
print ("BAM2 (%s) is matched to default genome reference (%s)" % (BAM1, REFERENCE))
elif len(bam2_ALT_diff) == 0:
bam2_ref = REF_ALTERNATE
if args.verbose:
print ("BAM2 (%s) is matched to alternate genome reference (%s)" % (BAM2, REF_ALTERNATE))
# allow some missing chroms
elif len(bam2_ALT_diff) < n_chroms_expected/2 or len(bam2_ALT_diff) < n_chroms_expected/2:
if len(bam2_ALT_diff) < len(bam2_REF_diff):
bam2_ref = REF_ALTERNATE
else:
bam2_ref = REFERENCE
if args.verbose:
print ("""%s
BAM2 (%s) is missing:
- %d chromosomes against default reference (%s). Missing: %s
- %d chromosomes against alternate reference (%s). Missing: %s
BAM2 is more likely matched to: %s
""" % (WARNING_MSG, BAM2, len(bam2_REF_diff), REFERENCE, ", ".join(bam2_REF_diff),
len(bam2_ALT_diff), REF_ALTERNATE, ", ".join(bam2_ALT_diff), bam2_ref))
else:
print ("""%s
Cannot match BAM2 to a genome reference
BAM2 (%s) is missing:
- %d chromosomes against default reference (%s). Missing: %s
- %d chromosomes against alternate reference (%s). Missing: %s
""" % (CONFIG_ERROR, BAM2, len(bam2_REF_diff), REFERENCE, ", ".join(bam2_REF_diff),
len(bam2_ALT_diff), REF_ALTERNATE, ", ".join(bam2_ALT_diff)))
exit(1)
# use chromosome map if either BAM1 or BAM2 are not using default REFERENCE
if bam1_ref != REFERENCE or bam2_ref != REFERENCE:
using_chrom_map = True
#===============================================================================
# Batch operations
# args.do_not_cache, args.recalculate
BATCH_WRITE_CACHE = True
BATCH_USE_CACHED = True
if CACHE_DIR != "":
CACHE_DIR = os.path.abspath(os.path.expanduser(CACHE_DIR))
if args.recalculate:
BATCH_USE_CACHED = False
if args.do_not_cache:
BATCH_WRITE_CACHE = False
if args.cache_dir != None:
CACHE_DIR = os.path.abspath(os.path.expanduser(args.cache_dir))
if BATCH_WRITE_CACHE:
if CACHE_DIR == "":
print ("""%s
No CACHE_DIR specified in configuration or at command line.
Cached operations requires this to work.
If you don't want the cache the data, use the --do-not-cache/-NC flag.
""" % CONFIG_ERROR)
sys.exit(1)
# check if CACHE_DIR exists, if not, create it
if not os.path.isdir(CACHE_DIR):
if args.verbose:
print ("\n\nSpecified cache directory %s does not exist. Will attempt to create it" % CACHE_DIR)
try:
os.mkdir(CACHE_DIR)
except OSError as e:
print ("""%s
Specified cache directory (%s) does not exist.
Attempt to create the directory failed.
You may not have permission to create this directory, or the parent directory also does not exist.
Python error:
%s\n
""" % (FILE_ERROR, CACHE_DIR, e))
exit(1)
# check if cache directory is write-able
try:
test_cache_file = os.path.join(CACHE_DIR, "cache_test")
test_cache = open( test_cache_file, "w" )
test_cache.write("")
test_cache.close()
os.remove(test_cache_file)
except (IOError) as e:
print ("""%s
Unable to write to specified cache directory ('%s')
You may not have permission to write to this directory.
Either specify another cache directory (--cache-dir/-CD), or use --do-not-cache/-NC.
Python error msg:
%s
""" % (CONFIG_ERROR, CACHE_DIR, e))
sys.exit(1)
# check if cache directory is readable
if os.access(CACHE_DIR, os.R_OK) == False:
print ("%s\n\nSpecified cache directory (%s) is not readable!\n\n\n\n" % (WARNING_MSG, CACHE_DIR))
#------------------------------------------
# Print config settings
if args.verbose:
print ("""\n\nCONFIG SETTINGS
VCF file: %s
DP_threshold: %d
number_of_SNPs: %d (if 0, all variants in VCF file will be used)
Caller: %s""" % (VCF_FILE, DP_THRESH, NUMBER_OF_SNPS, CALLER))
if CALLER == "freebayes":
print ("fast_freebayes: ", FAST_FREEBAYES)
print ("""
default genome reference: %s
alternate genome reference: %s
BAM1 matched to: %s
BAM2 matched to: %s""" % (REFERENCE, REF_ALTERNATE, bam1_ref, bam2_ref))
if using_chrom_map:
print ("""
using chromosome map: %r
chromosome map: %s
""" % (using_chrom_map, CHROM_MAP))
print ("""
cache directory: %s
use cached wherever possible: %r
write cache data for new samples: %r
""" % (CACHE_DIR, BATCH_USE_CACHED, BATCH_WRITE_CACHE))
#===============================================================================
# Finished configuration and arguments checking and loading
#===============================================================================
#===============================================================================
# Variant calling
#===============================================================================
if args.verbose:
print ("""
================================================================================
GENOTYPE CALLING
================================================================================
""")
#-------------------------------------------------------------------------------
# first look for cached data if using BATCH_USE_CACHED is True
# cached file is named as the md5sum of:
# - the BAM path
# - number of variants compared
# - depth
# - bam file timestamp
# - bam header
# - VCF file path (list of variants to check)
m1 = md5()
# bam1_path = os.path.abspath(BAM1)
bam1_mtime = str(os.path.getmtime(BAM1)).encode('utf-8')
m1.update(BAM1.encode('utf-8'))
m1.update(str(NUMBER_OF_SNPS).encode('utf-8'))
m1.update(str(DP_THRESH).encode('utf-8'))
m1.update(bam1_mtime)
m1.update(VCF_FILE.encode('utf-8'))
m1.update(bam1_ref.encode('utf-8'))
m1.update(REFERENCE.encode('utf-8'))
for line in get_bam_header(BAM1):
m1.update(line.encode('utf-8'))
m2 = md5()
# bam2_path = os.path.abspath(BAM2)
bam2_mtime = str(os.path.getmtime(BAM2)).encode('utf-8')
m2.update(BAM2.encode('utf-8'))
m2.update(str(NUMBER_OF_SNPS).encode('utf-8'))
m2.update(str(DP_THRESH).encode('utf-8'))
m2.update(bam2_mtime)
m2.update(VCF_FILE.encode('utf-8'))
m2.update(bam2_ref.encode('utf-8'))
m2.update(REFERENCE.encode('utf-8'))
for line in get_bam_header(BAM2):
m2.update(line.encode('utf-8'))
bam1_cache_path = os.path.join(CACHE_DIR, m1.hexdigest())
bam2_cache_path = os.path.join(CACHE_DIR, m2.hexdigest())
bam1_is_cached = os.access(bam1_cache_path, os.R_OK)
bam2_is_cached = os.access(bam2_cache_path, os.R_OK)
if BATCH_USE_CACHED == False:
bam1_is_cached = False
bam2_is_cached = False
if args.verbose:
print ("BAM1 is cached:", bam1_is_cached)
print ("BAM2 is cached:", bam2_is_cached)
# Only check callers if not using cached data
# Test caller binaries
if bam1_is_cached == False or bam2_is_cached==False:
if args.verbose:
print ("\n---------------\nChecking caller\n---------------")
if CALLER == "freebayes" and not JAVA:
print ("%s\nJava command was not specified.\nDo this in the configuration file" % CONFIG_ERROR)
sys.exit(1)
caller_check_log = os.path.join(SCRATCH_DIR, "caller_check.log")
if CALLER == "gatk3":
check_caller(CALLER, GATK3, JAVA, args.verbose, logfile=caller_check_log)
elif CALLER == "gatk4":
check_caller(CALLER, GATK4, JAVA, args.verbose, logfile=caller_check_log)
elif CALLER == "freebayes":
check_caller(CALLER, FREEBAYES, JAVA, args.verbose, logfile=caller_check_log)
elif CALLER == "varscan":
check_caller(CALLER, VARSCAN, JAVA, args.verbose, logfile=caller_check_log, SAMTL=SAMTOOLS)
if args.verbose:
print ("Caller settings seem okay.\n")
else:
if args.verbose:
print ("""
---------------
Checking caller
---------------
Using cached data for both BAM files, so don't need to test caller.
""")
#-------------------------------------------------------------------------------
# generating intervals file for variant calling - only required if not using cached data
# VCF_FILE, NUMBER_OF_SNPS
interval_files_list = []
if bam1_is_cached == False or bam2_is_cached == False:
if args.verbose:
print ("Creating intervals file")
bam1_itv = os.path.join(SCRATCH_DIR, "bam1.intervals")
bam2_itv = os.path.join(SCRATCH_DIR, "bam2.intervals")
temp_files.append(bam1_itv)
temp_files.append(bam2_itv)
# if using default reference (or alternate reference),
# assume that the VCF file is same as default
if using_default_reference:
# if using chrom_map, assume that at least one BAM is not mapped to REFERENCE
if using_chrom_map:
_, _, MAP_DEF2ALT, _ = get_chrom_data_from_map(CHROM_MAP)
if bam1_ref == REFERENCE:
convert_vcf_to_intervals(VCF_FILE, bam1_itv, 0, NUMBER_OF_SNPS, CALLER)
else:
convert_vcf_to_intervals(VCF_FILE, bam1_itv, 0, NUMBER_OF_SNPS, CALLER, cmap=MAP_DEF2ALT)
if bam2_ref == REFERENCE:
convert_vcf_to_intervals(VCF_FILE, bam2_itv, 0, NUMBER_OF_SNPS, CALLER)
else:
convert_vcf_to_intervals(VCF_FILE, bam2_itv, 0, NUMBER_OF_SNPS, CALLER, cmap=MAP_DEF2ALT)
# else, assume that both are mapped to REFERENCE
else:
convert_vcf_to_intervals(VCF_FILE, bam1_itv, 0, NUMBER_OF_SNPS, CALLER)
convert_vcf_to_intervals(VCF_FILE, bam2_itv, 0, NUMBER_OF_SNPS, CALLER)
interval_files_list = [bam1_itv, bam2_itv]
# check intervals files
# if they are empty, then something is wrong
for i in [0, 1]:
if os.path.getsize(interval_files_list[i]) == 0:
print ("""%s
No intervals were extracted from variants list.
Genotype calling have no targets and will either fail or generate an empty VCF file.
Check:
1. input VCF file (whose genomic position format should match the DEFAULT genome reference fasta),
2. default genome reference fasta
3. alternate genome reference fasta if it is being used
4. the chromosome map file if it is being used.
Input VCF file: %s
Default genome reference: %s
Alternate genome reference: %s
chromosome map: %s
""" % (CONFIG_ERROR, VCF_FILE, REFERENCE, REF_ALTERNATE, CHROM_MAP))
exit(1)
#-------------------------------------------------------------------------------
# Caller output files
if args.verbose:
print ("\n----------------\nCalling variants\n----------------")
vcf1 = os.path.join(SCRATCH_DIR, "bam1.vcf")
vcf2 = os.path.join(SCRATCH_DIR, "bam2.vcf")
# pileup files, for VarScan
pup1 = os.path.join(SCRATCH_DIR, "bam1.pileup")
pup2 = os.path.join(SCRATCH_DIR, "bam2.pileup")
# lists
bam_list = [BAM1, BAM2]
vcf_list = [vcf1, vcf2]
pup_list = [pup1, pup2]
ref_list = [bam1_ref, bam2_ref]
cached_list = [bam1_is_cached, bam2_is_cached]
cache_path_list = [bam1_cache_path, bam2_cache_path]
# add temp files
temp_files += [vcf1, vcf2]
temp_files.append(vcf1+".idx")
temp_files.append(vcf2+".idx")
temp_files += pup_list
# Variant calling is not done in a single step,
# even though this is possible for some callers, because:
# 1. If the sample names are the same, this causes problems for GATK3
# 2. They may have been mapped to different reference files
for i in [0,1]:
if args.verbose:
print ("\nGenotype calling for BAM %d\n--------------------------" % (i+1))
if BATCH_USE_CACHED:
if cached_list[i]:
if args.verbose:
print ("BAM %d has cached genotype data" % (i+1))
continue
in_bam = bam_list[i]
out_vcf = vcf_list[i]
ref = ref_list[i]
interval_file = interval_files_list[i]
if args.verbose:
print ("input bam: \t%s\noutput vcf:\t%s" % (in_bam, out_vcf))
# set up caller log file
caller_log_file = os.path.join(SCRATCH_DIR, "caller%d.log" % i)