-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
tb-profiler
677 lines (551 loc) · 36.2 KB
/
tb-profiler
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
#! /usr/bin/env python3
import sys
import pathogenprofiler as pp
from pathogenprofiler import TempFilePrefix, TempFolder
import pathogenprofiler.variant_calling as vc
import argparse
from rich_argparse import ArgumentDefaultsRichHelpFormatter
import json
import tbprofiler as tbp
import os
import csv
from uuid import uuid4
import glob
import atexit
import shutil
from joblib import Parallel, delayed
from tqdm import tqdm
import logging
from rich.logging import RichHandler
from copy import deepcopy
import importlib
import pkgutil
discovered_plugins = {
name: importlib.import_module(name)
for finder, name, ispkg
in pkgutil.iter_modules()
if name.startswith('tbprofiler_')
}
__softwarename__ = 'tbprofiler'
@atexit.register
def cleanup():
if "last_traceback" in vars(sys):
if args.files_prefix and not args.no_clean:
sys.stderr.write("Cleaning up after failed run\n")
for f in glob.glob(args.files_prefix+"*"):
os.remove(f)
import traceback
if "prefix" in vars(args):
outfile = "%s.errlog.txt" % args.prefix
elif "vcf" in vars(args):
outfile = "%s.errlog.txt" % args.vcf.split("/")[-1]
else:
outfile = "%s.errlog.txt" % uuid4()
if "conf" in vars(args) and args.conf:
del args.conf['json_db']
with open(outfile, "w") as O:
O.write("# tb-profiler error report\n\n")
O.write("* OS: %s\n" % sys.platform)
O.write("* Program version: %s\n" % tbp.__version__)
O.write("* Database version: %s\n" % args.conf.get("version","N/A") if "conf" in vars(args) and args.conf else "")
O.write("* Program call:\n")
O.write("```\n")
O.write("%s\n" % vars(args))
O.write("```\n")
O.write("## Traceback:\n")
O.write("```\n")
traceback.print_tb(sys.last_traceback,file=O)
O.write("```\n")
O.write("## Value:\n")
O.write("```\n")
O.write("%s" % sys.last_value)
O.write("```\n")
logging.error("""\n
################################# ERROR #######################################
This run has failed. Please check all arguments and make sure all input files
exist. If no solution is found, please open up an issue at
https://github.com/jodyphelan/TBProfiler/issues/new and paste or attach the
contents of the error log (%s)
###############################################################################
""" % (outfile))
def vcf_job(args: argparse.Namespace,sample_name: str):
# logging.info(f"\nExtracting variants and running pipeline for {sample_name}\n")
copy_of_args = deepcopy(args)
copy_of_args.prefix = sample_name
with TempFolder() as tmpfolder:
cmd = f"bcftools view -s {sample_name} -ac 1 {args.vcf} | bcftools +fixploidy -Oz -o {tmpfolder}/{args.vcf} && bcftools index {tmpfolder}/{args.vcf} " % vars(copy_of_args)
pp.run_cmd(cmd)
os.chdir(tmpfolder)
copy_of_args.files_prefix = os.path.abspath(f"{os.getcwd()}/{copy_of_args.prefix}")
main_profile(copy_of_args)
os.chdir('../')
def multisample_vcf_run(args):
vcf_obj = pp.Vcf(args.vcf)
jobs = []
for sample_name in vcf_obj.samples:
jobs.append((args,sample_name))
parallel = Parallel(n_jobs=args.threads, return_as='generator')
[r for r in tqdm(parallel(delayed(vcf_job)(cmd[0],cmd[1]) for cmd in jobs),total=len(jobs),desc="Running jobs")]
def create_output_directories(args,directories=["bam","vcf","results"]):
if pp.nofolder(args.dir):
os.mkdir(args.dir)
for d in directories:
if pp.nofolder(args.dir+"/"+d):
os.mkdir(args.dir+"/"+d)
def plugin_decorator(func):
def wrapper(args):
for plugin in tbp.ProfilePlugin.__subclasses__():
logging.debug(f"Running pre process for {plugin}")
plugin().pre_process(args)
func(args)
for plugin in tbp.ProfilePlugin.__subclasses__():
logging.debug(f"Running post process for {plugin}")
plugin().post_process(args)
return wrapper
@plugin_decorator
def main_profile(args):
pp.process_args(args)
create_output_directories(args)
if args.vcf:
nsamples = len(tbp.get_vcf_samples(args.vcf))
if nsamples>1:
return multisample_vcf_run(args)
tbp.process_tb_profiler_args(args)
variants_profile = pp.run_profiler(args)
notes = set()
if 'rules' in args.conf:
rules_applied = pp.apply_rules(args.conf['rules'], variants_profile, just_make_note=True if args.implement_rules==False else False)
for var in variants_profile:
for ann in var.annotation:
if 'note' in ann:
notes.add(ann['note'])
else:
rules_applied = []
logging.debug(rules_applied)
tbp.clean_up_duplicate_annotations(variants_profile)
# Convert variant objects to DrVariant if they cause resistance
for var in variants_profile:
var.convert_to_dr_element()
if args.call_lineage:
barcode_result = tbp.barcode2lineage(pp.run_barcoder(args))
if args.spoligotype:
spoligotype = tbp.spoligotype(args)
else:
spoligotype = None
if args.data_source in ('bam','fastq'):
qc = pp.run_bam_qc(args)
elif args.data_source=="fasta":
qc = pp.run_fasta_qc(args)
else:
qc = pp.run_vcf_qc(args)
result = tbp.create_resistance_result(
args = args,
notes=notes,
lineage=barcode_result,
spoligotype=spoligotype,
variants=variants_profile,
qc=qc,
)
if args.snp_dist:
tbp.run_snp_dists(args,result)
tbp.update_neighbour_snp_dist_output(args,result)
for plugin in tbp.ProfilePlugin.__subclasses__():
plugin().run(args)
### Create folders for results if they don't exist ###
if pp.nofolder(d:=args.dir+"/bam") and args.read1:
os.mkdir(d)
if pp.nofolder(d:=args.dir+"/vcf"):
os.mkdir(d)
if pp.nofolder(d:=args.dir+"/results"):
os.mkdir(d)
tbp.write_outputs(args,result)
# ### Move files to respective directories ###
if os.path.isfile("%s.nwk" % args.files_prefix):
shutil.copy("%s.nwk" % args.files_prefix,"%s/results/latest.nwk" % (args.dir))
result_files = {
"%s.targets.vcf.gz" % args.files_prefix: "%s/vcf/%s.targets.vcf.gz" % (args.dir,args.prefix),
"%s.vcf.gz" % args.files_prefix: "%s/vcf/%s.vcf.gz" % (args.dir,args.prefix),
"%s.bam" % args.files_prefix: "%s/bam/%s.bam" % (args.dir,args.prefix),
"%s.bam.bai" % args.files_prefix: "%s/bam/%s.bam.bai" % (args.dir,args.prefix),
"%s.nwk" % args.files_prefix: "%s/results/%s.nwk" % (args.dir,args.prefix),
}
if args.save_low_dp_mask:
result_files["%s.%s.mask.bed" % (args.files_prefix,args.prefix)] = "%s/results/%s.mask.bed" % (args.dir,args.prefix)
for file,target in result_files.items():
if os.path.isfile(file):
shutil.move(file,target)
if not args.no_clean:
pp.run_cmd("rm %s*" % args.files_prefix)
pp.logging.info("[green]Profiling finished sucessfully![/]",extra={"markup": True})
def main_update_tbdb(args):
if args.match_ref:
args.match_ref = os.path.abspath(args.match_ref)
if pp.nofolder("tbdb"):
pp.run_cmd(f"git clone {args.repo}")
os.chdir("tbdb")
pp.run_cmd(f'git checkout {args.branch}')
pp.run_cmd("git pull")
if args.commit:
pp.run_cmd(f"git checkout {args.commit}")
if args.prefix==None:
args.prefix = args.branch
extra_args = []
if os.path.isfile('rules.txt'):
extra_args.append("--rules rules.txt")
if args.match_ref:
extra_args.append("--match_ref %s" % os.path.abspath(args.match_ref))
extra_args = " ".join(extra_args)
with TempFilePrefix() as tmpfile:
pp.run_cmd(f"tb-profiler create_db --prefix {args.prefix} --csv mutations.csv --watchlist watchlist.csv {extra_args} --load")
os.chdir("../")
pp.logging.info("Sucessfully updated TBDB")
def main_create_db(args):
version_string = json.load(open('variables.json'))['tb-profiler-version']
tbp.check_db_version(version_string,tbp.__version__)
if args.no_overwrite:
dbs = pp.list_db(args.software_name)
names = [x['version']['name'] for x in dbs]
if args.prefix in names:
pp.warninglog("\nWarning: A database with this name already exists!\n")
sys.exit()
extra_files = {
"spoligotype_spacers": args.spoligotypes,
"spoligotype_annotations": args.spoligotype_annotations,
"bedmask": {"name":args.bedmask,"convert":1},
}
if args.barcode:
extra_files["barcode"] = args.barcode
if args.rules:
extra_files["rules"] = args.rules
with TempFilePrefix() as tmpfile:
args.csv = tbp.reformat_variant_csv_file(args.csv,f'{tmpfile}.variants.csv')
args.watchlist = tbp.reformat_variant_csv_file([args.watchlist],f'{tmpfile}.watchlist.csv')
pp.create_db(args,extra_files=extra_files)
def main_load_library(args):
variables_file = "%(prefix)s.variables.json" % vars(args)
source_dir = os.path.realpath(args.dir)
pp.load_db(variables_file,args.software_name,source_dir=source_dir)
def main_lineage(args):
create_output_directories(args,directories=["results"])
args.data_source = "bam"
barcode_result = tbp.barcode2lineage(pp.run_barcoder(args))
result = tbp.create_lineage_result(args,barcode_result)
json_output = args.dir+"/results/"+args.prefix+".lineage.json"
open(json_output,"w").write(result.model_dump_json(indent=4))
def main_spoligotype(args):
create_output_directories(args,directories=["results"])
if args.bam:
args.bam_file = args.bam
spoligotype = tbp.spoligotype(args)
json_output = args.dir+"/results/"+args.prefix+".spoligotype.json"
open(json_output,"w").write(spoligotype.model_dump_json(indent=4))
def main_collate(args):
tbp.collate_results(args)
def main_version(args):
sys.stdout.write("tb-profiler version %s\n" % tbp.__version__)
def main_reformat(args):
data = json.load(open(args.json))
result = tbp.ProfileResult(**data)
args.prefix = result.id
tbp.write_outputs(args,result,template_file=args.text_template)
def main_batch(args):
if args.args==None:
args.args=""
commands = []
for row in csv.DictReader(open(args.csv)):
line = f"tb-profiler profile -p {row['id']} --temp {args.temp} --dir {args.dir} --threads {args.threads_per_job}"
if "bam" in row:
line += f" -a {row['bam']}"
elif "read1" in row:
line += f" -1 {row['read1']}"
if "read2" in row:
line += f" -2 {row['read2']}"
elif "vcf" in row:
line += f" -v {row['vcf']}"
elif "fasta" in row:
line += f" -f {row['fasta']}"
cmd = line + " " + args.args
commands.append(cmd)
# run commands in parallel with joblib
parallel = Parallel(n_jobs=args.jobs, return_as='generator')
[r for r in tqdm(parallel(delayed(pp.run_cmd)(cmd) for cmd in commands),total=len(commands),desc="Running jobs")]
# tqdm(Parallel(n_jobs=args.jobs, return_as='generator')(delayed(pp.run_cmd)(cmd) for cmd in commands))
def main_list_db(args):
dbs = pp.list_db(args.software_name)
for db in dbs:
if 'version' in db:
d = dict(**db['version'], location=f"{sys.base_prefix}/share/{args.software_name}/{db['version']['name']}")
sys.stdout.write("%(name)s\t%(commit)s\t%(Author)s\t%(Date)s\t%(location)s\n" % d)
#### Argument Parsing ####
def int_2_or_more(arg):
try:
i = int(arg)
except ValueError:
raise argparse.ArgumentTypeError("Must be a of type Integer")
if i < 2 :
raise argparse.ArgumentTypeError("Argument must be < " + "2")
return i
variant_callers = [cls.__software__ for cls in vc.VariantCaller.__subclasses__()]
docx_plugins = [cls.__template_name__ for cls in tbp.docx.DocxResultTemplate.__subclasses__()]
parser = argparse.ArgumentParser(description='tb-profiler: a tool to predict drug resistance and infer lineages',formatter_class=ArgumentDefaultsRichHelpFormatter,add_help=False)
parser.add_argument('--version', action='version', version="tb-profiler version %s" % tbp.__version__)
parser.add_argument('--logging',type=str.upper,default="INFO",choices=["DEBUG","INFO","WARNING","ERROR","CRITICAL"],help='Logging level')
parser.add_argument('--debug',action='store_true',help=argparse.SUPPRESS)
subparsers = parser.add_subparsers(help="Task to perform")
# Profile #
parser_sub = subparsers.add_parser('profile', help='Run whole profiling pipeline', formatter_class=ArgumentDefaultsRichHelpFormatter)
input=parser_sub.add_argument_group("Input options")
group = input.add_mutually_exclusive_group(required=True)
group.add_argument('--read1','-1',help='First read file')
input.add_argument('--read2','-2',help='Second read file')
group.add_argument('--bam','-a',help='BAM file (make sure it has been generated using the H37Rv genome (GCA_000195955.2))')
group.add_argument('--fasta','-f',help='Fasta file')
group.add_argument('--vcf','-v',help='VCF file')
input.add_argument('--platform','-m',choices=["illumina","nanopore","pacbio"],default="illumina",help='NGS Platform used to generate data')
input.add_argument('--db',default='tbdb',help='Mutation panel name')
input.add_argument('--external_db','--external-db',type=str,help='Path to db files prefix (overrides --db parameter)')
output=parser_sub.add_argument_group("Output options")
output.add_argument('--prefix','-p',default="tbprofiler",help='Sample prefix for all results generated')
output.add_argument('--csv',action="store_true",help="Add CSV output")
output.add_argument('--txt',action="store_true",help="Add text output")
output.add_argument('--text_template','--text-template',type=str,help='Jinja2 formatted template for output')
output.add_argument('--docx',action="store_true",help="Add docx output")
output.add_argument('--docx_template','--docx-template',help="Supply custom template for --docx output")
output.add_argument('--docx_plugin','--docx-plugin',choices=docx_plugins,help="Use a plugin template for --docx output")
output.add_argument('--add_columns','--add-columns',default=None,type=str,help="Add additional columns found in the mutation database to the text and csv results")
output.add_argument('--add_mutation_metadata','--add-mutation-metadata',action="store_true",help=argparse.SUPPRESS)
output.add_argument('--dir','-d',default=".",help='Storage directory')
filtering=parser_sub.add_argument_group("Variant filtering options")
filtering.add_argument('--depth',default="0,10",type=str,help='Minimum depth hard and soft cutoff specified as comma separated values')
filtering.add_argument('--af',default="0,0.1",type=str,help='Minimum allele frequency hard and soft cutoff specified as comma separated values')
filtering.add_argument('--strand',default="0,3",type=str,help='Minimum read number per strand hard and soft cutoff specified as comma separated values')
filtering.add_argument('--sv_depth','--sv-depth',default="0,10",type=str,help='Structural variant minimum depth hard and soft cutoff specified as comma separated values')
filtering.add_argument('--sv_af','--sv-af',default="0.5,0.9",type=str,help='Structural variant minimum allele frequency hard cutoff specified as comma separated values')
filtering.add_argument('--sv_len','--sv-len',default="100000,50000",type=str,help='Structural variant maximum size hard and soft cutoff specified as comma separated values')
algorithm=parser_sub.add_argument_group("Algorithm options")
algorithm.add_argument('--mapper',default="bwa", choices=["bwa","minimap2","bowtie2","bwa-mem2"],help="Mapping tool to use. If you are using nanopore or pacbio data it will default to minimap2",type=str)
algorithm.add_argument('--caller',default="freebayes", choices=variant_callers,help="Variant calling tool to use.",type=str)
algorithm.add_argument('--calling_params','--calling-params',type=str,help='Override default parameters for variant calling')
for cls in vc.VariantCaller.__subclasses__():
if hasattr(cls,"__cli_params__"):
for a in cls.__cli_params__:
algorithm.add_argument(*a['args'],**a['kwargs'])
algorithm.add_argument('--kmer_counter','--kmer-counter',default='kmc',choices=["kmc","dsk"],type=str,help="Kmer counter")
algorithm.add_argument('--coverage_tool','--coverage-tool',default='samtools',choices=["samtools","bedtools"],type=str,help="Kmer counter")
algorithm.add_argument('--suspect',action="store_true",help="Use the suspect suite of tools to add ML predictions")
algorithm.add_argument('--spoligotype',action="store_true",help="Perform in-silico spoligotyping")
# algorithm.add_argument('--update_phylo','--update-phylo',action="store_true",help="Update phylogeny using usher (experimental feature)")
algorithm.add_argument('--call_whole_genome','--call-whole-genome',action="store_true",help="Call variant across the whole genome")
algorithm.add_argument('--snp_dist','--snp-dist',type=int,help="Store variant set and get all samples with snp distance less than this cutoff (experimental feature)")
algorithm.add_argument('--snp_diff_db','--snp-diff_db',type=str,help=argparse.SUPPRESS)
algorithm.add_argument('--snp_diff_no_store','--snp-diff-no-store',action='store_true',help=argparse.SUPPRESS)
algorithm.add_argument('--no_trim','--no-trim',action="store_true",help="Don't trim files using trimmomatic")
algorithm.add_argument('--no_coverage_qc','--no-coverage-qc',action="store_true",help="Don't collect flagstats")
algorithm.add_argument('--no_samclip','--no-samclip',action="store_true",help="Don't remove clipped reads from variant calling")
algorithm.add_argument('--no_delly','--no-delly',action="store_true",help="Don't run delly")
algorithm.add_argument('--no_lineage','--no-lineage',action="store_true",help=argparse.SUPPRESS)
algorithm.add_argument('--add_variant_annotations','--add-variant-annotations',action="store_true",help=argparse.SUPPRESS)
algorithm.add_argument('--threads','-t',default=1,help='Threads to use',type=int)
algorithm.add_argument('--ram',default=2,help='Maximum memory to use',type=int)
algorithm.add_argument('--implement_rules','--implement-rules',action="store_true",help='Use rules implemented in the resistance library (by default only a note will be made)')
plugins=parser_sub.add_argument_group("Plugin options")
for cls in tbp.ProfilePlugin.__subclasses__():
if hasattr(cls,"__cli_params__"):
for a in cls.__cli_params__:
plugins.add_argument(*a['args'],**a['kwargs'])
other=parser_sub.add_argument_group("Other options")
other.add_argument('--logging',type=str.upper,default="INFO",choices=["DEBUG","INFO","WARNING","ERROR","CRITICAL"],help='Logging level')
other.add_argument('--debug',action='store_true',help=argparse.SUPPRESS)
other.add_argument('--delly_vcf','--delly-vcf',help=argparse.SUPPRESS)
other.add_argument('--supplementary_bam','--supplementary-bam',help=argparse.SUPPRESS)
other.add_argument('--low_dp_mask','--low-dp-mask',help=argparse.SUPPRESS)
other.add_argument('--save_low_dp_mask','--save-low-dp-mask',action='store_true',help=argparse.SUPPRESS)
other.add_argument('--no_clean','--no-clean', action='store_true',help=argparse.SUPPRESS)
other.add_argument('--temp',help="Temp firectory to process all files",type=str,default=".")
other.add_argument('--version', action='version', version="tb-profiler version %s" % tbp.__version__)
parser_sub.set_defaults(func=main_profile)
parser_sub = subparsers.add_parser('lineage', help='Profile only lineage', formatter_class=ArgumentDefaultsRichHelpFormatter)
parser_sub.add_argument('--bam','-a',required=True, help='BAM file. Make sure it has been generated using the H37Rv genome (GCA_000195955.2)')
parser_sub.add_argument('--prefix','-p',default="tbprofiler",help='Sample prefix')
parser_sub.add_argument('--barcode_snps','--barcode-snps',help='Dump barcoding mutations to a file')
parser_sub.add_argument('--caller',default='freebayes',choices=["bcftools","freebayes","gatk"],type=str,help="Variant caller")
parser_sub.add_argument('--kmer_counter','--kmer-counter',default='kmc',choices=["kmc","dsk"],type=str,help="Kmer counter")
parser_sub.add_argument('--platform','-m',choices=["illumina","nanopore","pacbio"],default="illumina",help='NGS Platform used to generate data')
parser_sub.add_argument('--db',default='tbdb',help='Mutation panel name')
parser_sub.add_argument('--spoligotype',action="store_true",help="Perform in-silico spoligotyping")
parser_sub.add_argument('--external_db','--external-db',type=str,help='Path to db files prefix (overrides "--db" parameter)')
parser_sub.add_argument('--text_template','--text-template',type=str,help='Jinja2 formatted template for output')
parser_sub.add_argument('--threads','-t',default=1,help='Threads to use',type=int)
parser_sub.add_argument('--dir','-d',default=".",help='Storage directory')
parser_sub.add_argument('--no_clean','--no-clean', action='store_true',help=argparse.SUPPRESS)
parser_sub.add_argument('--temp',help="Temp firectory to process all files",type=str,default=".")
parser_sub.add_argument('--version', action='version', version="tb-profiler version %s" % tbp.__version__)
parser_sub.add_argument('--logging',type=str.upper,default="INFO",choices=["DEBUG","INFO","WARNING","ERROR","CRITICAL"],help='Logging level')
parser_sub.add_argument('--debug',action='store_true',help=argparse.SUPPRESS)
parser_sub.set_defaults(func=main_lineage)
parser_sub = subparsers.add_parser('spoligotype', help='Profile spoligotype', formatter_class=ArgumentDefaultsRichHelpFormatter)
group = parser_sub.add_mutually_exclusive_group(required=True)
group.add_argument('--read1','-1',help='First read file')
parser_sub.add_argument('--read2','-2',help='Second read file')
group.add_argument('--bam','-a',help='BAM file. Make sure it has been generated using the H37Rv genome (GCA_000195955.2)')
group.add_argument('--fasta','-f',help='Fasta file')
parser_sub.add_argument('--prefix','-p',default="tbprofiler",help='Sample prefix')
parser_sub.add_argument('--txt',action="store_true",help="Add text output")
parser_sub.add_argument('--csv',action="store_true",help="Add CSV output")
parser_sub.add_argument('--docx',action="store_true",help="Add docx output. This requires docxtpl to be installed")
parser_sub.add_argument('--text_template',type=str,help='Jinja2 formatted template for output')
parser_sub.add_argument('--kmer_counter','--kmer-counter',default='kmc',choices=["kmc","dsk"],type=str,help="Kmer counter")
parser_sub.add_argument('--platform','-m',choices=["illumina","nanopore","pacbio"],default="illumina",help='NGS Platform used to generate data')
parser_sub.add_argument('--db',default='tbdb',help='Mutation panel name')
parser_sub.add_argument('--external_db','--external-db',type=str,help='Path to db files prefix (overrides "--db" parameter)')
parser_sub.add_argument('--dir','-d',default=".",help='Storage directory')
parser_sub.add_argument('--no_clean','--no-clean', action='store_true',help=argparse.SUPPRESS)
parser_sub.add_argument('--threads','-t',default=1,help='Threads to use',type=int)
parser_sub.add_argument('--ram',default=2,type=int_2_or_more,help='Maximum memory to use in Gb')
parser_sub.add_argument('--temp',help="Temp firectory to process all files",type=str,default=".")
parser_sub.add_argument('--version', action='version', version="tb-profiler version %s" % tbp.__version__)
parser_sub.add_argument('--logging',type=str.upper,default="INFO",choices=["DEBUG","INFO","WARNING","ERROR","CRITICAL"],help='Logging level')
parser_sub.add_argument('--debug',action='store_true',help=argparse.SUPPRESS)
parser_sub.set_defaults(func=main_spoligotype)
parser_sub = subparsers.add_parser('collate', help='Collate results form multiple samples together', formatter_class=ArgumentDefaultsRichHelpFormatter)
parser_sub.add_argument('--prefix','-p',default="tbprofiler",help='Sample prefix')
parser_sub.add_argument('--samples',help='File with samples (one per line)')
parser_sub.add_argument('--itol',action="store_true",help='Generate itol config files')
parser_sub.add_argument('--full',action="store_true",help='Output mutations in main result file')
parser_sub.add_argument('--all_variants','--all-variants',action="store_true",help='Output all variants in variant matrix')
parser_sub.add_argument('--mark_missing','--mark-missing',action="store_true",help='An asteriks will be use to mark predictions which are affected by missing data at a drug resistance position')
parser_sub.add_argument('--db',default='tbdb',help='Full path to mutation database json file to use')
parser_sub.add_argument('--format',default='txt',choices=['txt','csv'],help='Format of the output')
parser_sub.add_argument('--external_db','--external-db',type=str,help='Path to db files prefix (overrides "--db" parameter)')
parser_sub.add_argument('--dir','-d',nargs="+",default=["results"],help='Storage directory')
parser_sub.add_argument('--no_clean','--no-clean', action='store_true',help=argparse.SUPPRESS)
parser_sub.add_argument('--temp',help="Temp firectory to process all files",type=str,default=".")
parser_sub.add_argument('--version', action='version', version="tb-profiler version %s" % tbp.__version__)
parser_sub.add_argument('--logging',type=str.upper,default="INFO",choices=["DEBUG","INFO","WARNING","ERROR","CRITICAL"],help='Logging level')
parser_sub.add_argument('--debug',action='store_true',help=argparse.SUPPRESS)
parser_sub.set_defaults(func=main_collate)
parser_sub = subparsers.add_parser('reformat', help='Reformat json results into text or csv', formatter_class=ArgumentDefaultsRichHelpFormatter)
parser_sub.add_argument('json',default="tbprofiler",help='Sample prefix')
parser_sub.add_argument('--txt',action="store_true",help="Add text output")
parser_sub.add_argument('--csv',action="store_true",help="Add CSV output")
parser_sub.add_argument('--docx',action="store_true",help="Add docx output. This requires docxtpl to be installed")
parser_sub.add_argument('--docx_template','--docx-template',help="Supply custom template for --docx output")
parser_sub.add_argument('--docx_plugin','--docx-plugin',choices=list(docx_plugins),help="Use a plugin template for --docx output")
parser_sub.add_argument('--text_template','--text-template',type=str,help='Jinja2 formatted template for output')
parser_sub.add_argument('--db',default='tbdb',help='Mutation panel name')
parser_sub.add_argument('--external_db','--external-db',type=str,help='Path to db files prefix (overrides "--db" parameter)')
parser_sub.add_argument('--dir','-d',default=".",help='Storage directory')
parser_sub.add_argument('--no_clean','--no-clean', action='store_true',help=argparse.SUPPRESS)
parser_sub.add_argument('--suspect',action="store_true",help=argparse.SUPPRESS)
parser_sub.add_argument('--temp',help="Temp firectory to process all files",type=str,default=".")
parser_sub.add_argument('--version', action='version', version="tb-profiler version %s" % tbp.__version__)
parser_sub.add_argument('--logging',type=str.upper,default="INFO",choices=["DEBUG","INFO","WARNING","ERROR","CRITICAL"],help='Logging level')
parser_sub.add_argument('--debug',action='store_true',help=argparse.SUPPRESS)
parser_sub.set_defaults(func=main_reformat)
parser_sub = subparsers.add_parser('create_db', help='Generate the files required to run tb-profiler', formatter_class=ArgumentDefaultsRichHelpFormatter)
parser_sub.add_argument('--prefix','-p',type=str,help='The prefix for all output files',required=True)
parser_sub.add_argument('--csv','-c',nargs="+",default=["mutations.csv"],type=str,help='The input CSV file containing the mutations')
parser_sub.add_argument('--watchlist','-w',default="watchlist.csv",type=str,help='A csv file containing genes to profile but without any specific associated mutations')
parser_sub.add_argument('--spoligotypes',default="spoligotype_spacers.txt",type=str,help='A file containing a list of spoligotype spacers')
parser_sub.add_argument('--spoligotype_annotations','--spoligotype-annotations',default="spoligotype_list.csv")
parser_sub.add_argument('--barcode',default="barcode.bed",type=str,help='A bed file containing lineage barcode SNPs')
parser_sub.add_argument('--bedmask',default="mask.bed",type=str,help='A bed file containing a list of low-complexity regions')
parser_sub.add_argument('--rules',type=str,default="rules.txt",help='A file containing python rules')
parser_sub.add_argument('--amplicon_primers','--amplicon-primers',type=str,help='A file containing a list of amplicon primers')
parser_sub.add_argument('--match_ref','--match-ref',type=str,help='Match the chromosome name to the given fasta file')
parser_sub.add_argument('--custom',action="store_true",help='Tells the script this is a custom database, this is used to alter the generation of the version definition')
parser_sub.add_argument('--db_name',help='Overrides the name of the database in the version file')
parser_sub.add_argument('--db_commit','--db-commit',help='Overrides the commit string of the database in the version file')
parser_sub.add_argument('--db_author','--db-author',help='Overrides the author of the database in the version file')
parser_sub.add_argument('--db_date','--db-date',help='Overrides the date of the database in the version file')
parser_sub.add_argument('--include_original_mutation','--include-original-mutation',action="store_true", help='Include the original mutation (before reformatting) as part of the variant annotaion')
parser_sub.add_argument('--load',action="store_true", help='Automaticaly load database')
parser_sub.add_argument('--no_overwrite','--no-overwrite',action="store_true", help="Don't load if existing database with prefix exists")
parser_sub.add_argument('--dir','-d',default=".",help='Storage directory')
parser_sub.add_argument('--no_clean','--no-clean', action='store_true',help=argparse.SUPPRESS)
parser_sub.add_argument('--temp',help="Temp firectory to process all files",type=str,default=".")
parser_sub.add_argument('--version', action='version', version="tb-profiler version %s" % tbp.__version__)
parser_sub.add_argument('--logging',type=str.upper,default="INFO",choices=["DEBUG","INFO","WARNING","ERROR","CRITICAL"],help='Logging level')
parser_sub.add_argument('--debug',action='store_true',help=argparse.SUPPRESS)
parser_sub.set_defaults(func=main_create_db)
parser_sub = subparsers.add_parser('load_library', help='Load new library', formatter_class=ArgumentDefaultsRichHelpFormatter)
parser_sub.add_argument('prefix',type=str,help='Prefix to the library files')
parser_sub.add_argument('--dir','-d',default=".",help='Storage directory')
parser_sub.add_argument('--no_clean','--no-clean', action='store_true',help=argparse.SUPPRESS)
parser_sub.add_argument('--temp',help="Temp firectory to process all files",type=str,default=".")
parser_sub.add_argument('--version', action='version', version="tb-profiler version %s" % tbp.__version__)
parser_sub.add_argument('--logging',type=str.upper,default="INFO",choices=["DEBUG","INFO","WARNING","ERROR","CRITICAL"],help='Logging level')
parser_sub.add_argument('--debug',action='store_true',help=argparse.SUPPRESS)
parser_sub.set_defaults(func=main_load_library)
parser_sub = subparsers.add_parser('update_tbdb', help='Pull the latest tbdb library and load', formatter_class=ArgumentDefaultsRichHelpFormatter)
parser_sub.add_argument('--prefix','-p',help='Database name')
parser_sub.add_argument('--repo','-r',default="https://github.com/jodyphelan/tbdb.git",help='Repository to pull from')
parser_sub.add_argument('--branch','-b',default="tbdb",help='Branch to pull from')
parser_sub.add_argument('--commit','-c',help='Git commit hash to checkout (default: latest)')
parser_sub.add_argument('--match_ref','--match-ref',type=str,help='The prefix for all output files')
parser_sub.add_argument('--dir','-d',default=".",help='Storage directory')
parser_sub.add_argument('--no_clean','--no-clean', action='store_true',help=argparse.SUPPRESS)
parser_sub.add_argument('--temp',help="Temp firectory to process all files",type=str,default=".")
parser_sub.add_argument('--version', action='version', version="tb-profiler version %s" % tbp.__version__)
parser_sub.add_argument('--logging',type=str.upper,default="INFO",choices=["DEBUG","INFO","WARNING","ERROR","CRITICAL"],help='Logging level')
parser_sub.add_argument('--debug',action='store_true',help=argparse.SUPPRESS)
parser_sub.set_defaults(func=main_update_tbdb)
parser_sub = subparsers.add_parser('batch', help='Run tb-profiler for several samples', formatter_class=ArgumentDefaultsRichHelpFormatter)
parser_sub.add_argument('--csv',help='CSV with samples and files',required=True)
parser_sub.add_argument('--args',type=str, help='Arguments to use with tb-profiler')
parser_sub.add_argument('--jobs','-j',default=1,help='Threads to use',type=int)
parser_sub.add_argument('--threads_per_job','--threads-per-job','-t',default=1,help='Threads to use',type=int)
parser_sub.add_argument('--dir','-d',default=".",help='Storage directory')
parser_sub.add_argument('--no_clean','--no-clean', action='store_true',help=argparse.SUPPRESS)
parser_sub.add_argument('--temp',help="Temp firectory to process all files",type=str,default=".")
parser_sub.add_argument('--version', action='version', version="tb-profiler version %s" % tbp.__version__)
parser_sub.add_argument('--logging',type=str.upper,default="INFO",choices=["DEBUG","INFO","WARNING","ERROR","CRITICAL"],help='Logging level')
parser_sub.add_argument('--debug',action='store_true',help=argparse.SUPPRESS)
parser_sub.set_defaults(func=main_batch)
parser_sub = subparsers.add_parser('list_db', help='List loaded databases', formatter_class=ArgumentDefaultsRichHelpFormatter)
parser_sub.add_argument('--dir','-d',default=".",help='Storage directory')
parser_sub.add_argument('--no_clean','--no-clean', action='store_true',help=argparse.SUPPRESS)
parser_sub.add_argument('--temp',help="Temp firectory to process all files",type=str,default=".")
parser_sub.add_argument('--version', action='version', version="tb-profiler version %s" % tbp.__version__)
parser_sub.add_argument('--logging',type=str.upper,default="INFO",choices=["DEBUG","INFO","WARNING","ERROR","CRITICAL"],help='Logging level')
parser_sub.add_argument('--debug',action='store_true',help=argparse.SUPPRESS)
parser_sub.set_defaults(func=main_list_db)
parser_sub = subparsers.add_parser('version', help='Output program version and exit', formatter_class=ArgumentDefaultsRichHelpFormatter)
parser_sub.add_argument('--dir','-d',default=".",help='Storage directory')
parser_sub.add_argument('--no_clean','--no-clean', action='store_true',help=argparse.SUPPRESS)
parser_sub.add_argument('--temp',help="Temp firectory to process all files",type=str,default=".")
parser_sub.add_argument('--version', action='version', version="tb-profiler version %s" % tbp.__version__)
parser_sub.add_argument('--logging',type=str.upper,default="INFO",choices=["DEBUG","INFO","WARNING","ERROR","CRITICAL"],help='Logging level')
parser_sub.add_argument('--debug',action='store_true',help=argparse.SUPPRESS)
parser_sub.set_defaults(func=main_version)
args = parser.parse_args()
if args.debug:
args.logging = "DEBUG"
logging.basicConfig(
level=args.logging, format="%(message)s", datefmt="[%X]", handlers=[RichHandler()]
)
if hasattr(args, 'func'):
args.software_name = __softwarename__
args.version = tbp.__version__
args.tmp_prefix = str(uuid4())
args.files_prefix = os.path.abspath(f"{args.temp}/{args.tmp_prefix}")
if hasattr(args,'dir'):
if isinstance(args.dir,list):
args.dir = [os.path.abspath(x) for x in args.dir]
else:
args.dir = os.path.abspath(args.dir)
if hasattr(args, 'db'):
if args.db=="tbdb" and not args.external_db and pp.nofile(sys.base_prefix+"/share/tbprofiler/tbdb.fasta"):
logging.error("Can't find the tbdb file at %s. Please run 'tb-profiler update_tbdb' to load the default library or specify another using the '--external_db' flag" % sys.base_prefix)
raise SystemExit
if args.external_db:
args.conf = pp.get_db(args.software_name,args.external_db)
else:
args.conf = pp.get_db(args.software_name,args.db)
if args.conf is None:
logging.error("Can't find the database %s. Please run 'tb-profiler create_db' to create the database or specify another using the '--external_db' flag" % args.db)
raise SystemExit
args.plugins = docx_plugins
args.func(args)
else:
parser.print_help(sys.stderr)