# Path: seqcluster/libs/pysen.py
# def pysenMMean (x, y):
# 
# Path: seqcluster/libs/utils.py
# def file_exists(fname):
#     """Check if a file exists and is non-empty.
#     """
#     try:
#         return fname and os.path.exists(fname) and os.path.getsize(fname) > 0
#     except OSError:
#         return False
# 
# Path: seqcluster/detect/metacluster.py
# def _get_seqs_from_cluster(seqs, seen):
#     """
#     Returns the sequences that are already part of the cluster
# 
#     :param seqs: list of sequences ids
#     :param clus_id: dict of sequences ids that are part of a cluster
# 
#     :returns:
#         * :code:`already_in`list of cluster id that contained some of the sequences
#         * :code:`not_in`list of sequences that don't belong to any cluster yet
#     """
#     already_in = set()
#     not_in = []
# 
#     already_in = [e for e in map(seen.get, seqs)]
#     # if isinstance(already_in, list):
#     already_in = filter(None, already_in)
#     not_in = set(seqs) - set(seen.keys())
#     return list(set(already_in)), list(not_in)
# 
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
#         log_stdout=False):
#     """Run the provided command, logging details and checking for errors.
#     """
#     try:
#         logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
#         _do_run(cmd, checks, log_stdout)
#     except:
#         if log_error:
#             logger.info("error at command")
#         raise


import os.path as op
import pysam
import pybedtools
import numpy as np
import seqcluster.libs.logger as mylog
from progressbar import ProgressBar
from  seqcluster.libs import pysen
from seqcluster.libs.utils import file_exists
from seqcluster.libs.classes import *
from seqcluster.detect.metacluster import _get_seqs_from_cluster
from seqcluster.libs.do import run
            # logger.debug("num cluster %s" % len(clus_obj.keys()))
    logger.info("%s clusters merged" % len(metacluster))

    return metacluster, seen

def peak_calling(clus_obj):
    """
    Run peak calling inside each cluster
    """
    new_cluster = {}
    for cid in clus_obj.clus:
        cluster = clus_obj.clus[cid]
        cluster.update()
        logger.debug("peak calling for %s" % cid)
        bigger = cluster.locimaxid
        if bigger in clus_obj.loci:
            s, e = min(clus_obj.loci[bigger].counts.keys()), max(clus_obj.loci[bigger].counts.keys())
            scale = s
            if clus_obj.loci[bigger].strand == "-":
                scale = e
            logger.debug("bigger %s at %s-%s" % (bigger, s, e))
            dt = np.array([0] * (abs(e - s) + 12))
            for pos in clus_obj.loci[bigger].counts:
                ss = abs(int(pos) - scale) + 5
                dt[ss] += clus_obj.loci[bigger].counts[pos]
        x = np.array(range(0, len(dt)))
        logger.debug("x %s and y %s" % (x, dt))
        # tab = pd.DataFrame({'x': x, 'y': dt})
        # tab.to_csv( str(cid) + "peaks.csv", mode='w', header=False, index=False)
        if len(x) > 35 + 12:

# Path: seqcluster/libs/pysen.py
# def pysenMMean (x, y):
# 
# Path: seqcluster/libs/utils.py
# def file_exists(fname):
#     """Check if a file exists and is non-empty.
#     """
#     try:
#         return fname and os.path.exists(fname) and os.path.getsize(fname) > 0
#     except OSError:
#         return False
# 
# Path: seqcluster/detect/metacluster.py
# def _get_seqs_from_cluster(seqs, seen):
#     """
#     Returns the sequences that are already part of the cluster
# 
#     :param seqs: list of sequences ids
#     :param clus_id: dict of sequences ids that are part of a cluster
# 
#     :returns:
#         * :code:`already_in`list of cluster id that contained some of the sequences
#         * :code:`not_in`list of sequences that don't belong to any cluster yet
#     """
#     already_in = set()
#     not_in = []
# 
#     already_in = [e for e in map(seen.get, seqs)]
#     # if isinstance(already_in, list):
#     already_in = filter(None, already_in)
#     not_in = set(seqs) - set(seen.keys())
#     return list(set(already_in)), list(not_in)
# 
# Path: seqcluster/libs/do.py
# def run(cmd, data=None, checks=None, region=None, log_error=True,
#         log_stdout=False):
#     """Run the provided command, logging details and checking for errors.
#     """
#     try:
#         logger.debug(" ".join(str(x) for x in cmd) if not isinstance(cmd, basestring) else cmd)
#         _do_run(cmd, checks, log_stdout)
#     except:
#         if log_error:
#             logger.info("error at command")
#         raise


# Path: seqcluster/detect/cluster.py
import os.path as op
import pysam
import pybedtools
import numpy as np
import seqcluster.libs.logger as mylog
from progressbar import ProgressBar
from  seqcluster.libs import pysen
from seqcluster.libs.utils import file_exists
from seqcluster.libs.classes import *
from seqcluster.detect.metacluster import _get_seqs_from_cluster
from seqcluster.libs.do import run

            # logger.debug("num cluster %s" % len(clus_obj.keys()))
    logger.info("%s clusters merged" % len(metacluster))

    return metacluster, seen

def peak_calling(clus_obj):
    """
    Run peak calling inside each cluster
    """
    new_cluster = {}
    for cid in clus_obj.clus:
        cluster = clus_obj.clus[cid]
        cluster.update()
        logger.debug("peak calling for %s" % cid)
        bigger = cluster.locimaxid
        if bigger in clus_obj.loci:
            s, e = min(clus_obj.loci[bigger].counts.keys()), max(clus_obj.loci[bigger].counts.keys())
            scale = s
            if clus_obj.loci[bigger].strand == "-":
                scale = e
            logger.debug("bigger %s at %s-%s" % (bigger, s, e))
            dt = np.array([0] * (abs(e - s) + 12))
            for pos in clus_obj.loci[bigger].counts:
                ss = abs(int(pos) - scale) + 5
                dt[ss] += clus_obj.loci[bigger].counts[pos]
        x = np.array(range(0, len(dt)))
        logger.debug("x %s and y %s" % (x, dt))
        # tab = pd.DataFrame({'x': x, 'y': dt})
        # tab.to_csv( str(cid) + "peaks.csv", mode='w', header=False, index=False)
        if len(x) > 35 + 12:

            peaks = list(np.array(pysen.pysenMMean(x, dt)) - 5)