##
## MCMC sampler for Mixture-of-Isoforms (MISO) model
##
## Yarden Katz <yarden@mit.edu>
##
## The sampler uses a Metropolis-Hastings sampling scheme, combined with
## a Gibbs sampling step.
##
import scipy
import misopy
from misopy.reads_utils import count_aligned_reads, \
                               count_isoform_assignments
from misopy.read_simulator import simulate_reads, print_reads_summary, \
                                  read_counts_to_read_list, \
                                  get_reads_summary
import misopy.hypothesis_test as ht
from misopy.Gene import Gene, Exon
from misopy.py2c_gene import *

# C MISO interface
import pysplicing

from scipy import *
from numpy import *
import cPickle as pickle
from scipy.stats import mode
import math
import time
from numpy import numarray
import os
import sys
from collections import defaultdict
import glob
import logging
import logging.handlers

loggers = {}

def get_logger(logger_name, log_outdir,
               level=logging.WARNING,
               include_stdout=True):
    """
    Return a logging object.
    """
    global loggers
    # Avoid race-conditions
    try:
        os.makedirs(log_outdir)
    except OSError:
        pass
    if loggers.get(logger_name):
        return loggers.get(logger_name)
    logger = logging.getLogger(logger_name)
    formatter = \
        logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                          datefmt='%m/%d/%Y %I:%M:%S %p')
    # Do not log to file
    #if log_outdir is not None:
    #    log_filename = os.path.join(log_outdir, "%s.log" %(logger_name))
    #    fh = logging.FileHandler(log_filename)
    #    fh.setLevel(level)
    #    fh.setFormatter(formatter)
    #    logger.addHandler(fh)
    logging.root.setLevel(level)
    # Optionally add handler that streams all logs
    # to stdout
    if include_stdout:
        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(level)
        ch.setFormatter(formatter)
        logger.addHandler(ch)
    logger.info("Created logger %s" %(logger_name))
    loggers.update({logger_name: logger})
    return logger


##
## Helper statistics/linear algebra functions
##
def set_diag(a, v):
    for i, elt in enumerate(a):
        a[i, i] = v
    return a

def maxi(l):
    m = max(l)
    for i, v in enumerate(l):
        if m == v:
            return i

def mini(l):
    m = min(l)