
    AVh*              	       
   d Z ddlZddlZddlZddlZddlZddlmZ ddlm	Z	 ddlm
Z
 ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ dgZ G d d ej,                  dg d            Z G d dej0                        Zy)zBijector base.    N)dtypes)ops)tensor_shape)tensor_util)	array_ops)	check_ops)math_ops)util)object_identityBijectorc                   `     e Zd ZdZd	 fd	Zed        Zed        Zd
dZddZ	d Z
d Z xZS )_Mappingz?Helper class to make it easier to manage caching in `Bijector`.c                 2    t         t        |   | ||||      S )a  Custom __new__ so namedtuple items have defaults.

    Args:
      x: `Tensor`. Forward.
      y: `Tensor`. Inverse.
      ildj_map: `Dictionary`. This is a mapping from event_ndims to a `Tensor`
        representing the inverse log det jacobian.
      kwargs: Python dictionary. Extra args supplied to
        forward/inverse/etc functions.

    Returns:
      mapping: New instance of _Mapping.
    )superr   __new__)clsxyildj_mapkwargs	__class__s        a/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/ops/distributions/bijector_impl.pyr   z_Mapping.__new__,   s     3'Q8VDD    c           	          t        j                  | j                        f| j                  t	        t        | j                  j                                           z   S )z$Returns key used for caching Y=g(X).)r   	Referencer   _deep_tupletuplesortedr   itemsselfs    r   x_keyz_Mapping.x_key<   J     &&tvv.0U6$++*;*;*=#>?@A Br   c           	          t        j                  | j                        f| j                  t	        t        | j                  j                                           z   S )z)Returns key used for caching X=g^{-1}(Y).)r   r   r   r   r   r   r   r   r    s    r   y_keyz_Mapping.y_keyB   r#   r   c           	         |t        ||||      }n!t        d ||||fD              rt        d      t        | j                  | j                  |j                        | j                  | j
                  |j
                        | j                  | j                  |j                        | j                  | j                  |j                              S )ai  Returns new _Mapping with args merged with self.

    Args:
      x: `Tensor`. Forward.
      y: `Tensor`. Inverse.
      ildj_map: `Dictionary`. This is a mapping from event_ndims to a `Tensor`
        representing the inverse log det jacobian.
      kwargs: Python dictionary. Extra args supplied to
        forward/inverse/etc functions.
      mapping: Instance of _Mapping to merge. Can only be specified if no other
        arg is specified.

    Returns:
      mapping: New instance of `_Mapping` which has inputs merged with self.

    Raises:
      ValueError: if mapping and any other arg is not `None`.
    r   r   r   r   c              3   $   K   | ]  }|d u 
 y wN ).0args     r   	<genexpr>z!_Mapping.merge.<locals>.<genexpr>]   s     AS_As   z?Cannot simultaneously specify mapping and individual arguments.)	r   any
ValueError_merger   r   _merge_dictsr   r   )r!   r   r   r   r   mappings         r   mergez_Mapping.mergeH   s    & 1HVDg	AAx(@A	A $ % % 
++dffgii
(
++dffgii
(""4=='2B2BC{{4;;7	9 9r   c                     |i n|}|i n|}|j                         D ]A  \  }}|j                  |d      }|#||urt        dj                  |||   |            |||<   C |S )z!Helper to merge two dictionaries.NzHFound different value for existing key (key:{} old_value:{} new_value:{})r   getr/   format)r!   oldnewkvvals         r   r1   z_Mapping._merge_dictsg   s    "C"C		 1GGAtc	S\ ==CVA>+, 	, c!f Jr   c                 <    ||S |||urt        d|d|      |S )z0Helper to merge which handles merging one value.zIncompatible values: z != )r/   )r!   r7   r8   s      r   r0   z_Mapping._merget   s,    
{j	S^#sCDDJr   c                 p    t        |t        t        f      rt        t        | j                  |            S |S )z,Converts lists of lists to tuples of tuples.)
isinstancelistr   mapr   r!   r   s     r   r   z_Mapping._deep_tuple|   s6     !dE]+ #d&&*+ 4124r   )NNNN)NNNNNNN)__name__
__module____qualname____doc__r   propertyr"   r%   r3   r1   r0   r   __classcell__)r   s   @r   r   r   (   sL    GE  B B
 B B
9>4r   r   r'   c                      e Zd ZdZej
                  	 	 	 	 	 	 	 d(d       Zed        Zed        Z	ed        Z
ed        Zed        Zed	        Zed
        Zed        Zd Z	 d)dZd Zd Zd Z	 d*dZd Zd Zd Zd Zd+dZd Zd Zd,dZd Zd Z	 d-dZ d Z!d Z"	 d.dZ#e$jJ                  d/d        Z&d! Z'd" Z(d0d#Z)d$ Z*d% Z+d& Z,d' Z-y)1r   a2  Interface for transformations of a `Distribution` sample.

  Bijectors can be used to represent any differentiable and injective
  (one to one) function defined on an open subset of `R^n`.  Some non-injective
  transformations are also supported (see "Non Injective Transforms" below).

  #### Mathematical Details

  A `Bijector` implements a [smooth covering map](
  https://en.wikipedia.org/wiki/Local_diffeomorphism), i.e., a local
  diffeomorphism such that every point in the target has a neighborhood evenly
  covered by a map ([see also](
  https://en.wikipedia.org/wiki/Covering_space#Covering_of_a_manifold)).
  A `Bijector` is used by `TransformedDistribution` but can be generally used
  for transforming a `Distribution` generated `Tensor`. A `Bijector` is
  characterized by three operations:

  1. Forward

     Useful for turning one random outcome into another random outcome from a
     different distribution.

  2. Inverse

     Useful for "reversing" a transformation to compute one probability in
     terms of another.

  3. `log_det_jacobian(x)`

     "The log of the absolute value of the determinant of the matrix of all
     first-order partial derivatives of the inverse function."

     Useful for inverting a transformation to compute one probability in terms
     of another. Geometrically, the Jacobian determinant is the volume of the
     transformation and is used to scale the probability.

     We take the absolute value of the determinant before log to avoid NaN
     values.  Geometrically, a negative determinant corresponds to an
     orientation-reversing transformation.  It is ok for us to discard the sign
     of the determinant because we only integrate everywhere-nonnegative
     functions (probability densities) and the correct orientation is always the
     one that produces a nonnegative integrand.

  By convention, transformations of random variables are named in terms of the
  forward transformation. The forward transformation creates samples, the
  inverse is useful for computing probabilities.

  #### Example Uses

  - Basic properties:

  ```python
  x = ...  # A tensor.
  # Evaluate forward transformation.
  fwd_x = my_bijector.forward(x)
  x == my_bijector.inverse(fwd_x)
  x != my_bijector.forward(fwd_x)  # Not equal because x != g(g(x)).
  ```

  - Computing a log-likelihood:

  ```python
  def transformed_log_prob(bijector, log_prob, x):
    return (bijector.inverse_log_det_jacobian(x, event_ndims=0) +
            log_prob(bijector.inverse(x)))
  ```

  - Transforming a random outcome:

  ```python
  def transformed_sample(bijector, x):
    return bijector.forward(x)
  ```

  #### Example Bijectors

  - "Exponential"

    ```none
    Y = g(X) = exp(X)
    X ~ Normal(0, 1)  # Univariate.
    ```

    Implies:

    ```none
      g^{-1}(Y) = log(Y)
      |Jacobian(g^{-1})(y)| = 1 / y
      Y ~ LogNormal(0, 1), i.e.,
      prob(Y=y) = |Jacobian(g^{-1})(y)| * prob(X=g^{-1}(y))
                = (1 / y) Normal(log(y); 0, 1)
    ```

    Here is an example of how one might implement the `Exp` bijector:

    ```python
      class Exp(Bijector):

        def __init__(self, validate_args=False, name="exp"):
          super(Exp, self).__init__(
              validate_args=validate_args,
              forward_min_event_ndims=0,
              name=name)

        def _forward(self, x):
          return math_ops.exp(x)

        def _inverse(self, y):
          return math_ops.log(y)

        def _inverse_log_det_jacobian(self, y):
          return -self._forward_log_det_jacobian(self._inverse(y))

        def _forward_log_det_jacobian(self, x):
          # Notice that we needn't do any reducing, even when`event_ndims > 0`.
          # The base Bijector class will handle reducing for us; it knows how
          # to do so because we called `super` `__init__` with
          # `forward_min_event_ndims = 0`.
          return x
      ```

  - "Affine"

    ```none
    Y = g(X) = sqrtSigma * X + mu
    X ~ MultivariateNormal(0, I_d)
    ```

    Implies:

    ```none
      g^{-1}(Y) = inv(sqrtSigma) * (Y - mu)
      |Jacobian(g^{-1})(y)| = det(inv(sqrtSigma))
      Y ~ MultivariateNormal(mu, sqrtSigma) , i.e.,
      prob(Y=y) = |Jacobian(g^{-1})(y)| * prob(X=g^{-1}(y))
                = det(sqrtSigma)^(-d) *
                  MultivariateNormal(inv(sqrtSigma) * (y - mu); 0, I_d)
      ```

  #### Min_event_ndims and Naming

  Bijectors are named for the dimensionality of data they act on (i.e. without
  broadcasting). We can think of bijectors having an intrinsic `min_event_ndims`
  , which is the minimum number of dimensions for the bijector act on. For
  instance, a Cholesky decomposition requires a matrix, and hence
  `min_event_ndims=2`.

  Some examples:

  `AffineScalar:  min_event_ndims=0`
  `Affine:  min_event_ndims=1`
  `Cholesky:  min_event_ndims=2`
  `Exp:  min_event_ndims=0`
  `Sigmoid:  min_event_ndims=0`
  `SoftmaxCentered:  min_event_ndims=1`

  Note the difference between `Affine` and `AffineScalar`. `AffineScalar`
  operates on scalar events, whereas `Affine` operates on vector-valued events.

  More generally, there is a `forward_min_event_ndims` and an
  `inverse_min_event_ndims`. In most cases, these will be the same.
  However, for some shape changing bijectors, these will be different
  (e.g. a bijector which pads an extra dimension at the end, might have
  `forward_min_event_ndims=0` and `inverse_min_event_ndims=1`.


  #### Jacobian Determinant

  The Jacobian determinant is a reduction over `event_ndims - min_event_ndims`
  (`forward_min_event_ndims` for `forward_log_det_jacobian` and
  `inverse_min_event_ndims` for `inverse_log_det_jacobian`).
  To see this, consider the `Exp` `Bijector` applied to a `Tensor` which has
  sample, batch, and event (S, B, E) shape semantics. Suppose the `Tensor`'s
  partitioned-shape is `(S=[4], B=[2], E=[3, 3])`. The shape of the `Tensor`
  returned by `forward` and `inverse` is unchanged, i.e., `[4, 2, 3, 3]`.
  However the shape returned by `inverse_log_det_jacobian` is `[4, 2]` because
  the Jacobian determinant is a reduction over the event dimensions.

  Another example is the `Affine` `Bijector`. Because `min_event_ndims = 1`, the
  Jacobian determinant reduction is over `event_ndims - 1`.

  It is sometimes useful to implement the inverse Jacobian determinant as the
  negative forward Jacobian determinant. For example,

  ```python
  def _inverse_log_det_jacobian(self, y):
     return -self._forward_log_det_jac(self._inverse(y))  # Note negation.
  ```

  The correctness of this approach can be seen from the following claim.

  - Claim:

      Assume `Y = g(X)` is a bijection whose derivative exists and is nonzero
      for its domain, i.e., `dY/dX = d/dX g(X) != 0`. Then:

      ```none
      (log o det o jacobian o g^{-1})(Y) = -(log o det o jacobian o g)(X)
      ```

  - Proof:

      From the bijective, nonzero differentiability of `g`, the
      [inverse function theorem](
          https://en.wikipedia.org/wiki/Inverse_function_theorem)
      implies `g^{-1}` is differentiable in the image of `g`.
      Applying the chain rule to `y = g(x) = g(g^{-1}(y))` yields
      `I = g'(g^{-1}(y))*g^{-1}'(y)`.
      The same theorem also implies `g^{-1}'` is non-singular therefore:
      `inv[ g'(g^{-1}(y)) ] = g^{-1}'(y)`.
      The claim follows from [properties of determinant](
  https://en.wikipedia.org/wiki/Determinant#Multiplicativity_and_matrix_groups).

  Generally its preferable to directly implement the inverse Jacobian
  determinant.  This should have superior numerical stability and will often
  share subgraphs with the `_inverse` implementation.

  #### Is_constant_jacobian

  Certain bijectors will have constant jacobian matrices. For instance, the
  `Affine` bijector encodes multiplication by a matrix plus a shift, with
  jacobian matrix, the same aforementioned matrix.

  `is_constant_jacobian` encodes the fact that the jacobian matrix is constant.
  The semantics of this argument are the following:

    * Repeated calls to "log_det_jacobian" functions with the same
      `event_ndims` (but not necessarily same input), will return the first
      computed jacobian (because the matrix is constant, and hence is input
      independent).
    * `log_det_jacobian` implementations are merely broadcastable to the true
      `log_det_jacobian` (because, again, the jacobian matrix is input
      independent). Specifically, `log_det_jacobian` is implemented as the
      log jacobian determinant for a single input.

      ```python
      class Identity(Bijector):

        def __init__(self, validate_args=False, name="identity"):
          super(Identity, self).__init__(
              is_constant_jacobian=True,
              validate_args=validate_args,
              forward_min_event_ndims=0,
              name=name)

        def _forward(self, x):
          return x

        def _inverse(self, y):
          return y

        def _inverse_log_det_jacobian(self, y):
          return -self._forward_log_det_jacobian(self._inverse(y))

        def _forward_log_det_jacobian(self, x):
          # The full log jacobian determinant would be array_ops.zero_like(x).
          # However, we circumvent materializing that, since the jacobian
          # calculation is input independent, and we specify it for one input.
          return constant_op.constant(0., x.dtype.base_dtype)

      ```

  #### Subclass Requirements

  - Subclasses typically implement:

      - `_forward`,
      - `_inverse`,
      - `_inverse_log_det_jacobian`,
      - `_forward_log_det_jacobian` (optional).

    The `_forward_log_det_jacobian` is called when the bijector is inverted via
    the `Invert` bijector. If undefined, a slightly less efficiently
    calculation, `-1 * _inverse_log_det_jacobian`, is used.

    If the bijector changes the shape of the input, you must also implement:

      - _forward_event_shape_tensor,
      - _forward_event_shape (optional),
      - _inverse_event_shape_tensor,
      - _inverse_event_shape (optional).

    By default the event-shape is assumed unchanged from input.

  - If the `Bijector`'s use is limited to `TransformedDistribution` (or friends
    like `QuantizedDistribution`) then depending on your use, you may not need
    to implement all of `_forward` and `_inverse` functions.

    Examples:

      1. Sampling (e.g., `sample`) only requires `_forward`.
      2. Probability functions (e.g., `prob`, `cdf`, `survival`) only require
         `_inverse` (and related).
      3. Only calling probability functions on the output of `sample` means
        `_inverse` can be implemented as a cache lookup.

    See "Example Uses" [above] which shows how these functions are used to
    transform a distribution. (Note: `_forward` could theoretically be
    implemented as a cache lookup but this would require controlling the
    underlying sample generation mechanism.)

  #### Non Injective Transforms

  **WARNING** Handing of non-injective transforms is subject to change.

  Non injective maps `g` are supported, provided their domain `D` can be
  partitioned into `k` disjoint subsets, `Union{D1, ..., Dk}`, such that,
  ignoring sets of measure zero, the restriction of `g` to each subset is a
  differentiable bijection onto `g(D)`.  In particular, this implies that for
  `y in g(D)`, the set inverse, i.e. `g^{-1}(y) = {x in D : g(x) = y}`, always
  contains exactly `k` distinct points.

  The property, `_is_injective` is set to `False` to indicate that the bijector
  is not injective, yet satisfies the above condition.

  The usual bijector API is modified in the case `_is_injective is False` (see
  method docstrings for specifics).  Here we show by example the `AbsoluteValue`
  bijector.  In this case, the domain `D = (-inf, inf)`, can be partitioned
  into `D1 = (-inf, 0)`, `D2 = {0}`, and `D3 = (0, inf)`.  Let `gi` be the
  restriction of `g` to `Di`, then both `g1` and `g3` are bijections onto
  `(0, inf)`, with `g1^{-1}(y) = -y`, and `g3^{-1}(y) = y`.  We will use
  `g1` and `g3` to define bijector methods over `D1` and `D3`.  `D2 = {0}` is
  an oddball in that `g2` is one to one, and the derivative is not well defined.
  Fortunately, when considering transformations of probability densities
  (e.g. in `TransformedDistribution`), sets of measure zero have no effect in
  theory, and only a small effect in 32 or 64 bit precision.  For that reason,
  we define `inverse(0)` and `inverse_log_det_jacobian(0)` both as `[0, 0]`,
  which is convenient and results in a left-semicontinuous pdf.


  ```python
  abs = tfp.distributions.bijectors.AbsoluteValue()

  abs.forward(-1.)
  ==> 1.

  abs.forward(1.)
  ==> 1.

  abs.inverse(1.)
  ==> (-1., 1.)

  # The |dX/dY| is constant, == 1.  So Log|dX/dY| == 0.
  abs.inverse_log_det_jacobian(1., event_ndims=0)
  ==> (0., 0.)

  # Special case handling of 0.
  abs.inverse(0.)
  ==> (0., 0.)

  abs.inverse_log_det_jacobian(0., event_ndims=0)
  ==> (0., 0.)
  ```

  Nc                    |xs g | _         ||t        d      ||}n||}t        |t              s-t	        dj                  t        |      j                              t        |t              s-t	        dj                  t        |      j                              |dk  rt        d      |dk  rt        d      || _        || _	        || _
        i | _        || _        || _        i | _        i | _        |r|| _        n2d } |t        |       j                  j#                  d	            | _        t%        | j                         D ],  \  }	}
