# Source code for GPy.likelihoods.binomial

# Copyright (c) 2012-2014 The GPy authors (see AUTHORS.txt)

import numpy as np
from ..util.univariate_Gaussian import std_norm_pdf, std_norm_cdf
from .likelihood import Likelihood
from scipy import special

[docs]class Binomial(Likelihood):
"""
Binomial likelihood

.. math::
p(y_{i}|\\lambda(f_{i})) = \\lambda(f_{i})^{y_{i}}(1-f_{i})^{1-y_{i}}

.. Note::
Y takes values in either {-1, 1} or {0, 1}.
link function should have the domain [0, 1], e.g. probit (default) or Heaviside

likelihood.py, for the parent class
"""

"""
Likelihood function given inverse link of f.

.. math::
p(y_{i}|\\lambda(f_{i})) = \\lambda(f_{i})^{y_{i}}(1-f_{i})^{1-y_{i}}

:param y: data
:type y: Nx1 array
:returns: likelihood evaluated for this point
:rtype: float

.. Note:
Each y_i must be in {0, 1}
"""

"""
Log Likelihood function given inverse link of f.

.. math::
\\ln p(y_{i}|\\lambda(f_{i})) = y_{i}\\log\\lambda(f_{i}) + (1-y_{i})\\log (1-f_{i})

:param y: data
:type y: Nx1 array
:returns: log likelihood evaluated at points inverse link of f.
:rtype: float
"""
np.testing.assert_array_equal(N.shape, y.shape)

nchoosey = special.gammaln(N+1) - special.gammaln(y+1) - special.gammaln(N-y+1)
Ny = N-y
t1 = np.zeros(y.shape)
t2 = np.zeros(y.shape)

return nchoosey + t1 + t2

"""

.. math::
\\frac{d^{2}\\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)^{2}} = \\frac{y_{i}}{\\lambda(f)} - \\frac{(N-y_{i})}{(1-\\lambda(f))}

:param y: data
:type y: Nx1 array
:returns: gradient of log likelihood evaluated at points inverse link of f.
:rtype: Nx1 array
"""
np.testing.assert_array_equal(N.shape, y.shape)

Ny = N-y
t1 = np.zeros(y.shape)
t2 = np.zeros(y.shape)

return t1 - t2

"""
Hessian at y, given inv_link_f, w.r.t inv_link_f the hessian will be 0 unless i == j
i.e. second derivative logpdf at y given inverse link of f_i and inverse link of f_j  w.r.t inverse link of f_i and inverse link of f_j.

.. math::
\\frac{d^{2}\\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)^{2}} = \\frac{-y_{i}}{\\lambda(f)^{2}} - \\frac{(N-y_{i})}{(1-\\lambda(f))^{2}}

:param y: data
:type y: Nx1 array
:returns: Diagonal of log hessian matrix (second derivative of log likelihood evaluated at points inverse link of f.
:rtype: Nx1 array

.. Note::
Will return diagonal of hessian, since every where else it is 0, as the likelihood factorizes over cases
(the distribution for y_i depends only on inverse link of f_i not on inverse link of f_(j!=i)
"""
np.testing.assert_array_equal(N.shape, y.shape)
Ny = N-y
t1 = np.zeros(y.shape)
t2 = np.zeros(y.shape)
return t1+t2

"""
Third order derivative log-likelihood function at y given inverse link of f w.r.t inverse link of f

.. math::
\\frac{d^{2}\\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)^{2}} = \\frac{2y_{i}}{\\lambda(f)^{3}} - \\frac{2(N-y_{i})}{(1-\\lambda(f))^{3}}

:param y: data
:type y: Nx1 array
:returns: Diagonal of log hessian matrix (second derivative of log likelihood evaluated at points inverse link of f.
:rtype: Nx1 array

.. Note::
Will return diagonal of hessian, since every where else it is 0, as the likelihood factorizes over cases
(the distribution for y_i depends only on inverse link of f_i not on inverse link of f_(j!=i)
"""
np.testing.assert_array_equal(N.shape, y.shape)

Ny = N-y
t1 = np.zeros(y.shape)
t2 = np.zeros(y.shape)
return t1 + t2

[docs]    def samples(self, gp, Y_metadata=None, **kw):
"""
Returns a set of samples of observations based on a given value of the latent variable.

:param gp: latent variable
"""
orig_shape = gp.shape
gp = gp.flatten()
return Ysim.reshape(orig_shape)

pass

"""
:param obs: observed output
:param tau: cavity distribution 1st natural parameter (precision)
:param v: cavity distribution 2nd natural paramenter (mu*precision)
"""
#Compute first integral for zeroth moment.
#NOTE constant np.sqrt(2*pi/tau) added at the end of the function
else:
nu = 1.0
mu = v/tau
sigma2 = 1./tau
t = np.asarray(1 + sigma2*(nu**2))
t[t<1e-20] = 1e-20
a = np.sqrt(t)
z = obs*mu/a
m0 = normc_z
m1 = mu + (obs*sigma2*normp_z)/(normc_z*a)
#print('tau: {}, v: {}, nu: {}, z: {}, normc_z: {}, normp_z: {}'.format(tau, v, nu.values, z, normc_z, normp_z))
m2 = sigma2 - ((sigma2**2)*normp_z)/((1./(nu**2)+sigma2)*normc_z)*(z + normp_z/(nu**2)/normc_z)
#print("m0: {}, m1: {}, m2: {}".format(m0,m1,m2))
#m0a, m1a, m2a =  super(Binomial, self).moments_match_ep(obs,tau,v,Y_metadata_i)
#print("m0a: {}, m1a: {}, m2a: {}".format(m0a,m1a,m2a))
return m0, m1, m2
else:

[docs]    def variational_expectations(self, Y, m, v, gh_points=None, Y_metadata=None):

if gh_points is None:
gh_x, gh_w = self._gh_points()
else:
gh_x, gh_w = gh_points

gh_w = gh_w / np.sqrt(np.pi)
shape = m.shape
m,v,Y, C = m.flatten(), v.flatten(), Y.flatten()[:,None], C.flatten()[:,None]
X = gh_x[None,:]*np.sqrt(2.*v[:,None]) + m[:,None]
p = std_norm_cdf(X)
p = np.clip(p, 1e-9, 1.-1e-9) # for numerical stability
N = std_norm_pdf(X)
#TODO: missing nchoosek coefficient! use gammaln?
F = (Y*np.log(p) + (C-Y)*np.log(1.-p)).dot(gh_w)
NoverP = N/p
NoverP_ = N/(1.-p)
dF_dm = (Y*NoverP - (C-Y)*NoverP_).dot(gh_w)
dF_dv = -0.5* ( Y*(NoverP**2 + NoverP*X) + (C-Y)*(NoverP_**2 - NoverP_*X) ).dot(gh_w)
return F.reshape(*shape), dF_dm.reshape(*shape), dF_dv.reshape(*shape), None
else:
raise NotImplementedError