# Path: augur/utils.py
# class AugurException(Exception):
# class InvalidTreeError(Exception):
# def is_vcf(filename):
# def read_vcf(filename):
# def myopen(fname, mode):
# def get_json_name(args, default=None):
# def ambiguous_date_to_date_range(uncertain_date, fmt, min_max_year=None):
# def read_metadata(fname, query=None, as_data_frame=False):
# def is_date_ambiguous(date, ambiguous_by="any"):
# def get_numerical_date_from_value(value, fmt=None, min_max_year=None):
# def get_numerical_dates(meta_dict, name_col = None, date_col='date', fmt=None, min_max_year=None):
# def read_tree(fname, min_terminals=3):
# def read_node_data(fnames, tree=None):
# def write_json(data, file_name, indent=(None if os.environ.get("AUGUR_MINIFY_JSON") else 2), include_version=True):
# def load_features(reference, feature_names=None):
# def read_config(fname):
# def read_lat_longs(overrides=None, use_defaults=True):
#     def add_line_to_coordinates(line):
# def read_colors(overrides=None, use_defaults=True):
# def write_VCF_translation(prot_dict, vcf_file_name, ref_file_name):
# def run_shell_command(cmd, raise_errors=False, extra_env=None):
# def first_line(text):
# def available_cpu_cores(fallback: int = 1) -> int:
# def nthreads_value(value):
# def get_parent_name_by_child_name_for_tree(tree):
# def annotate_parents_for_tree(tree):
# def json_to_tree(json_dict, root=True):
# def get_augur_version():
# def read_bed_file(bed_file):
# def read_mask_file(mask_file):
# def load_mask_sites(mask_file):
# def read_strains(*files, comment_char="#"):
#     T = None
#             T = Bio.Phylo.read(fname, fmt)
#                 T = None
# VALID_NUCLEOTIDES = { # http://reverse-complement.com/ambiguity.html
#     "A", "G", "C", "T", "U", "N", "R", "Y", "S", "W", "K", "M", "B", "V", "D", "H", "-",
#     "a", "g", "c", "t", "u", "n", "r", "y", "s", "w", "k", "m", "b", "v", "d", "h", "-"
# }


import os
import numpy as np
from shutil import copyfile
from Bio import AlignIO, SeqIO, Seq, Align
from .utils import run_shell_command, nthreads_value, shquote
from collections import defaultdict
    if existing_alignment:
        if ref_name not in {x.name for x in existing_alignment}:
            raise AlignmentError("ERROR: Specified reference name %s (via --reference-name) is not in the supplied alignment."%ref_name)
    else:
        if ref_name not in {x.name for x in seqs}:
            raise AlignmentError("ERROR: Specified reference name %s (via --reference-name) is not in the sequence sample."%ref_name)


    # align
    # if args.method=='mafft':
    #     shoutput = shquote(output)
    #     shname = shquote(seq_fname)
    #     cmd = "mafft --reorder --anysymbol --thread %d %s 1> %s 2> %s.log"%(args.nthreads, shname, shoutput, shoutput)

def read_reference(ref_fname):
    if not os.path.isfile(ref_fname):
        raise AlignmentError("ERROR: Cannot read reference sequence."
                             "\n\tmake sure the file \"%s\" exists"%ref_fname)
    try:
        ref_seq = SeqIO.read(ref_fname, 'genbank' if ref_fname.split('.')[-1] in ['gb', 'genbank'] else 'fasta')
    except:
        raise AlignmentError("ERROR: Cannot read reference sequence."
                "\n\tmake sure the file %s contains one sequence in genbank or fasta format"%ref_fname)
    return ref_seq

def generate_alignment_cmd(method, nthreads, existing_aln_fname, seqs_to_align_fname, aln_fname, log_fname):
    if method=='mafft':
        if existing_aln_fname:
            cmd = "mafft --add %s --keeplength --reorder --anysymbol --nomemsave --adjustdirection --thread %d %s 1> %s 2> %s"%(shquote(seqs_to_align_fname), nthreads, shquote(existing_aln_fname), shquote(aln_fname), shquote(log_fname))
        else:

