File: average_nucleotide_identity.py

package info (click to toggle)
python-pyani 0.2.10-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 159,800 kB
  • sloc: python: 3,111; makefile: 86; sh: 30
file content (981 lines) | stat: -rwxr-xr-x 36,320 bytes parent folder | download
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (c) The James Hutton Institute 2013-2019
# (c) University of Strathclyde 2019-2020
# Author: Leighton Pritchard
#
# Contact: leighton.pritchard@strath.ac.uk
#
# Leighton Pritchard,
# Strathclyde Institute for Pharmacy and Biomedical Sciences,
# Cathedral Street,
# Glasgow,
# G4 0RE
# Scotland,
# UK
#
# The MIT License
#
# Copyright (c) 2013-2019 The James Hutton Institute
# Copyright (c) 2019-2020 University of Strathclyde
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Provides average_nucleotide_identity.py script.

This script calculates Average Nucleotide Identity (ANI) according to one of
a number of alternative methods described in, e.g.

Richter M, Rossello-Mora R (2009) Shifting the genomic gold standard for the
prokaryotic species definition. Proc Natl Acad Sci USA 106: 19126-19131.
doi:10.1073/pnas.0906412106. (ANI1020, ANIm, ANIb)

Goris J, Konstantinidis KT, Klappenbach JA, Coenye T, Vandamme P, et al.
(2007) DNA-DNA hybridization values and their relationship to whole-genome
sequence similarities. Int J Syst Evol Micr 57: 81-91.
doi:10.1099/ijs.0.64483-0.

ANI is proposed to be the appropriate in silico substitute for DNA-DNA
hybridisation (DDH), and so useful for delineating species boundaries. A
typical percentage threshold for species boundary in the literature is 95%
ANI (e.g. Richter et al. 2009).

All ANI methods follow the basic algorithm:
- Align the genome of organism 1 against that of organism 2, and identify
  the matching regions
- Calculate the percentage nucleotide identity of the matching regions, as
  an average for all matching regions
Methods differ on: (1) what alignment algorithm is used, and the choice of
parameters (this affects the aligned region boundaries); (2) what the input
is for alignment (typically either fragments of fixed size, or the most
complete assembly available); (3) whether a reciprocal comparison is
necessary or desirable.

ANIm: uses MUMmer (NUCmer) to align the input sequences.
ANIb: uses BLASTN to align 1000nt fragments of the input sequences
TETRA: calculates tetranucleotide frequencies of each input sequence

This script takes as main input a directory containing a set of
correctly-formatted FASTA multiple sequence files. All sequences for a
single organism should be contained in only one sequence file. The names of
these files are used for identification, so it would be advisable to name
them sensibly.

Output is written to a named directory. The output files differ depending on
the chosen ANI method.

ANIm: MUMmer/NUCmer .delta files, describing the sequence
      alignment; tab-separated format plain text tables describing total
      alignment lengths, and total alignment percentage identity

ANIb: FASTA sequences describing 1000nt fragments of each input sequence;
      BLAST nucleotide databases - one for each set of fragments; and BLASTN
      output files (tab-separated tabular format plain text) - one for each
      pairwise comparison of input sequences. There are potentially a lot of
      intermediate files.

TETRA: Tab-separated text file describing the Z-scores for each
       tetranucleotide in each input sequence.

In addition, all methods produce a table of output percentage identity (ANIm
and ANIb) or correlation (TETRA), between each sequence.

If graphical output is chosen, the output directory will also contain PDF
files representing the similarity between sequences as a heatmap with
row and column dendrograms.

DEPENDENCIES
============

