# Path: riboSeed/shared_methods.py
# def set_up_logging(verbosity, outfile, name):
#     """
#     Set up logging a la pyani, with
#     a little help from:
#     https://aykutakin.wordpress.com/2013/08/06/
#         logging-to-console-and-file-in-python/
#     requires logging, os, sys, time
#     and some coloring
#     logs debug level to file, and [verbosity] level to stderr
#     return a logger object
#     """
#     logger = logging.getLogger('root')
#     if (verbosity * 10) not in range(10, 60, 10):
#         raise ValueError('Invalid log level: %s' % verbosity)
#     # logging.basicConfig(level=logging.DEBUG)
#     logger.setLevel(logging.DEBUG)
#     logging.addLevelName(logging.DEBUG, "DBUG")
#     # create console handler and set level to given verbosity
#     console_err = logging.StreamHandler(sys.stderr)
#     console_err.setLevel(level=(verbosity * 10))
#     # console_err_format = logging.Formatter(
#     #     str("%(asctime)s " + name + " %(levelname).4s " +"%(message)s "),
#     #     "%H:%M:%S")
#     console_err_format = logging.Formatter(
#         str("%(asctime)s " + "%(levelname).4s" +" %(message)s"),
#         "%H:%M:%S")
#     console_err.setFormatter(console_err_format)
#     # set some pretty colors, shorten names of loggers to keep lines aligned
#     # sadly, this doesn't jive with log files (casue they cant display the col
#     # logging.addLevelName(logging.DEBUG, "\u001b[30m%s\033[1;0m" % "..")
#     # logging.addLevelName(logging.INFO,  "\u001b[32m%s\033[1;0m" % "--")
#     # logging.addLevelName(logging.WARNING, "\u001b[33m%s\033[1;0m" % "!!")
#     # logging.addLevelName(logging.ERROR, "\u001b[31m%s\033[1;0m" % "xx")
#     # logging.addLevelName(logging.CRITICAL, "\u001b[31m%s\033[1;0m" % "XX")
#     logger.addHandler(console_err)
#     # create debug file handler and set level to debug
#     try:
#         logfile_handler = logging.FileHandler(outfile, "w")
#         logfile_handler.setLevel(logging.DEBUG)
#         logfile_handler_formatter = \
#             logging.Formatter("%(asctime)s - %(levelname).4s - %(message)s")
#         logfile_handler.setFormatter(logfile_handler_formatter)
#         logger.addHandler(logfile_handler)
#     except Exception as e:
#         logger.error(e)
#         logger.error("Could not open %s for logging", outfile)
#         sys.exit(1)
#     logger.debug("Initializing logger")
#     logger.debug("logging at level %s", verbosity)
#     return logger
# 
# def make_barrnap_cmd(infasta, outgff, exe, thresh, kingdom, evalue=1e-06, threads=1):
#     """ construct a system call to barrnap
# 
#     Args:
#         infasta (str): path to fasta file
#         outgff (str): name of gff file to create
#         exe (str): path to system executable for barrnap
#         thresh (float): Proportional length threshold to reject prediction
#         kingdom (str): bac, euk, arc, or mito
#         threads (int): number of threads to use
#     Returns:
#         (str): command
# 
#     """
#     assert 1 >= thresh > 0 and thresh , "Thresh must be between 0 and 1!"
#     if exe.endswith("py"):
#         # ensure running python barrnap uses >3.5
#         pyexe = str(sys.executable + " ")
#     else:
#         pyexe = ""
#     cmd = "{0}{1} -k {2} {3} --reject {4} --threads {5} --evalue {6} > {7}".format(
#         pyexe,
#         exe,
#         kingdom,
#         infasta,
#         thresh,
#         threads,
#         evalue,
#         outgff
#         )
#     return cmd


    from line_profiler import LineProfiler
    from matplotlib import pyplot, patches
from .shared_methods import set_up_logging, make_barrnap_cmd
import sys
import os
import re
import random
import math
import glob
import subprocess
import argparse
import multiprocessing
    import matplotlib
import networkx as nx
def process_assembly_graph(args, fastg, output_root, PLOT, which_k, logger):
    # make a list of node objects, a adjacency matrix M, and a DiGRaph object G
    logger.info("Reading assembly graph: %s", fastg)
    node_list, G_dict, G = parse_fastg(f=fastg)
    if PLOT and args.MAKE_ADJACENCY_MATRIX:
        M = make_adjacency_matrix(G_dict)
        plot_adjacency_matrix(
            M, node_order=None, partitions=[], colors=[],
            outpath=os.path.join(output_root, "full_adjacency_matrix.pdf"))
        logger.info("Writing out adjacency graph")
        with open(os.path.join(args.output, "tab.txt"), "w") as o:
            for line in M:
                o.write("\t".join([str(x) for x in line]) + "\n")
    # alt nodes
    dic = {int(x.name): [int(y.name) for y in x.neighbor_list] for x in node_list}


    # run barrnap to find our rDNAs; first time trhough is to find "full" -
    # length genes, and the second run with the relaxed thresholds is for
    # finding partial genes
    barrnap_gff = os.path.join(output_root, "strict_barrnapped.gff")
    barrnap_gff_partial = os.path.join(output_root, "partial_barrnapped.gff")
    barrnap_cmd = make_barrnap_cmd(
        infasta=fastg,
        outgff=barrnap_gff,
        exe=args.barrnap_exe,
        threads=args.cores,
        thresh=args.barrnap_length_threshold,
        evalue=1e-06,
        kingdom="bac")

