from math import log, floor

# h in [0, 360]
# s in [0, 1]
# v in [0, 1]

# returns values in [0,1]

def HSVtoRGB(h, s, v):
    if s == 0:
        # achromatic (grey)
        r = v
        g = v
        b = v
    else:
        h = h/60  # sector 0 to 5
	i = floor( h )
	f = h - i	# factorial part of h
	p = v * ( 1 - s )
	q = v * ( 1 - s * f )
	t = v * ( 1 - s * ( 1 - f ) )
        if i == 0:
            return (v, t, p)
        elif i == 1:
            return (q, v, p)
        elif i == 2:
            return (p, v, t)
        elif i == 3:
            return (p, q, v)
        elif i == 4:
            return (t, p, v)
        else:
            return (v, p, q)

redHue = 0.0
greenHue = 120.0

def probToPyColor(p, uniformP = 0.5):
    if p > uniformP:
        return RGBToPyColor(HSVtoRGB(greenHue, 1.0,
                                     min(1.0, ((p - uniformP)/(1.0 - uniformP))**0.5)))
    else:
        return RGBToPyColor(HSVtoRGB(redHue, 1.0,
                                     min(1.0, ((uniformP - p)/uniformP)**2)))

def RGBToPyColor(colorVals):
    (r, g, b) = [floor(c*255.99) for c in colorVals]
    return '#%02x%02x%02x' % (r, g, b)

def safeLog(v):
    if v > 0:
        return log(v)
    else:
        return -1000
