code: # 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 implementations of batched variables."""
  
  from __future__ import absolute_import
  from __future__ import division
  from __future__ import print_function
  
  # Dependency imports
  import hypothesis as hp
  from hypothesis import strategies as hps
  from hypothesis.extra import numpy as hpnp
  import numpy as np
  import tensorflow as tf
  
  from tensorflow_probability.python.experimental.auto_batching import backend_test_lib as backend_test
  from tensorflow_probability.python.experimental.auto_batching import instructions as inst
  from tensorflow_probability.python.experimental.auto_batching import numpy_backend
  
  NP_BACKEND = numpy_backend.NumpyBackend()
  
  
  def var_init(max_stack_depth, initial_value):
    type_ = inst.TensorType(initial_value.dtype, initial_value.shape[1:])
    var = NP_BACKEND.create_variable(
        None, inst.VariableAllocation.FULL, type_,
        max_stack_depth, batch_size=initial_value.shape[0])
    return var.update(
        initial_value, NP_BACKEND.full_mask(initial_value.shape[0]))
  
  
  # A TF test case for self.assertAllEqual, but doesn't use TF so doesn't care
  # about Eager vs Graph mode.
  class NumpyVariableTest(tf.test.TestCase, backend_test.VariableTestCase):
  
    def testNumpySmoke(self):
      """Test the property on specific example, without relying on Hypothesis."""
      init = (12, np.random.randn(3, 2, 2).astype(np.float32))
      ops = [('pop', [False, False, True]),
             ('push', [True, False, True]),
             ('update', np.ones((3, 2, 2), dtype=np.float32),
              [True, True, False]),
             ('pop', [True, False, True])]
      self.check_same_results(init, ops, var_init)
  
    @hp.given(hps.data())
    @hp.settings(
        deadline=None,
        max_examples=100)
    def testNumpyVariableRandomOps(self, data):
      # Hypothesis strategy:
      # Generate a random max stack depth and value shape
      # Deduce the batch size from the value shape
      # Make a random dtype
      # Generate a random initial value of that dtype and shape
      # Generate ops, some of which write random values of that dtype and shape
      max_stack_depth = data.draw(hps.integers(min_value=1, max_value=1000))
      value_shape = data.draw(hpnp.array_shapes(min_dims=1))
      batch_size = value_shape[0]
      dtype = data.draw(hpnp.scalar_dtypes())
      masks = hpnp.arrays(dtype=np.bool, shape=[batch_size])
      values = hpnp.arrays(dtype, value_shape)
      init_val = data.draw(values)
      ops = data.draw(
          hps.lists(
              hps.one_of(
                  hps.tuples(hps.just('update'), values, masks),
                  hps.tuples(hps.just('push'), masks),
                  hps.tuples(hps.just('pop'), masks),  # preserve line break
                  hps.tuples(hps.just('read')))))
      self.check_same_results((max_stack_depth, init_val), ops, var_init)
  
  
  if __name__ == '__main__':
    tf.test.main()
   # 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.
  # ============================================================================
  """Sigmoid Tests."""
  
  from __future__ import absolute_import
  from __future__ import division
  from __future__ import print_function
  
  # Dependency imports
  import numpy as np
  from scipy import special
  import tensorflow.compat.v2 as tf
  from tensorflow_probability.python import bijectors as tfb
  
  from tensorflow_probability.python.bijectors import bijector_test_util
  from tensorflow.python.framework import test_util  # pylint: disable=g-direct-tensorflow-import,g-import-not-at-top
  
  
  @test_util.run_all_in_graph_and_eager_modes
  class SigmoidBijectorTest(tf.test.TestCase):
    """Tests correctness of the Y = g(X) = (1 + exp(-X))^-1 transformation."""
  
    def testBijector(self):
      self.assertStartsWith(tfb.Sigmoid().name, "sigmoid")
      x = np.linspace(-10., 10., 100).reshape([2, 5, 10]).astype(np.float32)
      y = special.expit(x)
      ildj = -np.log(y) - np.log1p(-y)
      bijector = tfb.Sigmoid()
      self.assertAllClose(
          y, self.evaluate(bijector.forward(x)), atol=0., rtol=1e-2)
      self.assertAllClose(
          x, self.evaluate(bijector.inverse(y)), atol=0., rtol=1e-4)
      self.assertAllClose(
          ildj,
          self.evaluate(bijector.inverse_log_det_jacobian(
              y, event_ndims=0)), atol=0., rtol=1e-6)
      self.assertAllClose(
          -ildj,
          self.evaluate(bijector.forward_log_det_jacobian(
              x, event_ndims=0)), atol=0., rtol=1e-4)
  
    def testScalarCongruency(self):
      bijector_test_util.assert_scalar_congruency(
          tfb.Sigmoid(), lower_x=-7., upper_x=7., eval_func=self.evaluate,
          rtol=.1)
  
    def testBijectiveAndFinite(self):
      x = np.linspace(-100., 100., 100).astype(np.float32)
      eps = 1e-3
      y = np.linspace(eps, 1. - eps, 100).astype(np.float32)
      bijector_test_util.assert_bijective_and_finite(
          tfb.Sigmoid(), x, y, eval_func=self.evaluate, event_ndims=0, atol=0.,
          rtol=1e-4)
  
  
  if __name__ == "__main__":
    tf.test.main()
   # 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.
  # ============================================================================
  """Helper functions for numpy backend."""
  
  from __future__ import absolute_import
  from __future__ import division
  from __future__ import print_function
  
  import importlib
  import types
  
  import numpy as np
  import tensorflow as tf
  
  
  __all__ = [
      'common_dtype',
      'copy_docstring',
      'numpy_dtype',
      'try_import',
  ]
  
  
  # TODO(jvdillon): Get decoration working. Eg,
  # # Dependency imports
  # import decorator
  
  
  def copy_docstring(original_fn, new_fn):  # pylint: disable=unused-argument
    return new_fn
    # TODO(jvdillon): Get decoration working. Eg,
    # @decorator.decorator
    # def wrap(wrapped_fn, *args, **kwargs):
    #   del wrapped_fn
    #   return new_fn(*args, **kwargs)
    # return wrap(original_fn)
  
  
  def numpy_dtype(dtype):
    if dtype is None:
      return None
    if hasattr(dtype, 'as_numpy_dtype'):
      return dtype.as_numpy_dtype
    return dtype
  
  
  def common_dtype(args_list, dtype_hint=None):
    """Returns explict dtype from `args_list` if exists, else dtype_hint."""
    dtype = None
    dtype_hint = None if dtype_hint is None else tf.as_dtype(dtype_hint)
    for a in tf.nest.flatten(args_list):
      if hasattr(a, 'dtype'):
        dt = tf.as_dtype(a.dtype)
      else:
        continue
      if dtype is None:
        dtype = dt
      elif dtype != dt:
        raise TypeError('Found incompatible dtypes, {} and {}.'.format(dtype, dt))
    if dtype is None and dtype_hint is None:
      return None
    return (dtype_hint if dtype is None else dtype).as_numpy_dtype
  
  
  def is_complex(dtype):
    """Returns whether this is a complex floating point type."""
    return np.issubdtype(np.dtype(dtype), np.complexfloating)
  
  
  class _FakeModule(types.ModuleType):
    """Dummy module which raises `NotImplementedError` on `getattr` access."""
  
    def __init__(self, name, doc):
      self._name = name
      self._doc = doc
      types.ModuleType.__init__(self, name, doc)  # pylint: disable=non-parent-init-called
  
    def __dir__(self):
      return []
  
    def __getattr__(self, attr):
      raise NotImplementedError(self._doc)
  
  
  def try_import(name):  # pylint: disable=invalid-name
    try:
      return importlib.import_module(name)
    except ImportError:
      return _FakeModule(name, 'Error loading module "{}".'.format(name))
  
apis: numpy.ones numpy.random.randn tensorflow.test.main
apis: numpy.log1p tensorflow.compat.v2.test.main numpy.log scipy.special.expit numpy.linspace
apis: numpy.dtype tensorflow.nest.flatten tensorflow.as_dtype