'''
Utility functions.

@author: Gergely Acs <acs@crysys.hu>
'''

import math
import random as rnd
import numpy as np

def strToSeq(str, dec=0):
    return reduce(lambda x,y: x + y, map(lambda x: unichr(int(x)-dec), str)) 

def seqToStr(sequence, inc=0):
    return " ".join(map(lambda x: str(ord(x)+inc), sequence))

def KL_div(p, q):
    s = 0
    for i in range(len(p)):
        if p[i] > 0:
            s += p[i] * math.log(float(p[i]) / q[i])
    return s

def sanitize(hist):
    return map(lambda x: max(1, x), hist)

def l2norm(values):
    return math.sqrt(reduce(lambda x,y: x + abs(y)**2, values))

def is_int(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

def laplace(p_lambda):
    return np.random.laplace(0, p_lambda, 1)[0]

def normalize(vec):
    s = sum(vec)
    return  vec if s <= 0 else map((lambda x: x/float(s)), vec)

def stat_dist(d1, d2):
    return sum( (abs(d1[i] - d2[i]) for i in range(len(d1))) )