|
t'        j(                  |
      rt        d
|	|
fz         y)a  Constructs Bijector.

    A `Bijector` transforms random variables into new random variables.

    Examples:

    ```python
    # Create the Y = g(X) = X transform.
    identity = Identity()

    # Create the Y = g(X) = exp(X) transform.
    exp = Exp()
    ```

    See `Bijector` subclass docstring for more details and specific examples.

    Args:
      graph_parents: Python list of graph prerequisites of this `Bijector`.
      is_constant_jacobian: Python `bool` indicating that the Jacobian matrix is
        not a function of the input.
      validate_args: Python `bool`, default `False`. Whether to validate input
        with asserts. If `validate_args` is `False`, and the inputs are invalid,
        correct behavior is not guaranteed.
      dtype: `tf.dtype` supported by this `Bijector`. `None` means dtype is not
        enforced.
      forward_min_event_ndims: Python `integer` indicating the minimum number of
        dimensions `forward` operates on.
      inverse_min_event_ndims: Python `integer` indicating the minimum number of
        dimensions `inverse` operates on. Will be set to
        `forward_min_event_ndims` by default, if no value is provided.
      name: The name to give Ops created by the initializer.

    Raises:
      ValueError:  If neither `forward_min_event_ndims` and
        `inverse_min_event_ndims` are specified, or if either of them is
        negative.
      ValueError:  If a member of `graph_parents` is not a `Tensor`.
    NzUMust specify at least one of `forward_min_event_ndims` and `inverse_min_event_ndims`.z:Expected forward_min_event_ndims to be of type int, got {}z:Expected inverse_min_event_ndims to be of type int, got {}r   z7forward_min_event_ndims must be a non-negative integer.z7inverse_min_event_ndims must be a non-negative integer.c                 z    t        j                  dd|       }t        j                  dd|      j                         S )Nz(.)([A-Z][a-z]+)z\1_\2z([a-z0-9])([A-Z]))resublower)names1s     r   camel_to_snakez)Bijector.__init__.<locals>.camel_to_snake?  s2    VV&$7vv)8R8>>@@r   _z)Graph parent item %d is not a Tensor; %s.)_graph_parentsr/   r>   int	TypeErrorr6   typerC   _forward_min_event_ndims_inverse_min_event_ndims_is_constant_jacobian_constant_ildj_map_validate_args_dtype_from_y_from_x_namelstrip	enumerater   