o Biopython (http://www.biopython.org)

o BLAST+ executable in the $PATH, or available on the command line (ANIb)
       (ftp://ftp.ncbi.nlm.nih.gov/blast/executables/blast+/LATEST/)

o MUMmer executables in the $PATH, or available on the command line (ANIm)
       (http://mummer.sourceforge.net/)

For graphical output
--------------------

o R with shared libraries installed on the system, for graphical output
      (http://cran.r-project.org/)

o Rpy2 (http://rpy.sourceforge.net/rpy2.html)


USAGE
=====

calculate_ani.py [options]

Options:
  -h, --help            show this help message and exit
  -o OUTDIRNAME, --outdir=OUTDIRNAME
                        Output directory
  -i INDIRNAME, --indir=INDIRNAME
                        Input directory name
  -v, --verbose         Give verbose output
  -f, --force           Force file overwriting
  -s, --fragsize        Sequence fragment size for ANIb
  --skip_nucmer         Skip NUCmer runs, for testing (e.g. if output already
                        present)
  --skip_blast          Skip BLAST runs, for testing (e.g. if output already
                        present)
  --noclobber           Don't nuke existing files
  -g, --graphics        Generate heatmap of ANI
  -m METHOD, --method=METHOD
                        ANI method
  --maxmatch            Override MUMmer settings and allow all matches in
                        NUCmer
  --nucmer_exe=NUCMER_EXE
                        Path to NUCmer executable
  --blast_exe=BLAST_EXE
                        Path to BLASTN+ executable
  --makeblastdb_exe=MAKEBLASTDB_EXE
                        Path to BLAST+ makeblastdb executable
"""

import json
import logging
import logging.handlers
import os
import pandas as pd
import random
import shutil
import sys
import tarfile
import time
import traceback

from argparse import ArgumentParser

from pyani import (
    anib,
    anim,
    tetra,
    pyani_config,
    pyani_files,
    pyani_graphics,
    pyani_tools,
)
from pyani import run_multiprocessing as run_mp
from pyani import run_sge
from pyani.pyani_config import params_mpl, ALIGNDIR, FRAGSIZE, TETRA_FILESTEMS
from pyani import __version__ as VERSION


# Process command-line arguments
def parse_cmdline():
    """Parse command-line arguments for script."""
    parser = ArgumentParser(prog="average_nucleotide_identity.py")
    parser.add_argument(
        "--version", action="version", version="%(prog)s: pyani " + VERSION
    )
    parser.add_argument(
        "-o",
        "--outdir",
        dest="outdirname",
        action="store",
        default=None,
        required=True,
        help="Output directory (required)",
    )
    parser.add_argument(
        "-i",
        "--indir",
        dest="indirname",
        action="store",
        default=None,
        required=True,
        help="Input directory name (required)",
    )
    parser.add_argument(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="Give verbose output",
    )
    parser.add_argument(
        "-f",
        "--force",
        dest="force",
        action="store_true",
        default=False,
        help="Force file overwriting",
    )
    parser.add_argument(
        "-s",
        "--fragsize",
        dest="fragsize",
        action="store",
        default=FRAGSIZE,
        type=int,
        help="Sequence fragment size for ANIb " "(default %i)" % FRAGSIZE,
    )
    parser.add_argument(
        "-l",
        "--logfile",
        dest="logfile",
        action="store",
        default=None,
        help="Logfile location",
    )
    parser.add_argument(
        "--skip_nucmer",
        dest="skip_nucmer",
        action="store_true",
        default=False,
        help="Skip NUCmer runs, for testing " + "(e.g. if output already present)",
    )
    parser.add_argument(
        "--skip_blastn",
        dest="skip_blastn",
        action="store_true",
        default=False,
        help="Skip BLASTN runs, for testing " + "(e.g. if output already present)",
    )
    parser.add_argument(
        "--noclobber",
        dest="noclobber",
        action="store_true",
        default=False,
        help="Don't nuke existing files",
    )
    parser.add_argument(
        "--nocompress",
        dest="nocompress",
        action="store_true",
        default=False,
        help="Don't compress/delete the comparison output",
    )
    parser.add_argument(
        "-g",
        "--graphics",
        dest="graphics",
        action="store_true",
        default=False,
        help="Generate heatmap of ANI",
    )
    parser.add_argument(
        "--gformat",
        dest="gformat",
        action="store",
        default="pdf,png,eps",
        help="Graphics output format(s) [pdf|png|jpg|svg] "
        "(default pdf,png,eps meaning three file formats)",
    )
    parser.add_argument(
        "--gmethod",
        dest="gmethod",
        action="store",
        default="mpl",
        choices=["mpl", "seaborn"],
        help="Graphics output method (default mpl)",
    )
    parser.add_argument(
        "--labels",
        dest="labels",
        action="store",
        default=None,
        help="Path to file containing sequence labels",
    )
    parser.add_argument(
        "--classes",
        dest="classes",
        action="store",
        default=None,
        help="Path to file containing sequence classes",
    )
    parser.add_argument(
        "-m",
        "--method",
        dest="method",
        action="store",
        default="ANIm",
        choices=["ANIm", "ANIb", "ANIblastall", "TETRA"],
        help="ANI method (default ANIm)",
    )
    parser.add_argument(
        "--scheduler",
        dest="scheduler",
        action="store",
        default="multiprocessing",
        choices=["multiprocessing", "SGE"],
        help="Job scheduler (default multiprocessing, i.e. locally)",
    )
    parser.add_argument(
        "--workers",
        dest="workers",
        action="store",
        default=None,
        type=int,
        help="Number of worker processes for multiprocessing "
        "(default zero, meaning use all available cores)",
    )
    parser.add_argument(
        "--SGEgroupsize",
        dest="sgegroupsize",
        action="store",
        default=10000,
        type=int,
        help="Number of jobs to place in an SGE array group " "(default 10000)",
    )
    parser.add_argument(
        "--SGEargs",
        dest="sgeargs",
        action="store",
        default=None,
        type=str,
        help="Additional arguments for qsub",
    )
    parser.add_argument(
        "--maxmatch",
        dest="maxmatch",
        action="store_true",
        default=False,
        help="Override MUMmer to allow all NUCmer matches",
    )
    parser.add_argument(
        "--nucmer_exe",
        dest="nucmer_exe",
        action="store",
        default=pyani_config.NUCMER_DEFAULT,
        help="Path to NUCmer executable",
    )
    parser.add_argument(
        "--filter_exe",
        dest="filter_exe",
        action="store",
        default=pyani_config.FILTER_DEFAULT,
        help="Path to delta-filter executable",
    )
    parser.add_argument(
        "--blastn_exe",
        dest="blastn_exe",
        action="store",
        default=pyani_config.BLASTN_DEFAULT,
        help="Path to BLASTN+ executable",
    )
    parser.add_argument(
        "--makeblastdb_exe",
        dest="makeblastdb_exe",
        action="store",
        default=pyani_config.MAKEBLASTDB_DEFAULT,
        help="Path to BLAST+ makeblastdb executable",
    )
    parser.add_argument(
        "--blastall_exe",
        dest="blastall_exe",
        action="store",
        default=pyani_config.BLASTALL_DEFAULT,
        help="Path to BLASTALL executable",
    )
    parser.add_argument(
        "--formatdb_exe",
        dest="formatdb_exe",
        action="store",
        default=pyani_config.FORMATDB_DEFAULT,
        help="Path to BLAST formatdb executable",
    )
    parser.add_argument(
        "--write_excel",
        dest="write_excel",
        action="store_true",
        default=False,
        help="Write Excel format output tables",
    )
    parser.add_argument(
        "--rerender",
        dest="rerender",
        action="store_true",
        default=False,
        help="Rerender graphics output without recalculation",
    )
    parser.add_argument(
        "--subsample",
        dest="subsample",
        action="store",
        default=None,
        help="Subsample a percentage [0-1] or specific "
        + "number (1-n) of input sequences",
    )
    parser.add_argument(
        "--seed",
        dest="seed",
        action="store",
        default=None,
        help="Set random seed for reproducible subsampling.",
    )
    parser.add_argument(
        "--jobprefix",
        dest="jobprefix",
        action="store",
        default="ANI",
        help="Prefix for SGE jobs (default ANI).",
    )
    return parser.parse_args()


# Report last exception as string
def last_exception():
    """Return last exception as a string, or use in logging."""
    exc_type, exc_value, exc_traceback = sys.exc_info()
    return "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))


# Create output directory if it doesn't exist
def make_outdir():
    """Make the output directory, if required.

    This is a little involved.  If the output directory already exists,
    we take the safe option by default, and stop with an error.  We can,
    however, choose to force the program to go on, in which case we can
    either clobber the existing directory, or not.  The options turn out
    as the following, if the directory exists:

    DEFAULT: stop and report the collision
    FORCE: continue, and remove the existing output directory
    NOCLOBBER+FORCE: continue, but do not remove the existing output
    """
    if os.path.exists(args.outdirname):
        if not args.force:
            logger.error(
                "Output directory %s would overwrite existing files (exiting)",
                args.outdirname,
            )
            sys.exit(1)
        elif args.noclobber:
            logger.warning(
                "NOCLOBBER: not actually deleting directory %s", args.outdirname
            )
        else:
            logger.info(
                "Removing directory %s and everything below it", args.outdirname
            )
            shutil.rmtree(args.outdirname)
    logger.info("Creating directory %s", args.outdirname)
    try:
        os.makedirs(args.outdirname)  # We make the directory recursively
        # Depending on the choice of method, a subdirectory will be made for
        # alignment output files
        if args.method != "TETRA":
            os.makedirs(os.path.join(args.outdirname, ALIGNDIR[args.method]))
    except OSError:
        # This gets thrown if the directory exists. If we've forced overwrite/
        # delete and we're not clobbering, we let things slide
        if args.noclobber and args.force:
            logger.info("NOCLOBBER+FORCE: not creating directory")
        else:
            logger.error(last_exception)
            sys.exit(1)


# Compress output directory and delete it
def compress_delete_outdir(outdir):
    """Compress the contents of the passed directory to .tar.gz and delete."""
    # Compress output in .tar.gz file and remove raw output
    tarfn = outdir + ".tar.gz"
    logger.info("\tCompressing output from %s to %s", outdir, tarfn)
    with tarfile.open(tarfn, "w:gz") as fh:
        fh.add(outdir)
    logger.info("\tRemoving output directory %s", outdir)
    shutil.rmtree(outdir)


# Calculate ANIm for input
def calculate_anim(infiles, org_lengths):
    """Returns ANIm result dataframes for files in input directory.

    - infiles - paths to each input file
    - org_lengths - dictionary of input sequence lengths, keyed by sequence

    Finds ANI by the ANIm method, as described in Richter et al (2009)
    Proc Natl Acad Sci USA 106: 19126-19131 doi:10.1073/pnas.0906412106.

    All FASTA format files (selected by suffix) in the input directory
    are compared against each other, pairwise, using NUCmer (which must
    be in the path). NUCmer output is stored in the output directory.

    The NUCmer .delta file output is parsed to obtain an alignment length
    and similarity error count for every unique region alignment between
    the two organisms, as represented by the sequences in the FASTA files.

    These are processed to give matrices of aligned sequence lengths,
    average nucleotide identity (ANI) percentages, coverage (aligned
    percentage of whole genome), and similarity error cound for each pairwise
    comparison.
    """
    logger.info("Running ANIm")
    logger.info("Generating NUCmer command-lines")
    deltadir = os.path.join(args.outdirname, ALIGNDIR["ANIm"])
    logger.info("Writing nucmer output to %s", deltadir)
    # Schedule NUCmer runs
    if not args.skip_nucmer:
        joblist = anim.generate_nucmer_jobs(
            infiles,
            args.outdirname,
            nucmer_exe=args.nucmer_exe,
            filter_exe=args.filter_exe,
            maxmatch=args.maxmatch,
            jobprefix=args.jobprefix,
        )
        if args.scheduler == "multiprocessing":
            logger.info("Running jobs with multiprocessing")
            if args.workers is None:
                logger.info("(using maximum number of available worker threads)")
            else:
                logger.info("(using %d worker threads, if available)", args.workers)
            cumval = run_mp.run_dependency_graph(
                joblist, workers=args.workers, logger=logger
            )
            logger.info("Cumulative return value: %d", cumval)
            if 0 < cumval:
                logger.warning("At least one NUCmer comparison failed. ANIm may fail.")
            else:
                logger.info("All multiprocessing jobs complete.")
        else:
            logger.info("Running jobs with SGE")
            logger.info("Jobarray group size set to %d", args.sgegroupsize)
            run_sge.run_dependency_graph(
                joblist,
                logger=logger,
                jgprefix=args.jobprefix,
                sgegroupsize=args.sgegroupsize,
                sgeargs=args.sgeargs,
            )
    else:
        logger.warning("Skipping NUCmer run (as instructed)!")

    # Process resulting .delta files
    logger.info("Processing NUCmer .delta files.")
    results = anim.process_deltadir(deltadir, org_lengths, logger=logger)
    if results.zero_error:  # zero percentage identity error
        if not args.skip_nucmer and args.scheduler == "multiprocessing":
            if 0 < cumval:
                logger.error(
                    "This has possibly been a NUCmer run failure, please investigate"
                )
                logger.error(last_exception())
                sys.exit(1)
            else:
                logger.error(
                    (
                        "This is possibly due to a NUCmer comparison being too "
                        "distant for use. Please consider using the --maxmatch option."
                    )
                )
                logger.error(
                    (
                        "This is alternatively due to NUCmer run failure, "
                        "analysis will continue, but please investigate."
                    )
                )
    if not args.nocompress:
        logger.info("Compressing/deleting %s", deltadir)
        compress_delete_outdir(deltadir)

    # Return processed data from .delta files
    return results


# Calculate TETRA for input
def calculate_tetra(infiles):
    """Calculate TETRA for files in input directory.

    - infiles - paths to each input file
    - org_lengths - dictionary of input sequence lengths, keyed by sequence

    Calculates TETRA correlation scores, as described in:

    Richter M, Rossello-Mora R (2009) Shifting the genomic gold standard for
    the prokaryotic species definition. Proc Natl Acad Sci USA 106:
    19126-19131. doi:10.1073/pnas.0906412106.

    and

    Teeling et al. (2004) Application of tetranucleotide frequencies for the
    assignment of genomic fragments. Env. Microbiol. 6(9): 938-947.
    doi:10.1111/j.1462-2920.2004.00624.x
    """
    logger.info("Running TETRA.")
    # First, find Z-scores
    logger.info("Calculating TETRA Z-scores for each sequence.")
    tetra_zscores = {}
    for filename in infiles:
        logger.info("Calculating TETRA Z-scores for %s", filename)
        org = os.path.splitext(os.path.split(filename)[-1])[0]
        tetra_zscores[org] = tetra.calculate_tetra_zscore(filename)
    # Then calculate Pearson correlation between Z-scores for each sequence
    logger.info("Calculating TETRA correlation scores.")
    tetra_correlations = tetra.calculate_correlations(tetra_zscores)
    return tetra_correlations


# Calculate ANIb for input
def unified_anib(infiles, org_lengths):
    """Calculate ANIb for files in input directory.

    - infiles - paths to each input file
    - org_lengths - dictionary of input sequence lengths, keyed by sequence

    Calculates ANI by the ANIb method, as described in Goris et al. (2007)
    Int J Syst Evol Micr 57: 81-91. doi:10.1099/ijs.0.64483-0. There are
    some minor differences depending on whether BLAST+ or legacy BLAST
    (BLASTALL) methods are used.

    All FASTA format files (selected by suffix) in the input directory are
    used to construct BLAST databases, placed in the output directory.
    Each file's contents are also split into sequence fragments of length
    options.fragsize, and the multiple FASTA file that results written to
    the output directory. These are BLASTNed, pairwise, against the
    databases.

    The BLAST output is interrogated for all fragment matches that cover
    at least 70% of the query sequence, with at least 30% nucleotide
    identity over the full length of the query sequence. This is an odd
    choice and doesn't correspond to the twilight zone limit as implied by
    Goris et al. We persist with their definition, however.  Only these
    qualifying matches contribute to the total aligned length, and total
    aligned sequence identity used to calculate ANI.

    The results are processed to give matrices of aligned sequence length
    (aln_lengths.tab), similarity error counts (sim_errors.tab), ANIs
    (perc_ids.tab), and minimum aligned percentage (perc_aln.tab) of
    each genome, for each pairwise comparison. These are written to the
    output directory in plain text tab-separated format.
    """
    logger.info("Running %s", args.method)
    blastdir = os.path.join(args.outdirname, ALIGNDIR[args.method])
    logger.info("Writing BLAST output to %s", blastdir)
    # Build BLAST databases and run pairwise BLASTN
    if not args.skip_blastn:
        # Make sequence fragments
        logger.info("Fragmenting input files, and writing to %s", args.outdirname)
        # Fraglengths does not get reused with BLASTN
        fragfiles, fraglengths = anib.fragment_fasta_files(
            infiles, blastdir, args.fragsize
        )
        # Export fragment lengths as JSON, in case we re-run with --skip_blastn
        with open(os.path.join(blastdir, "fraglengths.json"), "w") as outfile:
            json.dump(fraglengths, outfile)

        # Which executables are we using?
        # if args.method == "ANIblastall":
        #    format_exe = args.formatdb_exe
        #    blast_exe = args.blastall_exe
        # else:
        #    format_exe = args.makeblastdb_exe
        #    blast_exe = args.blastn_exe

        # Run BLAST database-building and executables from a jobgraph
        logger.info("Creating job dependency graph")
        jobgraph = anib.make_job_graph(
            infiles, fragfiles, anib.make_blastcmd_builder(args.method, blastdir)
        )
        # jobgraph = anib.make_job_graph(infiles, fragfiles, blastdir,
        #                               format_exe, blast_exe, args.method,
        #                               jobprefix=args.jobprefix)
        if args.scheduler == "multiprocessing":
            logger.info("Running jobs with multiprocessing")
            logger.info("Running job dependency graph")
            if args.workers is None:
                logger.info("(using maximum number of available worker threads)")
            else:
                logger.info("(using %d worker threads, if available)", args.workers)
            cumval = run_mp.run_dependency_graph(
                jobgraph, workers=args.workers, logger=logger
            )
            if 0 < cumval:
                logger.warning(
                    "At least one BLAST run failed. %s may fail.", args.method
                )
            else:
                logger.info("All multiprocessing jobs complete.")
        else:
            run_sge.run_dependency_graph(jobgraph, logger=logger)
            logger.info("Running jobs with SGE")
    else:
        # Import fragment lengths from JSON
        if args.method == "ANIblastall":
            with open(os.path.join(blastdir, "fraglengths.json"), "rU") as infile:
                fraglengths = json.load(infile)
        else:
            fraglengths = None
        logger.warning("Skipping BLASTN runs (as instructed)!")

    # Process pairwise BLASTN output
    logger.info("Processing pairwise %s BLAST output.", args.method)
    try:
        data = anib.process_blast(
            blastdir, org_lengths, fraglengths=fraglengths, mode=args.method
        )
    except ZeroDivisionError:
        logger.error("One or more BLAST output files has a problem.")
        if not args.skip_blastn:
            if 0 < cumval:
                logger.error(
                    "This is possibly due to BLASTN run failure, please investigate"
                )
            else:
                logger.error(
                    "This is possibly due to a BLASTN comparison being too distant for use."
                )
        logger.error(last_exception())
    if not args.nocompress:
        logger.info("Compressing/deleting %s", blastdir)
        compress_delete_outdir(blastdir)

    # Return processed BLAST data
    return data


# Write ANIb/ANIm/TETRA output
def write(results):
    """Write ANIb/ANIm/TETRA results to output directory.

    - results - results object from analysis

    Each dataframe is written to an Excel-format file (if args.write_excel is
    True), and plain text tab-separated file in the output directory. The
    order of result output must be reflected in the order of filestems.
    """
    logger.info("Writing %s results to %s", args.method, args.outdirname)
    if args.method == "TETRA":
        out_excel = os.path.join(args.outdirname, TETRA_FILESTEMS[0]) + ".xlsx"
        out_csv = os.path.join(args.outdirname, TETRA_FILESTEMS[0]) + ".tab"
        if args.write_excel:
            results.to_excel(out_excel, index=True)
        results.to_csv(out_csv, index=True, sep="\t")

    else:
        for dfr, filestem in results.data:
            out_excel = os.path.join(args.outdirname, filestem) + ".xlsx"
            out_csv = os.path.join(args.outdirname, filestem) + ".tab"
            logger.info("\t%s", filestem)
            if args.write_excel:
                dfr.to_excel(out_excel, index=True)
            dfr.to_csv(out_csv, index=True, sep="\t")


# Draw ANIb/ANIm/TETRA output
def draw(filestems, gformat):
    """Draw ANIb/ANIm/TETRA results.

    - filestems - filestems for output files
    - gformat - the format for output graphics
    """
    # Draw heatmaps
    for filestem in filestems:
        fullstem = os.path.join(args.outdirname, filestem)
        outfilename = fullstem + ".%s" % gformat
        infilename = fullstem + ".tab"
        # As some people want to provide input files whose names look like
        # floating point numbers, we need to guard against pandas interpreting
        # them as such, and creating a Float64Index. This requires us to read
        #  the .csv as if it had no index, specify column 0 as string datatype,
        # then reindex the dataframe with that column.
        df = pd.read_csv(infilename, sep="\t", dtype={"Unnamed: 0": str})
        df.set_index("Unnamed: 0", inplace=True)
        df = df.reindex(df.index.rename("Genomes"))
        logger.info("Writing heatmap to %s", outfilename)
        params = pyani_graphics.Params(
            params_mpl(df)[filestem],
            pyani_tools.get_labels(args.labels, logger=logger),
            pyani_tools.get_labels(args.classes, logger=logger),
        )
        if args.gmethod == "mpl":
            pyani_graphics.heatmap_mpl(
                df, outfilename=outfilename, title=filestem, params=params
            )
        elif args.gmethod == "seaborn":
            pyani_graphics.heatmap_seaborn(
                df, outfilename=outfilename, title=filestem, params=params
            )


# Subsample the input files
def subsample_input(infiles):
    """Returns a random subsample of the input files.

    - infiles: a list of input files for analysis
    """
    logger.info("--subsample: %s", args.subsample)
    try:
        samplesize = float(args.subsample)
    except TypeError:  # Not a number
        logger.error(
            "--subsample must be int or float, got %s (exiting)", type(args.subsample)
        )
        sys.exit(1)
    if samplesize <= 0:  # Not a positive value
        logger.error("--subsample must be positive value, got %s", str(args.subsample))
        sys.exit(1)
    if int(samplesize) > 1:
        logger.info("Sample size integer > 1: %d", samplesize)
        k = min(int(samplesize), len(infiles))
    else:
        logger.info("Sample size proportion in (0, 1]: %.3f", samplesize)
        k = int(min(samplesize, 1.0) * len(infiles))
    logger.info("Randomly subsampling %d sequences for analysis", k)
    if args.seed:
        logger.info("Setting random seed with: %s", args.seed)
        random.seed(args.seed)
    else:
        logger.warning("Subsampling without specified random seed!")
        logger.warning("Subsampling may NOT be easily reproducible!")
    return random.sample(infiles, k)


# Run as script
if __name__ == "__main__":

    # Parse command-line
    args = parse_cmdline()

    # Set up logging
    logger = logging.getLogger("average_nucleotide_identity.py: %s" % time.asctime())
    t0 = time.time()
    logger.setLevel(logging.DEBUG)
    err_handler = logging.StreamHandler(sys.stderr)
    err_formatter = logging.Formatter("%(levelname)s: %(message)s")
    err_handler.setFormatter(err_formatter)

    # Was a logfile specified? If so, use it
    if args.logfile is not None:
        try:
            logstream = open(args.logfile, "w")
            err_handler_file = logging.StreamHandler(logstream)
            err_handler_file.setFormatter(err_formatter)
            err_handler_file.setLevel(logging.INFO)
            logger.addHandler(err_handler_file)
        except IOError:
            logger.error("Could not open %s for logging", args.logfile)
            sys.exit(1)

    # Do we need verbosity?
    if args.verbose:
        err_handler.setLevel(logging.INFO)
    else:
        err_handler.setLevel(logging.WARNING)
    logger.addHandler(err_handler)

    # Report arguments, if verbose
    logger.info("pyani version: %s", VERSION)
    logger.info(args)
    logger.info("command-line: %s", " ".join(sys.argv))

    # Have we got an input and output directory? If not, exit.
    if args.indirname is None:
        logger.error("No input directory name (exiting)")
        sys.exit(1)
    logger.info("Input directory: %s", args.indirname)
    if args.outdirname is None:
        logger.error("No output directory name (exiting)")
        sys.exit(1)
    if args.rerender:  # Rerendering, we want to overwrite graphics
        args.force, args.noclobber = True, True
    make_outdir()
    logger.info("Output directory: %s", args.outdirname)

    # Check for the presence of space characters in any of the input filenames
    # or output directory. If we have any, abort here and now.
    filenames = [args.outdirname] + os.listdir(args.indirname)
    for fname in filenames:
        if " " in os.path.abspath(fname):
            logger.error("File or directory '%s' contains whitespace", fname)
            logger.error("This will cause issues with MUMmer and BLAST")
            logger.error("(exiting)")
            sys.exit(1)

    if args.labels and not os.path.isfile(args.labels):
        logger.error("Missing labels file: %s", args.labels)
        sys.exit(1)
    if args.classes and not os.path.isfile(args.classes):
        logger.error("Missing classes file: %s", args.classes)
        sys.exit(1)

    # Have we got a valid method choice?
    # Dictionary below defines analysis function, and output presentation
    # functions/settings, dependent on selected method.
    methods = {
        "ANIm": (calculate_anim, pyani_config.ANIM_FILESTEMS),
        "ANIb": (unified_anib, pyani_config.ANIB_FILESTEMS),
        "TETRA": (calculate_tetra, pyani_config.TETRA_FILESTEMS),
        "ANIblastall": (unified_anib, pyani_config.ANIBLASTALL_FILESTEMS),
    }
    if args.method not in methods:
        logger.error("ANI method %s not recognised (exiting)", args.method)
        logger.error("Valid methods are: %s", list(methods.keys()))
        sys.exit(1)
    logger.info("Using ANI method: %s", args.method)

    # Skip calculations (or not) depending on rerender option
    if args.rerender:
        logger.warning("--rerender option used")
        logger.warning("Producing graphics with no new recalculations")
    else:
        # Have we got a valid scheduler choice?
        schedulers = ["multiprocessing", "SGE"]
        if args.scheduler not in schedulers:
            logger.error("scheduler %s not recognised (exiting)", args.scheduler)
            logger.error("Valid schedulers are: %s", "; ".join(schedulers))
            sys.exit(1)
        logger.info("Using scheduler method: %s", args.scheduler)

        # Get input files
        logger.info("Identifying FASTA files in %s", args.indirname)
        infiles = pyani_files.get_fasta_files(args.indirname)
        logger.info("Input files:\n\t%s", "\n\t".join(infiles))

        # Are we subsampling? If so, make the selection here
        if args.subsample:
            infiles = subsample_input(infiles)
            logger.info("Sampled input files:\n\t%s", "\n\t".join(infiles))

        # Get lengths of input sequences
        logger.info("Processing input sequence lengths")
        org_lengths = pyani_files.get_sequence_lengths(infiles)
        logstr = "Sequence lengths:\n" + os.linesep.join(
            ["\t%s: %d" % (k, v) for k, v in list(org_lengths.items())]
        )
        logger.info(logstr)

        # Run appropriate method on the contents of the input directory,
        # and write out corresponding results.
        logger.info("Carrying out %s analysis", args.method)
        if args.method == "TETRA":
            results = methods[args.method][0](infiles)
        else:
            results = methods[args.method][0](infiles, org_lengths)
        write(results)

    # Do we want graphical output?
    if args.graphics or args.rerender:
        logger.info("Rendering output graphics")
        logger.info("Formats requested: %s", args.gformat)
        for gfmt in args.gformat.split(","):
            logger.info("Graphics format: %s", gfmt)
            logger.info("Graphics method: %s", args.gmethod)
            draw(methods[args.method][1], gfmt)

    # Report that we've finished
    logger.info("Done: %s.", time.asctime())
    logger.info("Time taken: %.2fs", (time.time() - t0))