# Copyright 2018 The TensorFlow Probability Authors.
#
# 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
#
#     http://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 Bijector."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow.compat.v2 as tf
from tensorflow_probability.python import bijectors as tfb
from tensorflow_probability.python import distributions as tfd

from tensorflow_probability.python.bijectors import bijector_test_util
from tensorflow_probability.python.internal import tensorshape_util
from tensorflow_probability.python.internal import test_util as tfp_test_util
from tensorflow.python.framework import test_util  # pylint: disable=g-direct-tensorflow-import


@test_util.run_all_in_graph_and_eager_modes
class InvertBijectorTest(tf.test.TestCase):
  """Tests the correctness of the Y = Invert(bij) transformation."""

  def testBijector(self):
    for fwd in [
        tfb.Identity(),
        tfb.Exp(),
        tfb.Affine(shift=[0., 1.], scale_diag=[2., 3.]),
        tfb.Softplus(),
        tfb.SoftmaxCentered(),
    ]:
      rev = tfb.Invert(fwd)
      self.assertStartsWith(rev.name, "_".join(["invert", fwd.name]))
      x = [[[1., 2.],
            [2., 3.]]]
      self.assertAllClose(
          self.evaluate(fwd.inverse(x)), self.evaluate(rev.forward(x)))
      self.assertAllClose(
          self.evaluate(fwd.forward(x)), self.evaluate(rev.inverse(x)))
      self.assertAllClose(
          self.evaluate(fwd.forward_log_det_jacobian(x, event_ndims=1)),
          self.evaluate(rev.inverse_log_det_jacobian(x, event_ndims=1)))
      self.assertAllClose(
          self.evaluate(fwd.inverse_log_det_jacobian(x, event_ndims=1)),
          self.evaluate(rev.forward_log_det_jacobian(x, event_ndims=1)))

  def testScalarCongruency(self):
    bijector = tfb.Invert(tfb.Exp())
    bijector_test_util.assert_scalar_congruency(
        bijector, lower_x=1e-3, upper_x=1.5, eval_func=self.evaluate, rtol=0.05)

  def testShapeGetters(self):
    bijector = tfb.Invert(
        tfb.SoftmaxCentered(validate_args=True))
    x = tf.TensorShape([2])
    y = tf.TensorShape([1])
    self.assertAllEqual(y, bijector.forward_event_shape(x))
    self.assertAllEqual(
        tensorshape_util.as_list(y),
        self.evaluate(
            bijector.forward_event_shape_tensor(tensorshape_util.as_list(x))))
    self.assertAllEqual(x, bijector.inverse_event_shape(y))
    self.assertAllEqual(
        tensorshape_util.as_list(x),
        self.evaluate(
            bijector.inverse_event_shape_tensor(tensorshape_util.as_list(y))))

  def testDocstringExample(self):
    exp_gamma_distribution = (
        tfd.TransformedDistribution(
            distribution=tfd.Gamma(concentration=1., rate=2.),
            bijector=tfb.Invert(tfb.Exp())))
    self.assertAllEqual(
        [],
        self.evaluate(
            tf.shape(
                exp_gamma_distribution.sample(seed=tfp_test_util.test_seed()))))


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

[(92, 'tensorflow.compat.v2.test.main', 'tf.test.main', True, 'import tensorflow.compat.v2 as tf\n'), (60, 'tensorflow_probability.python.bijectors.bijector_test_util.assert_scalar_congruency', 'bijector_test_util.assert_scalar_congruency', False, 'from tensorflow_probability.python.bijectors import bijector_test_util\n'), (66, 'tensorflow.compat.v2.TensorShape', 'tf.TensorShape', True, 'import tensorflow.compat.v2 as tf\n'), (67, 'tensorflow.compat.v2.TensorShape', 'tf.TensorShape', True, 'import tensorflow.compat.v2 as tf\n'), (37, 'tensorflow_probability.python.bijectors.Identity', 'tfb.Identity', True, 'from tensorflow_probability.python import bijectors as tfb\n'), (38, 'tensorflow_probability.python.bijectors.Exp', 'tfb.Exp', True, 'from tensorflow_probability.python import bijectors as tfb\n'), (39, 'tensorflow_probability.python.bijectors.Affine', 'tfb.Affine', True, 'from tensorflow_probability.python import bijectors as tfb\n'), (40, 'tensorflow_probability.python.bijectors.Softplus', 'tfb.Softplus', True, 'from tensorflow_probability.python import bijectors as tfb\n'), (41, 'tensorflow_probability.python.bijectors.SoftmaxCentered', 'tfb.SoftmaxCentered', True, 'from tensorflow_probability.python import bijectors as tfb\n'), (43, 'tensorflow_probability.python.bijectors.Invert', 'tfb.Invert', True, 'from tensorflow_probability.python import bijectors as tfb\n'), (59, 'tensorflow_probability.python.bijectors.Exp', 'tfb.Exp', True, 'from tensorflow_probability.python import bijectors as tfb\n'), (65, 'tensorflow_probability.python.bijectors.SoftmaxCentered', 'tfb.SoftmaxCentered', True, 'from tensorflow_probability.python import bijectors as tfb\n'), (70, 'tensorflow_probability.python.internal.tensorshape_util.as_list', 'tensorshape_util.as_list', False, 'from tensorflow_probability.python.internal import tensorshape_util\n'), (75, 'tensorflow_probability.python.internal.tensorshape_util.as_list', 'tensorshape_util.as_list', False, 'from tensorflow_probability.python.internal import tensorshape_util\n'), (82, 'tensorflow_probability.python.distributions.Gamma', 'tfd.Gamma', True, 'from tensorflow_probability.python import distributions as tfd\n'), (72, 'tensorflow_probability.python.internal.tensorshape_util.as_list', 'tensorshape_util.as_list', False, 'from tensorflow_probability.python.internal import tensorshape_util\n'), (77, 'tensorflow_probability.python.internal.tensorshape_util.as_list', 'tensorshape_util.as_list', False, 'from tensorflow_probability.python.internal import tensorshape_util\n'), (83, 'tensorflow_probability.python.bijectors.Exp', 'tfb.Exp', True, 'from tensorflow_probability.python import bijectors as tfb\n'), (88, 'tensorflow_probability.python.internal.test_util.test_seed', 'tfp_test_util.test_seed', True, 'from tensorflow_probability.python.internal import test_util as tfp_test_util\n')]