is_tf_type)r!   graph_parentsis_constant_jacobianvalidate_argsdtypeforward_min_event_ndimsinverse_min_event_ndimsrO   rQ   its              r   __init__zBijector.__init__  s   ^ (-2D&+B+J 8 9 9	 	( 7	 	( 7-s3 ))/67@@*BC C -s3 ))/67@@*BC C " " # #" " # # %<D!$;D!!5D D'DDKDLDLdjA "$t*"5"5"<"<S"ABdj$--. O1	
+003D1vMNNOr   c                     | j                   S )z9Returns this `Bijector`'s graph_parents as a Python list.)rS   r    s    r   rc   zBijector.graph_parentsH       r   c                     | j                   S )zFReturns the minimal number of dimensions bijector.forward operates on.)rW   r    s    r   rg   z Bijector.forward_min_event_ndimsM       (((r   c                     | j                   S )zFReturns the minimal number of dimensions bijector.inverse operates on.)rX   r    s    r   rh   z Bijector.inverse_min_event_ndimsR  ro   r   c                     | j                   S )zReturns true iff the Jacobian matrix is not a function of x.

    Note: Jacobian matrix is either constant for both forward and inverse or
    neither.

    Returns:
      is_constant_jacobian: Python `bool`.
    )rY   r    s    r   rd   zBijector.is_constant_jacobianW  s     %%%r   c                      y)a  Returns true iff the forward map `g` is injective (one-to-one function).

    **WARNING** This hidden property and its behavior are subject to change.

    Note:  Non-injective maps `g` are supported, provided their domain `D` can
    be partitioned into `k` disjoint subsets, `Union{D1, ..., Dk}`, such that,
    ignoring sets of measure zero, the restriction of `g` to each subset is a
    differentiable bijection onto `g(D)`.

    Returns:
      is_injective: Python `bool`.
    Tr*   r    s    r   _is_injectivezBijector._is_injectivec  s     r   c                     | j                   S )z3Returns True if Tensor arguments will be validated.)r[   r    s    r   re   zBijector.validate_argss  rm   r   c                     | j                   S )z6dtype of `Tensor`s transformable by this distribution.)r\   r    s    r   rf   zBijector.dtypex  s     ;;r   c                     | j                   S )z+Returns the string name of this `Bijector`.)r_   r    s    r   rO   zBijector.name}  s     ::r   c                     |S )zBSubclass implementation for `forward_event_shape_tensor` function.r*   r!   input_shapes     r   _forward_event_shape_tensorz$Bijector._forward_event_shape_tensor  
     r   c                     | j                  ||g      5  t        j                  |t        j                  d      }| j                  |      cddd       S # 1 sw Y   yxY w)aw  Shape of a single sample from a single batch as an `int32` 1D `Tensor`.

    Args:
      input_shape: `Tensor`, `int32` vector indicating event-portion shape
        passed into `forward` function.
      name: name to give to the op

    Returns:
      forward_event_shape_tensor: `Tensor`, `int32` vector indicating
        event-portion shape after applying `forward`.
    ry   rf   rO   N)_name_scoper   convert_to_tensorr   int32rz   )r!   ry   rO   s      r   forward_event_shape_tensorz#Bijector.forward_event_shape_tensor  sT     
		$	. ;))+V\\/<>k--k:; ; ;   7AAc                     |S )zBSubclass implementation for `forward_event_shape` public function.r*   rx   s     r   _forward_event_shapezBijector._forward_event_shape  r{   r   c                 J    | j                  t        j                  |            S )a  Shape of a single sample from a single batch as a `TensorShape`.

    Same meaning as `forward_event_shape_tensor`. May be only partially defined.

    Args:
      input_shape: `TensorShape` indicating event-portion shape passed into
        `forward` function.

    Returns:
      forward_event_shape_tensor: `TensorShape` indicating event-portion shape
        after applying `forward`. Possibly unknown.
    )r   r   TensorShaperx   s     r   forward_event_shapezBijector.forward_event_shape  s      $$\%=%=k%JKKr   c                     |S )zBSubclass implementation for `inverse_event_shape_tensor` function.r*   r!   output_shapes     r   _inverse_event_shape_tensorz$Bijector._inverse_event_shape_tensor  s
     r   c                     | j                  ||g      5  t        j                  |t        j                  d      }| j                  |      cddd       S # 1 sw Y   yxY w)ax  Shape of a single sample from a single batch as an `int32` 1D `Tensor`.

    Args:
      output_shape: `Tensor`, `int32` vector indicating event-portion shape
        passed into `inverse` function.
      name: name to give to the op

    Returns:
      inverse_event_shape_tensor: `Tensor`, `int32` vector indicating
        event-portion shape after applying `inverse`.
    r   r}   N)r~   r   r   r   r   r   )r!   r   rO   s      r   inverse_event_shape_tensorz#Bijector.inverse_event_shape_tensor  sU     
		$	/ <**<v||0>@l--l;< < <r   c                 ,    t        j                  |      S )zBSubclass implementation for `inverse_event_shape` public function.)r   r   r   s     r   _inverse_event_shapezBijector._inverse_event_shape  s     ##L11r   c                 $    | j                  |      S )a  Shape of a single sample from a single batch as a `TensorShape`.

    Same meaning as `inverse_event_shape_tensor`. May be only partially defined.

    Args:
      output_shape: `TensorShape` indicating event-portion shape passed into
        `inverse` function.

    Returns:
      inverse_event_shape_tensor: `TensorShape` indicating event-portion shape
        after applying `inverse`. Possibly unknown.
    )r   r   s     r   inverse_event_shapezBijector.inverse_event_shape  s     $$\22r   c                     t        d      )z6Subclass implementation for `forward` public function.zforward not implemented.NotImplementedErrorrA   s     r   _forwardzBijector._forward  s    
