# utils.pxd
# Contact: Jacob Schreiber ( jmschreiber91@gmail.com )

from libc.math cimport log as clog, sqrt as csqrt, exp as cexp

# Define some useful constants
DEF NEGINF = float("-inf")
DEF INF = float("inf")
DEF SQRT_2_PI = 2.50662827463

# Useful speed optimized functions
cdef inline double _log ( double x ):
	'''
	A wrapper for the c log function, by returning negative input if the
	input is 0.
	'''

	return clog( x ) if x > 0 else NEGINF

cdef inline int pair_int_max( int x, int y ):
	'''
	Calculate the maximum of a pair of two integers. This is
	significantly faster than the Python function max().
	'''

	return x if x > y else y

cdef inline double pair_lse( double x, double y ):
	'''
	Perform log-sum-exp on a pair of numbers in log space..  This is calculated
	as z = log( e**x + e**y ). However, this causes underflow sometimes
	when x or y are too negative. A simplification of this is thus
	z = x + log( e**(y-x) + 1 ), where x is the greater number. If either of
	the inputs are infinity, return infinity, and if either of the inputs
	are negative infinity, then simply return the other input.
	'''

	if x == INF or y == INF:
		return INF
	if x == NEGINF:
		return y
	if y == NEGINF:
		return x
	if x > y:
		return x + clog( cexp( y-x ) + 1 )
	return y + clog( cexp( x-y ) + 1 )