<commit_before># 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.
# ============================================================================
"""Class which enables `tfd.Distribution` to `tf.Tensor` coercion."""

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

import copy
import six

import tensorflow.compat.v2 as tf

from tensorflow_probability.python.distributions import distribution as tfd
from tensorflow_probability.python.util.deferred_tensor import TensorMetaClass
from tensorflow.python.framework import composite_tensor  # pylint: disable=g-direct-tensorflow-import


__all__ = []  # We intend nothing public.


# Define mixin type because Distribution already has its own metaclass.
class _DistributionAndTensorCoercibleMeta(type(tfd.Distribution),
                                          TensorMetaClass):
  pass


@six.add_metaclass(_DistributionAndTensorCoercibleMeta)
class _TensorCoercible(tfd.Distribution):
  """Docstring."""

  def __new__(cls, distribution, convert_to_tensor_fn=tfd.Distribution.sample):
    if isinstance(distribution, cls):
      return distribution
    if not isinstance(distribution, tfd.Distribution):
      raise TypeError('`distribution` argument must be a '
                      '`tfd.Distribution` instance; '
                      'saw "{}" of type "{}".'.format(
                          distribution, type(distribution)))
    self = copy.copy(distribution)
    distcls = distribution.__class__
    self.__class__ = type(distcls.__name__, (cls, distcls), {})
    self._concrete_value = None  # pylint: disable=protected-access
    self._convert_to_tensor_fn = convert_to_tensor_fn  # pylint: disable=protected-access
    return self

  def __init__(self,
               distribution,
               convert_to_tensor_fn=tfd.Distribution.sample):
    pass

  @property
  def shape(self):
    return (tf.TensorShape(None) if self._concrete_value is None
            else self._concrete_value.shape)

  def _value(self, dtype=None, name=None, as_ref=False):
    """Get the value returned by `tf.convert_to_tensor(distribution)`.

    Note: this function may mutate the distribution instance state by caching
    the concretized `Tensor` value.

    Args:<commit_msg>Don't create new TensorCoercible subclass is the same class has already been created<commit_after># 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.
# ============================================================================
"""Class which enables `tfd.Distribution` to `tf.Tensor` coercion."""

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

import copy
import six

import tensorflow.compat.v2 as tf

from tensorflow_probability.python.distributions import distribution as tfd
from tensorflow_probability.python.util.deferred_tensor import TensorMetaClass
from tensorflow.python.framework import composite_tensor  # pylint: disable=g-direct-tensorflow-import


__all__ = []  # We intend nothing public.


# Define mixin type because Distribution already has its own metaclass.
class _DistributionAndTensorCoercibleMeta(type(tfd.Distribution),
                                          TensorMetaClass):
  pass


@six.add_metaclass(_DistributionAndTensorCoercibleMeta)
class _TensorCoercible(tfd.Distribution):
  """Docstring."""

  registered_class_list = {}
  def __new__(cls, distribution, convert_to_tensor_fn=tfd.Distribution.sample):
    if isinstance(distribution, cls):
      return distribution
    if not isinstance(distribution, tfd.Distribution):
      raise TypeError('`distribution` argument must be a '
                      '`tfd.Distribution` instance; '
                      'saw "{}" of type "{}".'.format(
                          distribution, type(distribution)))
    self = copy.copy(distribution)
    distcls = distribution.__class__
    self_class = _TensorCoercible.registered_class_list.get(distcls)
    if not self_class:
      self_class = _TensorCoercible.registered_class_list[distcls] = type(distcls.__name__, (cls, distcls), {})
    self.__class__ = self_class
    self._concrete_value = None  # pylint: disable=protected-access
    self._convert_to_tensor_fn = convert_to_tensor_fn  # pylint: disable=protected-access
    return self

  def __init__(self,
               distribution,
               convert_to_tensor_fn=tfd.Distribution.sample):
    pass

  @property
  def shape(self):
    return (tf.TensorShape(None) if self._concrete_value is None
            else self._concrete_value.shape)

  def _value(self, dtype=None, name=None, as_ref=False):
    """Get the value returned by `tf.convert_to_tensor(distribution)`.

    Note: this function may mutate the distribution instance state by caching
    the concretized `Tensor` value.

    Args:
{'fraction_non_alphanumeric': 0.101652056641942, 'fraction_numerical': 0.0030343897505057315, 'mean_word_length': 3.8791118421052633, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '421910', 'n_tokens_mistral': 1612, 'n_tokens_neox': 1519, 'n_words': 498}