8
99r   c                    | j                  ||g      5  t        j                  |d      }| j                  |       | j                  s | j
                  |fi |cd d d        S | j                  ||      }|j                  |j                  cd d d        S |j                   | j
                  |fi |      }| j                  |       |j                  cd d d        S # 1 sw Y   y xY w)Nr   rO   r   r   )r   )
r~   r   r   _maybe_assert_dtypers   r   _lookupr   r3   _cache)r!   r   rO   r   r2   s        r   _call_forwardzBijector._call_forward      			$	$ 




,a
q!t}}Q)&)	
 

 q0g		yy
 
 a :6 :;g
kk'YY
 
 
   AC"%*C"?C""C+c                 &    | j                  ||      S )ak  Returns the forward `Bijector` evaluation, i.e., X = g(Y).

    Args:
      x: `Tensor`. The input to the "forward" evaluation.
      name: The name to give this op.

    Returns:
      `Tensor`.

    Raises:
      TypeError: if `self.dtype` is specified and `x.dtype` is not
        `self.dtype`.
      NotImplementedError: if `_forward` is not implemented.
    )r   )r!   r   rO   s      r   forwardzBijector.forward  s     a&&r   c                     t        d      )z6Subclass implementation for `inverse` public function.zinverse not implementedr   r!   r   s     r   _inversezBijector._inverse  s    
