# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tests for nngp.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf

import nngp


class NNGPTest(tf.test.TestCase):

  def ExactQabArcCos(self, var_aa, corr_ab):
    """Exact integration result from Cho & Saul (2009).

    Specifically:
      qaa = 0.5*qaa
      qab = (qaa/2*pi)*(sin angle + (pi-angle)*cos angle),

      where cos angle = corr_ab.

    Args:
      var_aa: 1d tensor of variance grid points.
      corr_ab: 1d tensor of correlation grid points.
    Returns:
      qab_exact: tensor, exact covariance matrix.
    """
    angle = tf.acos(corr_ab)
    jtheta = tf.sin(angle) + (np.pi - angle) * tf.cos(angle)

    term1 = tf.tile(tf.expand_dims(var_aa, 1), [1, corr_ab.shape[0]])
    term2 = tf.tile(tf.expand_dims(jtheta, 0), [var_aa.shape[0], 1])
    qab_exact = (1 / (2 * np.pi)) * term1 * term2

    return qab_exact

  def testComputeQmapGridRelu(self):
    """Test checks the compute_qmap_grid function.

    (i) Checks sizes are appropriate and (ii) checks
    accuracy of the numerical values generated by the
    grid by comparing against the analytically known
    form for Relu (Cho and Saul, '09).
    """
    n_gauss, n_var, n_corr = 301, 33, 31
    kernel = nngp.NNGPKernel(
        nonlin_fn=tf.nn.relu, n_gauss=n_gauss, n_var=n_var, n_corr=n_corr)

    var_aa_grid = kernel.var_aa_grid
    corr_ab_grid = kernel.corr_ab_grid
    qaa_grid = kernel.qaa_grid
    qab_grid = kernel.qab_grid

    qaa_exact = 0.5 * var_aa_grid
    qab_exact = self.ExactQabArcCos(var_aa_grid, corr_ab_grid)

    with self.test_session() as sess:
      self.assertEqual(var_aa_grid.shape.as_list(), [n_var])
      self.assertEqual(corr_ab_grid.shape.as_list(), [n_corr])
      self.assertAllClose(sess.run(qaa_exact), sess.run(qaa_grid), rtol=1e-6)
      self.assertAllClose(
          sess.run(qab_exact), sess.run(qab_grid), rtol=1e-6, atol=2e-2)

  def testComputeQmapGridReluLogSpacing(self):
    n_gauss, n_var, n_corr = 301, 33, 31
    kernel = nngp.NNGPKernel(
        nonlin_fn=tf.nn.relu, n_gauss=n_gauss, n_var=n_var, n_corr=n_corr)

    var_aa_grid = kernel.var_aa_grid
    corr_ab_grid = kernel.corr_ab_grid
    qaa_grid = kernel.qaa_grid
    qab_grid = kernel.qab_grid

    qaa_exact = 0.5 * var_aa_grid
    qab_exact = self.ExactQabArcCos(var_aa_grid, corr_ab_grid)

    with self.test_session() as sess:
      self.assertEqual(var_aa_grid.shape.as_list(), [n_var])
      self.assertEqual(corr_ab_grid.shape.as_list(), [n_corr])
      self.assertAllClose(
          sess.run(qaa_exact), sess.run(qaa_grid), rtol=1e-6, atol=2e-2)
      self.assertAllClose(
          sess.run(qab_exact), sess.run(qab_grid), rtol=1e-6, atol=2e-2)

  def testComputeQmapGridEvenNGauss(self):
    n_gauss, n_var, n_corr = 102, 33, 31

    with self.assertRaises(ValueError):
      nngp.NNGPKernel(
          nonlin_fn=tf.nn.relu, n_gauss=n_gauss, n_var=n_var, n_corr=n_corr)

  def testGetVarFixedPoint(self):
    n_gauss, n_var, n_corr = 101, 33, 31
    weight_var, bias_var = 1.9, 0.2
    analytic_fixed_point = bias_var / (1. - weight_var/2)

    kernel = nngp.NNGPKernel(
        nonlin_fn=tf.nn.relu, weight_var=weight_var, bias_var=bias_var,
        n_gauss=n_gauss, n_var=n_var, n_corr=n_corr)
    fixed_point, _ = kernel.get_var_fixed_point()

    self.assertAllClose(analytic_fixed_point, fixed_point[0], atol=1e-4)


if __name__ == "__main__":
  tf.test.main()