# Path: riboSeed/riboSim.py
# def ageSequence(rec, outfile, freq, end_length, seed, logger=None):
#     assert logger is not None, "must use logging"
#     logger.info("frequncy of mutation: %f", freq)
#     newseqlist = list(rec.seq)
#     alph = ["A", "T", "C", "G"]
#     seqlen = len(rec.seq)
#     if end_length is None or end_length is 0:
#         ignore_region = []
#     elif not seqlen - (2 * end_length) > 1:
#         raise ValueError("Edge width cannot be greater than half the " +
#                          "length of the sequence ")
#     else:
#         ignore_region = set([idx for sublist in
#                              [range(end_length, seqlen - end_length)]
#                              for idx in sublist])
#     newseqlist = list(rec.seq)
#     seq_len = len(newseqlist)
#     random.seed(seed)
#     # subst_idxs = random.sample(range(0, seq_len), int(round(seq_len * freq)))
#     idxs = list(range(0, seq_len))
#     random.shuffle(idxs)
#     subst_idxs = idxs[0: int(round(seq_len * freq))]
#     # ignore the indexes in the regions we are leaving unchanaged
#     executed_subst_idxs = [x for x in subst_idxs if x not in ignore_region]
#     for i in executed_subst_idxs:
#         if i in ignore_region:
#             pass
#         else:
#             substitute_base(strlist=newseqlist, position=i, alph=alph)
#     logger.info("Changed %d of %d bases", len(executed_subst_idxs), seq_len)
#     newrec = SeqRecord(
#         id=rec.id,
#         # description="riboSim mutation frequency" + str(freq),
#         seq=Seq("".join(newseqlist),
#                 IUPAC.IUPACAmbiguousDNA()))
# 
#     with open(outfile, "a") as o:
#         SeqIO.write(newrec, o, "fasta")
# 
#     assert len(newseqlist) == len(rec.seq), \
#         "something bad happened! unequal lengths of input and output sequences"
# 
# def main(args, logger=None):
#     # allow user to give relative paths
#     output_root = os.path.abspath(os.path.expanduser(args.output))
#     try:
#         os.makedirs(output_root, exist_ok=False)
#     except OSError:
#         print("Output directory already exists; exiting...")
#         sys.exit(1)
#     t0 = time.time()
#     log_path = os.path.join(output_root,
#                             str("riboSim_log_{0}.txt".format(
#                                 time.strftime("%Y%m%d%H%M"))))
#     logger = set_up_logging(verbosity=args.verbosity,
#                             outfile=log_path,
#                             name=__name__)
# 
#     logger.info("Usage:\n{0}\n".format(" ".join([x for x in sys.argv])))
#     logger.debug("All settings used:")
#     for k, v in sorted(vars(args).items()):
#         logger.debug("{0}: {1}".format(k, v))
# 
#     output_file = os.path.join(
#         output_root,
#         os.path.basename(args.fasta))
# 
#     with open(args.fasta, "r") as infile:
#         for rec in SeqIO.parse(infile, "fasta"):
#             ageSequence(rec, freq=args.frequency, end_length=args.end_length,
#                         outfile=output_file, seed=args.seed, logger=logger)
#     # Report that we've finished
#     logger.info("Done: %s", time.asctime())
#     logger.info("Time taken: %.3fs" % (time.time() - t0))
# 
# Path: riboSeed/shared_methods.py
# def md5(fname, string=False):
#     """straight from quantumsoup
#     http://stackoverflow.com/questions/3431825/
#         generating-an-md5-checksum-of-a-file
#     updated 20160916 for strings; if true, fname can be a string
#     """
#     if string:
#         return hashlib.md5(fname.encode('utf-8')).hexdigest()
#     else:
#         hash_md5 = hashlib.md5()
#         with open(fname, "rb") as f:
#             for chunk in iter(lambda: f.read(4096), b""):
#                 hash_md5.update(chunk)
#             return hash_md5.hexdigest()


import sys
import logging
import shutil
import os
import unittest
import random
from Bio import SeqIO
from argparse import Namespace
from riboSeed.riboSim import ageSequence, main
from riboSeed.shared_methods import md5
        self.temp_fasta = os.path.join(
            os.path.dirname(__file__),
            "references", "riboSim_references", "new.fasta")
        self.temp_fasta2 = os.path.join(
            os.path.dirname(__file__),
            "references", "riboSim_references", "new2.fasta")
        self.mut_fasta = os.path.join(
            os.path.dirname(__file__),
            "references", "riboSim_references", "mutated_ten_seed_27.fasta")
        self.to_be_removed = []

    def test_correct_mutations(self):
        """check the aged sequence"""
        test_seq = str(
            "AAAAAAAAATAACAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAT" +
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
            "AAAAAGTAAAAAAAAAAAAAAAAAAATAAAGAAAGAAAAAAAAAAAAAAAAAAAACAAGA")
        with open(self.fasta, "r") as infile:
            rec = list(SeqIO.parse(infile, "fasta"))[0]
        ageSequence(rec, freq=.1, end_length=60,
                    outfile=self.temp_fasta, seed=27, logger=logger)
        with open(self.temp_fasta, "r") as infa:
            newrec = list(SeqIO.parse(infa, "fasta"))[0]
        self.assertEqual(test_seq, str(newrec.seq))
        self.to_be_removed.append(self.temp_fasta)

    def test_correct_mutation_rate(self):
        """check number of substitutions in aged sequence is sensible"""
        with open(self.fasta, "r") as infile:
            rec = list(SeqIO.parse(infile, "fasta"))[0]