7
88r   c                    | j                  ||g      5  t        j                  |d      }| j                  |       | j                  s | j
                  |fi |cd d d        S | j                  ||      }|j                  |j                  cd d d        S |j                   | j
                  |fi |      }| j                  |       |j                  cd d d        S # 1 sw Y   y xY w)Nr   r   r   r   )r   )
r~   r   r   r   rs   r   r   r   r3   r   )r!   r   rO   r   r2   s        r   _call_inversezBijector._call_inverse   r   r   c                 &    | j                  ||      S )a  Returns the inverse `Bijector` evaluation, i.e., X = g^{-1}(Y).

    Args:
      y: `Tensor`. The input to the "inverse" evaluation.
      name: The name to give this op.

    Returns:
      `Tensor`, if this bijector is injective.
        If not injective, returns the k-tuple containing the unique
        `k` points `(x1, ..., xk)` such that `g(xi) = y`.

    Raises:
      TypeError: if `self.dtype` is specified and `y.dtype` is not
        `self.dtype`.
      NotImplementedError: if `_inverse` is not implemented.
    )r   )r!   r   rO   s      r   inversezBijector.inverse  s    " a&&r   c                     t        d      )a_  Subclass implementation of `inverse_log_det_jacobian` public function.

    In particular, this method differs from the public function, in that it
    does not take `event_ndims`. Thus, this implements the minimal Jacobian
    determinant calculation (i.e. over `inverse_min_event_ndims`).

    Args:
      y: `Tensor`. The input to the "inverse_log_det_jacobian" evaluation.
    Returns:
      inverse_log_det_jacobian: `Tensor`, if this bijector is injective.
        If not injective, returns the k-tuple containing jacobians for the
        unique `k` points `(x1, ..., xk)` such that `g(xi) = y`.
    z)inverse_log_det_jacobian not implemented.r   r   s     r   _inverse_log_det_jacobianz"Bijector._inverse_log_det_jacobian   s     I