# Path: riboSeed/shared_methods.py
# def set_up_logging(verbosity, outfile, name):
#     """
#     Set up logging a la pyani, with
#     a little help from:
#     https://aykutakin.wordpress.com/2013/08/06/
#         logging-to-console-and-file-in-python/
#     requires logging, os, sys, time
#     and some coloring
#     logs debug level to file, and [verbosity] level to stderr
#     return a logger object
#     """
#     logger = logging.getLogger('root')
#     if (verbosity * 10) not in range(10, 60, 10):
#         raise ValueError('Invalid log level: %s' % verbosity)
#     # logging.basicConfig(level=logging.DEBUG)
#     logger.setLevel(logging.DEBUG)
#     logging.addLevelName(logging.DEBUG, "DBUG")
#     # create console handler and set level to given verbosity
#     console_err = logging.StreamHandler(sys.stderr)
#     console_err.setLevel(level=(verbosity * 10))
#     # console_err_format = logging.Formatter(
#     #     str("%(asctime)s " + name + " %(levelname).4s " +"%(message)s "),
#     #     "%H:%M:%S")
#     console_err_format = logging.Formatter(
#         str("%(asctime)s " + "%(levelname).4s" +" %(message)s"),
#         "%H:%M:%S")
#     console_err.setFormatter(console_err_format)
#     # set some pretty colors, shorten names of loggers to keep lines aligned
#     # sadly, this doesn't jive with log files (casue they cant display the col
#     # logging.addLevelName(logging.DEBUG, "\u001b[30m%s\033[1;0m" % "..")
#     # logging.addLevelName(logging.INFO,  "\u001b[32m%s\033[1;0m" % "--")
#     # logging.addLevelName(logging.WARNING, "\u001b[33m%s\033[1;0m" % "!!")
#     # logging.addLevelName(logging.ERROR, "\u001b[31m%s\033[1;0m" % "xx")
#     # logging.addLevelName(logging.CRITICAL, "\u001b[31m%s\033[1;0m" % "XX")
#     logger.addHandler(console_err)
#     # create debug file handler and set level to debug
#     try:
#         logfile_handler = logging.FileHandler(outfile, "w")
#         logfile_handler.setLevel(logging.DEBUG)
#         logfile_handler_formatter = \
#             logging.Formatter("%(asctime)s - %(levelname).4s - %(message)s")
#         logfile_handler.setFormatter(logfile_handler_formatter)
#         logger.addHandler(logfile_handler)
#     except Exception as e:
#         logger.error(e)
#         logger.error("Could not open %s for logging", outfile)
#         sys.exit(1)
#     logger.debug("Initializing logger")
#     logger.debug("logging at level %s", verbosity)
#     return logger
# 
# def make_barrnap_cmd(infasta, outgff, exe, thresh, kingdom, evalue=1e-06, threads=1):
#     """ construct a system call to barrnap
# 
#     Args:
#         infasta (str): path to fasta file
#         outgff (str): name of gff file to create
#         exe (str): path to system executable for barrnap
#         thresh (float): Proportional length threshold to reject prediction
#         kingdom (str): bac, euk, arc, or mito
#         threads (int): number of threads to use
#     Returns:
#         (str): command
# 
#     """
#     assert 1 >= thresh > 0 and thresh , "Thresh must be between 0 and 1!"
#     if exe.endswith("py"):
#         # ensure running python barrnap uses >3.5
#         pyexe = str(sys.executable + " ")
#     else:
#         pyexe = ""
#     cmd = "{0}{1} -k {2} {3} --reject {4} --threads {5} --evalue {6} > {7}".format(
#         pyexe,
#         exe,
#         kingdom,
#         infasta,
#         thresh,
#         threads,
#         evalue,
#         outgff
#         )
#     return cmd


# Path: riboSeed/riboSpec.py
    from line_profiler import LineProfiler
    from matplotlib import pyplot, patches
from .shared_methods import set_up_logging, make_barrnap_cmd
import sys
import os
import re
import random
import math
import glob
import subprocess
import argparse
import multiprocessing
    import matplotlib
import networkx as nx

def process_assembly_graph(args, fastg, output_root, PLOT, which_k, logger):
    # make a list of node objects, a adjacency matrix M, and a DiGRaph object G
    logger.info("Reading assembly graph: %s", fastg)
    node_list, G_dict, G = parse_fastg(f=fastg)
    if PLOT and args.MAKE_ADJACENCY_MATRIX:
        M = make_adjacency_matrix(G_dict)
        plot_adjacency_matrix(
            M, node_order=None, partitions=[], colors=[],
            outpath=os.path.join(output_root, "full_adjacency_matrix.pdf"))
        logger.info("Writing out adjacency graph")
        with open(os.path.join(args.output, "tab.txt"), "w") as o:
            for line in M:
                o.write("\t".join([str(x) for x in line]) + "\n")
    # alt nodes
    dic = {int(x.name): [int(y.name) for y in x.neighbor_list] for x in node_list}


    # run barrnap to find our rDNAs; first time trhough is to find "full" -
    # length genes, and the second run with the relaxed thresholds is for
    # finding partial genes
    barrnap_gff = os.path.join(output_root, "strict_barrnapped.gff")
    barrnap_gff_partial = os.path.join(output_root, "partial_barrnapped.gff")
    barrnap_cmd = make_barrnap_cmd(
        infasta=fastg,
        outgff=barrnap_gff,
        exe=args.barrnap_exe,
        threads=args.cores,
        thresh=args.barrnap_length_threshold,
        evalue=1e-06,
        kingdom="bac")

    barrnap_cmd_partial = make_barrnap_cmd(