# Path: riboSeed/riboSim.py
# def ageSequence(rec, outfile, freq, end_length, seed, logger=None):
#     assert logger is not None, "must use logging"
#     logger.info("frequncy of mutation: %f", freq)
#     newseqlist = list(rec.seq)
#     alph = ["A", "T", "C", "G"]
#     seqlen = len(rec.seq)
#     if end_length is None or end_length is 0:
#         ignore_region = []
#     elif not seqlen - (2 * end_length) > 1:
#         raise ValueError("Edge width cannot be greater than half the " +
#                          "length of the sequence ")
#     else:
#         ignore_region = set([idx for sublist in
#                              [range(end_length, seqlen - end_length)]
#                              for idx in sublist])
#     newseqlist = list(rec.seq)
#     seq_len = len(newseqlist)
#     random.seed(seed)
#     # subst_idxs = random.sample(range(0, seq_len), int(round(seq_len * freq)))
#     idxs = list(range(0, seq_len))
#     random.shuffle(idxs)
#     subst_idxs = idxs[0: int(round(seq_len * freq))]
#     # ignore the indexes in the regions we are leaving unchanaged
#     executed_subst_idxs = [x for x in subst_idxs if x not in ignore_region]
#     for i in executed_subst_idxs:
#         if i in ignore_region:
#             pass
#         else:
#             substitute_base(strlist=newseqlist, position=i, alph=alph)
#     logger.info("Changed %d of %d bases", len(executed_subst_idxs), seq_len)
#     newrec = SeqRecord(
#         id=rec.id,
#         # description="riboSim mutation frequency" + str(freq),
#         seq=Seq("".join(newseqlist),
#                 IUPAC.IUPACAmbiguousDNA()))
# 
#     with open(outfile, "a") as o:
#         SeqIO.write(newrec, o, "fasta")
# 
#     assert len(newseqlist) == len(rec.seq), \
#         "something bad happened! unequal lengths of input and output sequences"
# 
# def main(args, logger=None):
#     # allow user to give relative paths
#     output_root = os.path.abspath(os.path.expanduser(args.output))
#     try:
#         os.makedirs(output_root, exist_ok=False)
#     except OSError:
#         print("Output directory already exists; exiting...")
#         sys.exit(1)
#     t0 = time.time()
#     log_path = os.path.join(output_root,
#                             str("riboSim_log_{0}.txt".format(
#                                 time.strftime("%Y%m%d%H%M"))))
#     logger = set_up_logging(verbosity=args.verbosity,
#                             outfile=log_path,
#                             name=__name__)
# 
#     logger.info("Usage:\n{0}\n".format(" ".join([x for x in sys.argv])))
#     logger.debug("All settings used:")
#     for k, v in sorted(vars(args).items()):
#         logger.debug("{0}: {1}".format(k, v))
# 
#     output_file = os.path.join(
#         output_root,
#         os.path.basename(args.fasta))
# 
#     with open(args.fasta, "r") as infile:
#         for rec in SeqIO.parse(infile, "fasta"):
#             ageSequence(rec, freq=args.frequency, end_length=args.end_length,
#                         outfile=output_file, seed=args.seed, logger=logger)
#     # Report that we've finished
#     logger.info("Done: %s", time.asctime())
#     logger.info("Time taken: %.3fs" % (time.time() - t0))
# 
# Path: riboSeed/shared_methods.py
# def md5(fname, string=False):
#     """straight from quantumsoup
#     http://stackoverflow.com/questions/3431825/
#         generating-an-md5-checksum-of-a-file
#     updated 20160916 for strings; if true, fname can be a string
#     """
#     if string:
#         return hashlib.md5(fname.encode('utf-8')).hexdigest()
#     else:
#         hash_md5 = hashlib.md5()
#         with open(fname, "rb") as f:
#             for chunk in iter(lambda: f.read(4096), b""):
#                 hash_md5.update(chunk)
#             return hash_md5.hexdigest()


# Path: tests/test_riboSim.py
import sys
import logging
import shutil
import os
import unittest
import random
from Bio import SeqIO
from argparse import Namespace
from riboSeed.riboSim import ageSequence, main
from riboSeed.shared_methods import md5

        self.temp_fasta = os.path.join(
            os.path.dirname(__file__),
            "references", "riboSim_references", "new.fasta")
        self.temp_fasta2 = os.path.join(
            os.path.dirname(__file__),
            "references", "riboSim_references", "new2.fasta")
        self.mut_fasta = os.path.join(
            os.path.dirname(__file__),
            "references", "riboSim_references", "mutated_ten_seed_27.fasta")
        self.to_be_removed = []

    def test_correct_mutations(self):
        """check the aged sequence"""
        test_seq = str(
            "AAAAAAAAATAACAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAT" +
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
            "AAAAAGTAAAAAAAAAAAAAAAAAAATAAAGAAAGAAAAAAAAAAAAAAAAAAAACAAGA")
        with open(self.fasta, "r") as infile:
            rec = list(SeqIO.parse(infile, "fasta"))[0]
        ageSequence(rec, freq=.1, end_length=60,
                    outfile=self.temp_fasta, seed=27, logger=logger)
        with open(self.temp_fasta, "r") as infa:
            newrec = list(SeqIO.parse(infa, "fasta"))[0]
        self.assertEqual(test_seq, str(newrec.seq))
        self.to_be_removed.append(self.temp_fasta)

    def test_correct_mutation_rate(self):
        """check number of substitutions in aged sequence is sensible"""
        with open(self.fasta, "r") as infile:
            rec = list(SeqIO.parse(infile, "fasta"))[0]

        ageSequence(rec, freq=.1, end_length=0,