JJr   c           	         
  j                  |g      5   j                  v r j                     cd d d        S t        j                  d       j	                         t        j
                   j                   j                              5   j                  s<	   j                  fi |}t         fd|D              cd d d        cd d d        S  j                  |      }|j                  /|j                  v r!|j                     cd d d        cd d d        S 	 d 
  j                  fi |}	 j!                  |	 j                        }	|j'                  
|	i      } j)                  |        j*                  r|	 j                  <   |	cd d d        cd d d        S # t        $ rh}	   j                  fi |
  j                  
fi |}t         
fd|D              cY d }~cd d d        cd d d        S # t        $ r |w xY wd }~ww xY w# t        $ ry}	 |j"                  |j"                  n  j                  fi |
  j                  
fi | }	 j!                  
|	 j$                        }	n# t        $ r |w xY wY d }~Fd }~ww xY w# 1 sw Y   nxY w	 d d d        y # 1 sw Y   y xY w)Nr   r   min_event_ndimsevent_ndimsc              3   Z   K   | ]"  }j                  |j                         $ y wr)   _reduce_jacobian_det_over_eventrh   r+   ildjr   r!   r   s     r   r-   z:Bijector._call_inverse_log_det_jacobian.<locals>.<genexpr><  4      ,! ==455{D ,   (+c              3   \   K   | ]#  }j                  | j                         % y wr)   r   rg   r+   fldjr   r!   r   s     r   r-   z:Bijector._call_inverse_log_det_jacobian.<locals>.<genexpr>C  6      .#  ??dUD88+G .   ),r   )r   r   )r~   rZ   r   r   r   control_dependencies_check_valid_event_ndimsrh   rs   r   r   r   r   _forward_log_det_jacobianr   r   r   r   rg   r3   r   rd   )r!   r   r   rO   r   ildjsoriginal_exceptionfldjsr2   r   r   s   ```       @r   _call_inverse_log_det_jacobianz'Bijector._call_inverse_log_det_jacobian0  s   			$	$ .	//	/&&{3. . 