# Path: augur/utils.py
# class AugurException(Exception):
# class InvalidTreeError(Exception):
# def is_vcf(filename):
# def read_vcf(filename):
# def myopen(fname, mode):
# def get_json_name(args, default=None):
# def ambiguous_date_to_date_range(uncertain_date, fmt, min_max_year=None):
# def read_metadata(fname, query=None, as_data_frame=False):
# def is_date_ambiguous(date, ambiguous_by="any"):
# def get_numerical_date_from_value(value, fmt=None, min_max_year=None):
# def get_numerical_dates(meta_dict, name_col = None, date_col='date', fmt=None, min_max_year=None):
# def read_tree(fname, min_terminals=3):
# def read_node_data(fnames, tree=None):
# def write_json(data, file_name, indent=(None if os.environ.get("AUGUR_MINIFY_JSON") else 2), include_version=True):
# def load_features(reference, feature_names=None):
# def read_config(fname):
# def read_lat_longs(overrides=None, use_defaults=True):
#     def add_line_to_coordinates(line):
# def read_colors(overrides=None, use_defaults=True):
# def write_VCF_translation(prot_dict, vcf_file_name, ref_file_name):
# def run_shell_command(cmd, raise_errors=False, extra_env=None):
# def first_line(text):
# def available_cpu_cores(fallback: int = 1) -> int:
# def nthreads_value(value):
# def get_parent_name_by_child_name_for_tree(tree):
# def annotate_parents_for_tree(tree):
# def json_to_tree(json_dict, root=True):
# def get_augur_version():
# def read_bed_file(bed_file):
# def read_mask_file(mask_file):
# def load_mask_sites(mask_file):
# def read_strains(*files, comment_char="#"):
#     T = None
#             T = Bio.Phylo.read(fname, fmt)
#                 T = None
# VALID_NUCLEOTIDES = { # http://reverse-complement.com/ambiguity.html
#     "A", "G", "C", "T", "U", "N", "R", "Y", "S", "W", "K", "M", "B", "V", "D", "H", "-",
#     "a", "g", "c", "t", "u", "n", "r", "y", "s", "w", "k", "m", "b", "v", "d", "h", "-"
# }


# Path: augur/align.py
import os
import numpy as np
from shutil import copyfile
from Bio import AlignIO, SeqIO, Seq, Align
from .utils import run_shell_command, nthreads_value, shquote
from collections import defaultdict

    if existing_alignment:
        if ref_name not in {x.name for x in existing_alignment}:
            raise AlignmentError("ERROR: Specified reference name %s (via --reference-name) is not in the supplied alignment."%ref_name)
    else:
        if ref_name not in {x.name for x in seqs}:
            raise AlignmentError("ERROR: Specified reference name %s (via --reference-name) is not in the sequence sample."%ref_name)


    # align
    # if args.method=='mafft':
    #     shoutput = shquote(output)
    #     shname = shquote(seq_fname)
    #     cmd = "mafft --reorder --anysymbol --thread %d %s 1> %s 2> %s.log"%(args.nthreads, shname, shoutput, shoutput)

def read_reference(ref_fname):
    if not os.path.isfile(ref_fname):
        raise AlignmentError("ERROR: Cannot read reference sequence."
                             "\n\tmake sure the file \"%s\" exists"%ref_fname)
    try:
        ref_seq = SeqIO.read(ref_fname, 'genbank' if ref_fname.split('.')[-1] in ['gb', 'genbank'] else 'fasta')
    except:
        raise AlignmentError("ERROR: Cannot read reference sequence."
                "\n\tmake sure the file %s contains one sequence in genbank or fasta format"%ref_fname)
    return ref_seq

def generate_alignment_cmd(method, nthreads, existing_aln_fname, seqs_to_align_fname, aln_fname, log_fname):
    if method=='mafft':
        if existing_aln_fname:
            cmd = "mafft --add %s --keeplength --reorder --anysymbol --nomemsave --adjustdirection --thread %d %s 1> %s 2> %s"%(shquote(seqs_to_align_fname), nthreads, shquote(existing_aln_fname), shquote(aln_fname), shquote(log_fname))
        else:

            cmd = "mafft --reorder --anysymbol --nomemsave --adjustdirection --thread %d %s 1> %s 2> %s"%(nthreads, shquote(seqs_to_align_fname), shquote(aln_fname), shquote(log_fname))