-
Notifications
You must be signed in to change notification settings - Fork 1
/
vclust.py
executable file
·1231 lines (1111 loc) · 36.1 KB
/
vclust.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 python3
"""Compute Average Nucleotide Identity (ANI) and cluster virus genome sequences.
https://github.com/refresh-bio/vclust-dev
"""
import argparse
import logging
import multiprocessing
import pathlib
import shutil
import os
import subprocess
import sys
import typing
import uuid
__version__ = '1.0.3'
DEFAULT_THREAD_COUNT = min(multiprocessing.cpu_count(), 64)
VCLUST_DIR = pathlib.Path(__file__).resolve().parent
# Default paths to third-party binaries
BIN_DIR = VCLUST_DIR / 'bin'
BIN_KMERDB = BIN_DIR / 'kmer-db'
BIN_LZANI = BIN_DIR / 'lz-ani'
BIN_CLUSTY = BIN_DIR / 'clusty'
BIN_FASTASPLIT = BIN_DIR / 'multi-fasta-split'
# lz-ani output columns
ALIGN_FIELDS = [
'idx1', 'idx2', 'id1', 'id2', 'tani', 'gani', 'ani', 'cov',
'num_alns', 'len_ratio', 'len1', 'len2', 'nt_match', 'nt_mismatch',
]
# vclust align output formats
ALIGN_OUTFMT = {
'lite': ALIGN_FIELDS[:2] + ALIGN_FIELDS[4:9],
'standard': ALIGN_FIELDS[:10],
'complete': ALIGN_FIELDS[:],
}
def get_parser() -> argparse.ArgumentParser:
"""Return an argument parser."""
fmt = lambda prog: CustomHelpFormatter(prog, max_help_position=32)
def input_path_type(value):
path = pathlib.Path(value)
if not path.exists():
msg = f'input does not exist: {value}'
raise argparse.ArgumentTypeError(msg)
return path
def ranged_float_type(value):
f = float(value)
if f < 0 or f > 1:
raise argparse.ArgumentTypeError('must be between 0 and 1')
return f
parser = argparse.ArgumentParser(
description=f'%(prog)s v.{__version__}: calculate ANI and cluster '
'virus (meta)genome sequences',
add_help=False,
)
parser.add_argument(
'-v', '--version',
action='version',
version=f'v.{__version__}',
help="Display the tool's version and exit"
)
parser.add_argument(
'-h', '--help',
action='help',
help='Show this help message and exit'
)
subparsers = parser.add_subparsers(dest='command')
# Prefilter parser
prefilter_parser = subparsers.add_parser(
'prefilter',
help='Prefilter genome pairs for alignment',
formatter_class=fmt,
add_help=False,
)
prefilter_optional = prefilter_parser._action_groups.pop()
prefilter_required = prefilter_parser.add_argument_group('required arguments')
prefilter_parser._action_groups.append(prefilter_optional)
prefilter_required.add_argument(
'-i', '--in',
metavar='<file>',
type=input_path_type,
dest='input_path',
help='Input FASTA file or directory with FASTA files',
required=True
)
prefilter_required.add_argument(
'-o', '--out',
metavar='<file>',
type=pathlib.Path,
dest='output_path',
help='Output filename',
required=True
)
prefilter_parser.add_argument(
'-k', '--k',
metavar="<int>",
type=int,
default=25,
choices=range(15, 31),
help="Size of k-mer for Kmer-db [%(default)s]"
)
prefilter_parser.add_argument(
'--min-kmers',
metavar="<int>",
type=int,
default=10,
help='Filter genome pairs based on minimum number of shared k-mers '
'[%(default)s]'
)
prefilter_parser.add_argument(
'--min-ident',
metavar="<float>",
type=ranged_float_type,
default=0.7,
help='Filter genome pairs based on minimum sequence identity of '
'the shorter sequence (0-1) [%(default)s]'
)
prefilter_parser.add_argument(
'--batch-size',
metavar="<int>",
type=int,
default=0,
help='Split a multifasta file into smaller files of n FASTA sequences. '
'This option reduces memory at the expense of speed. By default, no '
'batch [%(default)s]'
)
prefilter_parser.add_argument(
'--keep_temp',
action="store_true",
help='Keep temporary Kmer-db files [%(default)s]'
)
prefilter_parser.add_argument(
'--bin',
metavar='<file>',
type=pathlib.Path,
dest="bin_kmerdb",
default=f'{BIN_KMERDB}',
help='Path to the Kmer-db binary [%(default)s]'
)
prefilter_parser.add_argument(
'--bin-fasta',
metavar='<file>',
type=pathlib.Path,
dest="bin_fastasplit",
default=f'{BIN_FASTASPLIT}',
help='Path to the multi-fasta-split binary [%(default)s]'
)
prefilter_parser.add_argument(
'-t', '--threads',
metavar="<int>",
dest="num_threads",
type=int,
default=DEFAULT_THREAD_COUNT,
help='Number of threads (all by default) [%(default)s]'
)
prefilter_parser.add_argument(
'-v', '--verbose',
action="store_true",
help="Show Kmer-db progress"
)
prefilter_parser.add_argument(
'-h', '--help',
action='help',
help='Show this help message and exit'
)
# Align parser
align_parser = subparsers.add_parser(
'align',
help='Align genome sequences and calculate ANI metrics',
formatter_class=fmt,
add_help=False,
)
align_optional = align_parser._action_groups.pop()
align_required = align_parser.add_argument_group('required arguments')
align_parser._action_groups.append(align_optional)
align_required.add_argument(
'-i', '--in',
metavar='<file>',
type=input_path_type,
dest='input_path',
help='Input FASTA file or directory with FASTA files',
required=True
)
align_required.add_argument(
'-o', '--out',
metavar='<file>',
type=pathlib.Path,
dest='output_path',
help='Output filename',
required=True
)
align_parser.add_argument(
'--filter',
metavar='<file>',
type=input_path_type,
dest="filter_path",
help='Path to filter file (output of prefilter)'
)
align_parser.add_argument(
'--filter-threshold',
metavar='<float>',
dest='filter_threshold',
type=ranged_float_type,
default=0,
help='Align genome pairs above the threshold (0-1) [%(default)s]'
)
align_parser.add_argument(
'--outfmt',
metavar='<str>',
choices=ALIGN_OUTFMT.keys(),
dest='outfmt',
default='standard',
help='Output format [%(default)s]\n'
f'choices: {",".join(ALIGN_OUTFMT.keys())}'
)
align_parser.add_argument(
'--out-ani',
dest='ani',
metavar='<float>',
type=ranged_float_type,
default=0,
help='Min. ANI to output (0-1) [%(default)s]'
)
align_parser.add_argument(
'--out-tani',
dest='tani',
metavar='<float>',
type=ranged_float_type,
default=0,
help='Min. tANI to output (0-1) [%(default)s]'
)
align_parser.add_argument(
'--out-gani',
dest='gani',
metavar='<float>',
type=ranged_float_type,
default=0,
help='Min. gANI to output (0-1) [%(default)s]'
)
align_parser.add_argument(
'--out-cov',
dest='cov',
metavar='<float>',
type=ranged_float_type,
default=0,
help='Min. coverage (aligned fraction) to output (0-1) [%(default)s]'
)
align_parser.add_argument(
'--bin',
metavar='<file>',
type=pathlib.Path,
dest='bin_lzani',
default=f'{BIN_LZANI}',
help='Path to the lz-ani binary [%(default)s]'
)
align_parser.add_argument(
'--mal',
metavar='<int>',
type=int,
default=11,
help='Min. anchor length [%(default)s]'
)
align_parser.add_argument(
'--msl',
metavar='<int>',
type=int,
default=7,
help='Min. seed length [%(default)s]'
)
align_parser.add_argument(
'--mrd',
metavar='<int>',
type=int,
default=40,
help='Max. dist. between approx. matches in reference [%(default)s]'
)
align_parser.add_argument(
'--mqd',
metavar='<int>',
type=int,
default=40,
help='Max. dist. between approx. matches in query [%(default)s]'
)
align_parser.add_argument(
'--reg',
metavar='<int>',
type=int,
default=35,
help='Min. considered region length [%(default)s]'
)
align_parser.add_argument(
'--aw',
metavar='<int>',
type=int,
default=15,
help='Approx. window length [%(default)s]'
)
align_parser.add_argument(
'--am',
metavar='<int>',
type=int,
default=7,
help='Max. no. of mismatches in approx. window [%(default)s]'
)
align_parser.add_argument(
'--ar',
metavar='<int>',
type=int,
default=3,
help='Min. length of run ending approx. extension [%(default)s]'
)
align_parser.add_argument(
'-t', '--threads',
metavar='<int>',
dest='num_threads',
type=int,
default=DEFAULT_THREAD_COUNT,
help='Number of threads (all by default) [%(default)s]'
)
align_parser.add_argument(
'-v', '--verbose',
action="store_true",
help="Show LZ-ANI progress"
)
align_parser.add_argument(
'-h', '--help',
action='help',
help='Show this help message and exit'
)
# Cluster parser
cluster_parser = subparsers.add_parser(
'cluster',
help='Cluster genomes based on ANI thresholds',
formatter_class=fmt,
add_help=False,
)
cluster_optional = cluster_parser._action_groups.pop()
cluster_required = cluster_parser.add_argument_group('required arguments')
cluster_parser._action_groups.append(cluster_optional)
cluster_required.add_argument(
'-i', '--in',
metavar='<file>',
type=input_path_type,
dest='input_path',
help='Input file with ANI metrics (tsv)',
required=True
)
cluster_required.add_argument(
'-o', '--out',
metavar='<file>',
type=pathlib.Path,
dest='output_path',
help='Output filename',
required=True
)
cluster_required.add_argument(
'--ids',
metavar='<file>',
type=input_path_type,
dest='ids_path',
help='Input file with sequence identifiers (tsv)',
required=True
)
cluster_parser.add_argument(
'-r', '--out-repr',
action='store_true',
dest='representatives',
help='Output a representative genome for each cluster instead of '
'numerical cluster identifiers. The representative genome is selected '
'as the one with the longest sequence. [%(default)s]'
)
choices = ['single', 'complete', 'uclust', 'cd-hit', 'set-cover', 'leiden']
cluster_parser.add_argument(
'--algorithm',
metavar='<str>',
dest="algorithm",
choices=choices,
default='single',
help='Clustering algorithm [%(default)s]\n'
'* single: Single-linkage (connected component)\n'
'* complete: Complete-linkage\n'
'* uclust: UCLUST\n'
'* cd-hit: Greedy incremental\n'
'* set-cover: Greedy set-cover (MMseqs2)\n'
'* leiden: Leiden algorithm'
)
choices = ['tani','gani','ani']
cluster_parser.add_argument(
'--metric',
metavar='<str>',
dest='metric',
choices=choices,
default='tani',
help='Similarity metric for clustering [%(default)s]\n'
f'choices: {",".join(choices)}'
)
cluster_parser.add_argument(
'--tani',
metavar='<float>',
dest='tani',
type=ranged_float_type,
default=0,
help='Min. total ANI (0-1) [%(default)s]\n'
)
cluster_parser.add_argument(
'--gani',
metavar='<float>',
dest='gani',
type=ranged_float_type,
default=0,
help='Min. global ANI (0-1) [%(default)s]\n'
)
cluster_parser.add_argument(
'--ani',
metavar='<float>',
dest='ani',
type=ranged_float_type,
default=0,
help='Min. ANI (0-1) [%(default)s]\n'
)
cluster_parser.add_argument(
'--cov',
metavar='<float>',
dest='cov',
type=ranged_float_type,
default=0,
help='Min. coverage/aligned fraction (0-1) [%(default)s]\n'
)
cluster_parser.add_argument(
'--num_alns',
metavar='<int>',
dest='num_alns',
type=int,
default=0,
help='Max. number of local alignments between two genomes; 0 means all '
'genome pairs are allowed. [%(default)s]'
)
cluster_parser.add_argument(
'--leiden-resolution',
metavar='<float>',
type=ranged_float_type,
default=0.7,
help='Resolution parameter for the Leiden algorithm [%(default)s]\n'
)
cluster_parser.add_argument(
'--bin',
metavar='<file>',
type=pathlib.Path,
dest="BIN_CLUSTY",
default=f'{BIN_CLUSTY}',
help='Path to the Clusty binary [%(default)s]'
)
cluster_parser.add_argument(
'-v', '--verbose',
action="store_true",
help="Show Clusty progress"
)
cluster_parser.add_argument(
'-h', '--help',
action='help',
help='Show this help message and exit'
)
# Show help message if the script is run without any arguments.
if len(sys.argv[1:]) == 0:
parser.print_help()
parser.exit()
# Show subparser help message if the script is run without any arguments.
subparsers = [
('prefilter', prefilter_parser),
('align', align_parser),
('cluster', cluster_parser),
]
for name, subparser in subparsers:
if sys.argv[-1] == name:
subparser.print_help()
parser.exit()
return parser
def create_logger(name: str, log_level: int = logging.INFO) -> logging.Logger:
"""Returns a logger to log events.
Args:
name:
Name of the logger.
log_level:
The numeric level of the logging event (one of DEBUG, INFO etc.).
"""
logger = logging.getLogger(name)
logger.setLevel(log_level)
# Set log format to handlers
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
# Create stream logger handler
sh = logging.StreamHandler()
sh.setLevel(log_level)
sh.setFormatter(formatter)
logger.addHandler(sh)
return logger
def get_uuid() -> str:
"""Returns a unique string identifier."""
return f'vclust-{str(uuid.uuid4().hex)[:10]}'
def validate_binary(bin_path: pathlib.Path) -> pathlib.Path:
"""Validates the existence and executability of a binary file.
This function checks if the provided path points to an existing binary file
and if it is executable. It also attempts to run the binary to ensure it
operates without errors.
Args:
bin_path:
The path to the executable binary file.
Returns:
pathlib.Path: The resolved path to the binary file.
Raises:
SystemExit: If the binary file does not exist, is not executable, or
if running the binary encounters an error.
"""
bin_path = bin_path.resolve()
if not bin_path.exists():
exit(f'error: Executable not found: {bin_path}')
if not bin_path.is_file() or not os.access(bin_path, os.X_OK):
exit(f'error: Binary file not executable: {bin_path}')
try:
process = subprocess.run(
[str(bin_path)],
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
check=True
)
except subprocess.CalledProcessError as e:
exit(f'error: Running {bin_path} failed with message: {e.stderr}')
except OSError as e:
exit(f'error: OSError in {bin_path} - {e}')
except Exception as e:
exit(f'error: Unexpected error in binary {bin_path} - {e}')
return bin_path
def validate_args_fasta_input(args, parser) -> argparse.Namespace:
"""Validates the arguments for FASTA input."""
args.is_multifasta = True
args.fasta_paths = [args.input_path]
if args.input_path.is_dir():
args.is_multifasta = False
args.fasta_paths = sorted(
f for f in args.input_path.iterdir() if f.is_file()
)
if not args.is_multifasta and len(args.fasta_paths) < 2:
parser.error(f'Too few fasta files found in {args.input_path}. '
f'Expected at least 2, but found {len(args.fasta_paths)}.')
return args
def validate_args_prefilter(args, parser) -> argparse.Namespace:
"""Validates the arguments for the prefilter command."""
if args.batch_size and args.input_path.is_dir():
parser.error('--batch-size only handles a multi-fasta file'
', not a directory.')
return args
def validate_args_cluster(args, parser) -> argparse.Namespace:
"""Validates the arguments for the cluster command."""
# Check the metric and its threshold.
args_dict = vars(args)
args.metric_threshold = args_dict.get(args.metric, 0)
if not args.metric_threshold:
parser.error(f'{args.metric} threshold must be above 0. '
f'Specify the option: --{args.metric}')
# Check if the input TSV file has the required columns.
with open(args.input_path) as fh:
header = fh.readline().split()
if 'idx1' not in header and 'idx2' not in header:
parser.error(
f'missing columns `idx1` and `idx2` in {args.input_path}')
options = ['tani', 'gani', 'ani', 'cov', 'num_alns']
for name in options:
value = args_dict[name]
if value != 0 and name not in header:
parser.error(f'missing column `{name}` in {args.input_path}')
return args
def run(
cmd: typing.List[str],
verbose: bool,
logger: logging.Logger
) -> subprocess.CompletedProcess:
"""Executes a given command as a subprocess and handles logging.
This function runs the specified command, logs the execution details,
and manages errors. If verbose mode is enabled, the command's standard
error output is not suppressed. Otherwise, the standard error is piped
and logged in case of failure.
Args:
cmd:
The command to run as a list of strings.
verbose:
Flag indicating whether to run the command in verbose mode.
logger:
The logger instance for logging information and errors.
Returns:
subprocess.CompletedProcess: The completed process information.
Raises:
SystemExit: If the command fails to execute or an error occurs.
"""
logger.info(f'Running: {" ".join(cmd)}')
try:
process = subprocess.run(
cmd,
stdout=subprocess.DEVNULL,
stderr=None if verbose else subprocess.PIPE,
text=True,
check=True
)
except subprocess.CalledProcessError as e:
logger.error(f'Process {" ".join(cmd)} failed with message: {e.stderr}')
exit(1)
except OSError as e:
logger.error(f'OSError: {" ".join(cmd)} failed with message: {e}')
exit(1)
except Exception as e:
logger.error(f'Unexpected: {" ".join(cmd)} failed with message: {e}')
exit(1)
logger.info(f'Done')
return process
def cmd_fastasplit(
input_fasta: pathlib.Path,
out_dir: pathlib.Path,
n: int,
verbose: bool,
bin_path = BIN_FASTASPLIT
) -> typing.List[str]:
"""Constructs the command line for multi-fasta-split.
Args:
input_fasta (Path):
Path to the input FASTA file.
out_dir (Path):
Path to the output directory.
n (int):
Number of sequences per output FASTA file.
verbose (bool):
Whether to display verbose output.
bin_path (Path):
Path to the multi-fasta-split executable.
Returns:
list: The constructed command as a list of strings.
"""
cmd = [
f'{bin_path}',
'-n', f'{n}',
f'--verbosity',
f'{int(verbose)}',
'--out-prefix',
f'{out_dir}/part',
f'{input_fasta}',
]
return cmd
def cmd_kmerdb_build(
input_paths: pathlib.Path,
txt_path: pathlib.Path,
db_path: pathlib.Path,
is_multisample_fasta: bool,
kmer_size: int,
num_threads: int,
verbose: bool = False,
bin_path: pathlib.Path = BIN_KMERDB
) -> typing.List[str]:
"""Constructs the command line for Kmer-db build.
Args:
input_fasta (Path):
Path to the input FASTA file or directory with input FASTA files.
outfile_txt (Path):
Path to the output text file that will list the input FASTA files.
outfile_db (Path):
Path to the output kmer-db database file.
kmer_size (int):
k-mer size.
num_threads (int):
Number of threads to use in kmer-db.
verbose (bool):
Whether to display verbose output.
bin_path (Path):
Path to the kmer-db executable.
Returns:
list: The constructed command as a list of strings.
"""
# Create a text file listing input FASTA files.
with open(txt_path, 'w') as oh:
for f in input_paths:
oh.write(f'{f}\n')
# Run kmer-db build.
cmd = [
f"{bin_path}",
"build",
"-k", f"{kmer_size}",
"-t", f"{num_threads}",
f'{txt_path}',
f'{db_path}',
]
if is_multisample_fasta:
cmd.insert(2, '-multisample-fasta')
return cmd
def cmd_kmerdb_all2all(
db_paths: typing.List[pathlib.Path],
db_list_path: pathlib.Path,
outfile_all2all: pathlib.Path,
kmer_count: int,
num_threads: int,
verbose: bool,
bin_path: pathlib.Path = BIN_KMERDB
) -> typing.List[str]:
"""Constructs the command line for Kmer-db all2all.
Args:
db_paths (list[Path]):
List of paths to the input kmer-db database files.
db_list_path (Path):
Path to the output text file listing the kmer-db database files.
outfile_all2all (Path):
Path to the output all2all file.
kmer_count (int):
Minimum number of shared k-mers to report in all2all output.
num_threads (int):
Number of threads to use in kmer-db.
verbose (bool):
Whether to display verbose output.
bin_path (Path):
Path to the kmer-db executable.
Returns:
list: The constructed command as a list of strings.
"""
with open(db_list_path, 'w') as oh:
for db_path in db_paths:
oh.write(f'{db_path}\n')
cmd = [
f"{bin_path}",
'all2all-parts' if len(db_paths) > 1 else 'all2all-sp',
'-sparse',
'-above', f'{kmer_count}',
"-t", f"{num_threads}",
f'{db_list_path}' if len(db_paths) > 1 else f'{db_paths[0]}',
f'{outfile_all2all}',
]
return cmd
def cmd_kmerdb_distance(
infile_all2all: pathlib.Path,
min_value: float,
num_threads: int,
verbose: bool = False,
bin_path: pathlib.Path = BIN_KMERDB
) -> typing.List[str]:
"""Constructs the command line for Kmer-db distance.
Args:
infile_all2all (Path):
Path to the input all2all file.
min_value (float):
Minimum value to filter all2all output.
num_threads (int):
Number of threads to use in kmer-db.
verbose (bool):
Whether to display verbose output.
bin_path (Path):
Path to the kmer-db executable.
Returns:
list: The constructed command as a list of strings.
"""
cmd = [
f"{bin_path}",
"distance",
"ani-shorter",
"-sparse",
'-above', f'{min_value}',
"-t", f"{num_threads}",
f'{infile_all2all}',
]
return cmd
def cmd_lzani(
input_paths: typing.List[pathlib.Path],
txt_path: pathlib.Path,
output_path: pathlib.Path,
out_format: typing.List[str],
out_tani: float,
out_gani: float,
out_ani: float,
out_cov: float,
filter_file: pathlib.Path,
filter_threshold: float,
mal: int,
msl: int,
mrd: int,
mqd: int,
reg: int,
aw: int,
am: int,
ar: int,
num_threads: int,
verbose: bool,
bin_path: pathlib.Path = BIN_LZANI
) -> typing.List[str]:
"""Constructs the command line for LZ-ANI.
Args:
input_paths (List[Path]):
List of paths to the input FASTA files.
txt_path (Path):
Path to the output text file listing the input FASTA files.
output_path (Path):
Path to the output ANI file.
out_format (List[str]):
List of LZ-ANI column names.
out_tani (float):
Minimum tANI to output.
out_gani (float):
Minimum gANI to output.
out_ani (float):
Minimum ANI to output.
out_cov (float):
Minimum coverage (aligned fraction) to output.
filter_file (Path):
Path to the filter file (prefilter's output).
filter_threshold (float):
Filter threshold.
mal (int):
Minimum anchor length.
msl (int):
Minimum seed length.
mrd (int):
Maximum distance between approximate matches in reference.
mqd (int):
Maximum distance between approximate matches in query.
reg (int):
Minimum considered region length.
aw (int):
Approximate window length.
am (int):
Maximum number of mismatches in approximate window.
ar (int):
Minimum length of run ending approximate extension.
num_threads (int):
Number of threads to use in lz-ani.
verbose (bool):
Whether to display verbose output.
bin_path (Path):
Path to the lz-ani executable.
Returns:
list: The constructed command as a list of strings.
"""
# Create a text file listing input FASTA files.
with open(txt_path, 'w') as oh:
for f in input_paths:
oh.write(f'{f}\n')
cmd = [
f'{bin_path}',
'all2all',
'--in-txt',
f'{txt_path}',
'-o',
f'{output_path}',
'-t',
f'{num_threads}',
'--verbose', f'{int(verbose) + 1}',
'--mal', f'{mal}',
'--msl', f'{msl}',
'--mrd', f'{mrd}',
'--mqd', f'{mqd}',
'--reg', f'{reg}',
'--aw', f'{aw}',
'--am', f'{am}',
'--ar', f'{ar}',
'--multisample-fasta',
'true' if len(input_paths) == 1 else 'false',
'--out-type', 'tsv',
'--out-format',
','.join(out_format),
]
if filter_file:
cmd.extend(['--flt-kmerdb', f'{filter_file}', f'{filter_threshold}'])
cols = [
('tani', out_tani), ('gani', out_gani),
('ani', out_ani), ('cov', out_cov)
]
for name, value in cols:
if value > 0:
cmd.extend(['--out-filter', f'{name}', f'{value}'])
if verbose:
cmd.extend(['--verbose', '2'])
return cmd
def cmd_clusty(
input_path: pathlib.Path,
ids_path: pathlib.Path,
output_path: pathlib.Path,
algorithm: str,
metric: str,
tani: float,
gani: float,
ani: float,
cov: float,
num_alns: int,
is_representatives: bool,
leiden_resolution: float,
bin_path=BIN_CLUSTY,
) -> typing.List[str]:
"""Constructs the command line for Clusty.
Args:
input_path (Path):
Path to the input ANI file.
ids_path (Path):
Path to the input file with sequence identifiers.
output_path (Path):
Path to the output file.
algorithm (str):
Clustering algorithm.
metric (str):
Similarity metric for clustering.
metric_threshold (float):
Similarity threshold.
tani (float):
Minimum tANI.
gani (float):
Minimum gANI.
ani (float):
Minimum ANI.
cov (float):
Minimum coverage (aligned fraction).
num_alns (int):