,a
q!##D$A$A66! %B %# $ ) !!'2D221??E ,%*, ,) ). .0 ,,6,2'K7;K;K,K!!+.+) ). .6	%!///<V<$55t33[B$ --!{D.A-BG$$15$
!
!+
.S) ). . % ''$--,V,a4d44QA&Ae .',. . .) ). .* ' '&&''$ # 	%%%ii3#dmmA00 2D221???D77455{DD$ %$$% 	%7) ) ). . .s   KAKJ0%(F7	K ;J0	K/3H+"AJ0$	K7	H(;H<H(=J0	KH 	 H##H((J0+	J-5AJJ(J	J("J0(J--J00J9	5KKc                 (    | j                  |||      S )as  Returns the (log o det o Jacobian o inverse)(y).

    Mathematically, returns: `log(det(dX/dY))(Y)`. (Recall that: `X=g^{-1}(Y)`.)

    Note that `forward_log_det_jacobian` is the negative of this function,
    evaluated at `g^{-1}(y)`.

    Args:
      y: `Tensor`. The input to the "inverse" Jacobian determinant evaluation.
      event_ndims: Number of dimensions in the probabilistic events being
        transformed. Must be greater than or equal to
        `self.inverse_min_event_ndims`. The result is summed over the final
        dimensions to produce a scalar Jacobian determinant for each event,
        i.e. it has shape `y.shape.ndims - event_ndims` dimensions.
      name: The name to give this op.

    Returns:
      `Tensor`, if this bijector is injective.
        If not injective, returns the tuple of local log det
        Jacobians, `log(det(Dg_i^{-1}(y)))`, where `g_i` is the restriction
        of `g` to the `ith` partition `Di`.

    Raises:
      TypeError: if `self.dtype` is specified and `y.dtype` is not
        `self.dtype`.
      NotImplementedError: if `_inverse_log_det_jacobian` is not implemented.
    )r   )r!   r   r   rO   s       r   inverse_log_det_jacobianz!Bijector.inverse_log_det_jacobiana  s    : ..q+tDDr   c                     t        d      )a`  Subclass implementation of `forward_log_det_jacobian` public function.

    In particular, this method differs from the public function, in that it
    does not take `event_ndims`. Thus, this implements the minimal Jacobian
    determinant calculation (i.e. over `forward_min_event_ndims`).

    Args:
      x: `Tensor`. The input to the "forward_log_det_jacobian" evaluation.

    Returns:
      forward_log_det_jacobian: `Tensor`, if this bijector is injective.
        If not injective, returns the k-tuple containing jacobians for the
        unique `k` points `(x1, ..., xk)` such that `g(xi) = y`.
    z)forward_log_det_jacobian not implemented.r   rA   s     r   r   z"Bijector._forward_log_det_jacobian  s      35 5r   c           	         
  j                   st        d       j                  |g      5  t        j                   j                   j                              5   j                  v r$d j                     z  cd d d        cd d d        S t        j                  d       j                          j                   s<	   j                  fi |}t         fd|D              cd d d        cd d d        S  j                  |      }|j                  0|j                  v r"|j                      cd d d        cd d d        S 	 d 
  j                  fi | }	 j!                  |	 j                        }	|j'                  
|	i	      } j)                  |        j*                  r|	 j                  <   |	 cd d d        cd d d        S # t        $ rh}	   j                  fi |
  j                  
fi |}t         
fd|D              cY d }~cd d d        cd d d        S # t        $ r |w xY wd }~ww xY w# t        $ rx}	 |j"                  |j"                  n  j                  fi |
  j                  
fi |}	 j!                  
|	 j$                        }	n# t        $ r |w xY wY d }~Fd }~ww xY w# 1 sw Y   nxY w	 d d d        y # 1 sw Y   y xY w)
NzLforward_log_det_jacobian cannot be implemented for non-injective transforms.r   g      r   r   c              3   Z   K   | ]"  }j                  |j                         $ y wr)   r   r   s     r   r-   z:Bijector._call_forward_log_det_jacobian.<locals>.<genexpr>  r   r   c              3   \   K   | ]#  }j                  | j                         % y wr)   r   r   s     r   r-   z:Bijector._call_forward_log_det_jacobian.<locals>.<genexpr>  r   r   r   )r   r   )rs   r   r~   r   r   r   rg   rZ   r   r   r   r   r   r   r   r   r   r   rh   r3   r   rd   )r!   r   r   rO   r   r   r   r   r2   r   r   s   ```       @r   _call_forward_log_det_jacobianz'Bijector._call_forward_log_det_jacobian  s4     
		$	$ -##D$A$A66! %B %# $ , $111t..{;;, ,- - !!!#.  #!!'2D221??E ,%*, ,, ,- -0 ,,6,2'K7;K;K,K"";//3, ,- -6	%!0$00=f==$55t33[B$ --!{D.A-BG$$15$
!
!+
.uY, ,- - % ''$--,V,a4d44QA&Ae .',. . .%, ,- -, ' '&&''" # 	%%%ii3#dmmA00 1411!>v>D77455{DD$ %$$% 	%?, , ,- - -s   1K+  K 	K+4K(G0	K+<K?	K+4IAK
	K+	I';H:"I#K'	K+:I	I		IK	KAJ87K8K	KKKKK	K++K4c                 (    | j                  |||      S )a  Returns both the forward_log_det_jacobian.

    Args:
      x: `Tensor`. The input to the "forward" Jacobian determinant evaluation.
      event_ndims: Number of dimensions in the probabilistic events being
        transformed. Must be greater than or equal to
        `self.forward_min_event_ndims`. The result is summed over the final
        dimensions to produce a scalar Jacobian determinant for each event,
        i.e. it has shape `x.shape.ndims - event_ndims` dimensions.
      name: The name to give this op.

    Returns:
      `Tensor`, if this bijector is injective.
        If not injective this is not implemented.

    Raises:
      TypeError: if `self.dtype` is specified and `y.dtype` is not
        `self.dtype`.
      NotImplementedError: if neither `_forward_log_det_jacobian`
        nor {`_inverse`, `_inverse_log_det_jacobian`} are implemented, or
        this is a non-injective bijector.
    )r   )r!   r   r   rO   s       r   forward_log_det_jacobianz!Bijector.forward_log_det_jacobian  s    0 ..q+tDDr   c              #      K   t        j                  | j                        5  t        j                  ||xs g | j                  z         5 }| ddd       ddd       y# 1 sw Y   xY w# 1 sw Y   yxY ww)z(Helper function to standardize op scope.)valuesN)r   
name_scoperO   rc   )r!   rO   r   scopes       r   r~   zBijector._name_scope  sn      
			" >>
"(:(::< ?D   s4    A9)A-A!A-	A9!A*	&A--A62A9c                     | j                   T| j                   j                  |j                   j                  k7  r&t        d| j                   d|j                   d      yy)z/Helper to check dtype when self.dtype is known.NzInput had dtype z but expected .)rf   
base_dtyperU   rA   s     r   r   zBijector._maybe_assert_dtype  sO    zz$**"7"7177;M;M"Mzz177, - - #Nr   c                 0   |j                  | j                  |j                  |j                  |j                              }|j                  |j                  t        d      || j                  |j                  <   || j                  |j                  <   y)z:Helper which stores mapping info in forward/inverse dicts.)r2   NzBCaching expects at least one of (x,y) to be known, i.e., not None.)
r3   r   r   r   r   r/   r^   r"   r]   r%   )r!   r2   s     r   r   zBijector._cache  s{     mmDLL		799gnn%.m /GyyWYY. ) * *")DLL")DLLr   c                     t        |||      }|j                  &| j                  j                  |j                  |      S |j
                  &| j                  j                  |j                  |      S |S )z?Helper which retrieves mapping info from forward/inverse dicts.)r   r   r   )r   r   r^   r5   r"   r   r]   r%   )r!   r   r   r   r2   s        r   r   zBijector._lookup  sa    a/G yy\\gmmW55yy\\gmmW55Nr   c                    t        j                  |      }t        j                  |      ||z
  ||z
   }t        j                  ||j                        }t        j                  ||z  | j                  ||            }| j                  |      }	|	|j                  j                  |j                  j                  |j                  |j                  j                  |	z
  |j                  j                  |z
   }t        j                  |j                  |      }
|j                  |
d|
j                  |	|z
  z
          |S )z3Reduce jacobian over event_ndims - min_event_ndims.)axisN)r   rankshapeonesrf   r	   
reduce_sum_get_event_reduce_dims_maybe_get_static_event_ndimsndimsbroadcast_static_shape	set_shape)r!   r   r   r   r   y_ranky_shaper   reduced_ildjevent_ndims_broadcast_shapes              r   r   z(Bijector._reduce_jacobian_det_over_event  s#    ^^AFooa v79G >>'4::.D&&t((+FHL
 55kBL 	!

$479g!88WMo
 .O11_,. /0 r   c                     | j                  |      }|!t        d||z
  dz         D cg c]  }|  c}S ||z
  }t        j                  | d      S c c}w )z3Compute the reduction dimensions given event_ndims.   r   )r   ranger	   )r!   r   r   r   indexreduce_ndimss         r   r   zBijector._get_event_reduce_dims!  s_    55kBL"'</+IA+M"NOufOO ?2l^^\M1-- Ps   
Ac                    t        j                  |d      }t        j                  |      }g }|j                  j
                  s$t        dj                  |j                              |]|j                  j                  dk7  r$t        dj                  |j                              ||kD  rAt        dj                  ||            | j                  r|t        j                  ||      gz  }|j                  j                         rI|j                  j                  dk7  r.t        dj                  |j                  j                              |S | j                  r|t        j                  |dd	      gz  }|S )
z6Check whether event_ndims is at least min_event_ndims.r   r   $Expected integer dtype, got dtype {}r   z)Expected scalar event_ndims, got shape {}z9event_ndims ({}) must be larger than min_event_ndims ({})z#Expected scalar shape, got ndims {}zExpected scalar.)message)r   r   r   constant_valuerf   
is_integerr/   r6   r   r   re   r   assert_greater_equalis_fully_definedassert_rank)r!   r   r   r   
assertionss        r   r   z!Bijector._check_valid_event_ndims+  s   ''-HK--k:LJ''=DD


   				 	 A	%DKK   	 	<	' 006)?1<= 	= 
		

(
(o
FH Hj ))+				 	 A	%>EE##% & 	&  
		


Q8J
KM Mjr   c                    t        j                  |      }t        |t        j                  t        j
                  f      r|j                  t        j                  t        j                  fvr$t        dj                  |j                              t        |t        j
                        r/t        |j                        rt        dj                  |            t        |      }|S )z=Helper which returns tries to return an integer static value.r   z!Expected a scalar integer, got {})distribution_utilmaybe_get_static_valuer>   npgenericndarrayrf   r   int64r/   r6   lenr   rT   )r!   r   r   s      r   r   z&Bijector._maybe_get_static_event_ndimsK  s    $;;KHL,RZZ 89			BHHbhh#7	7?FF  ! 	! 
L"**	-#l6H6H2I<CC  	&lr   )NFFNNNN)r   )r   )r   )r   )r   )r   rB   )NNN).rC   rD   rE   rF   abcabstractmethodrk   rG   rc   rg   rh   rd   rs   re   rf   rO   rz   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   
contextlibcontextmanagerr~   r   r   r   r   r   r   r   r*   r   r   r   r      s   bH !$)"'+'+^O ^O@   ) ) ) ) 	& 	&         'C;&
L 'C<&2
3:'"9'&K /d "<E>5&2j "<E4  -
*	6.@r   )	metaclass)rF   r   collectionsr   rL   numpyr   tensorflow.python.frameworkr   r   r   r   tensorflow.python.opsr   r   r	   #tensorflow.python.ops.distributionsr
   r   tensorflow.python.utilr   __all__
namedtupler   ABCMetar   r*   r   r   <module>r	     su     
   	  . + 4 3 + + * I 2 
W4%{%%02 W4tW Wr   