
    AVh                    r   d 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dlmZ ddlmZ ddlmZ ddlmZ ddlmZ  G d d      Z eddg       ej0                  d       G d de                    Z eddg       ej0                  dd       G d de                    Z eddg       ej0                  d       G d de                    Z ed d!g       ej0                  d        G d" d#e                    Z ed$d%g       ej0                  d$       G d& d'e                    Z ed(d)g       ej0                  d(d)       G d* d+e                    Z ed,d-g       ej0                  d-d,       G d. d/e                    Z ed0d1g       ej0                  d0d1       G d2 d3e                    Z  ed4d5g       ej0                  d4d5       G d6 d7e                    Z! G d8 d9e      Z" G d: d;e      Z# G d< d=e#      Z$ G d> d?e#      Z% G d@ dAe#      Z& edBg       ej0                  dB       G dC dDe                    Z' edEdFg       ej0                  dEdF       G dG dHe                     Z( edIdJg       ej0                  dIdJ       G dK dLe                     Z)eZ*eZ+eZ,eZ-eZ.eZ/eZ0e Z1e(Z2e)Z3e!Z4e'Z5e"Z6e%Z7e$Z8e&Z9 edMg      dWdN       Z: edOg      dWdP       Z; edQg      dWdR       Z< edSg      dWdT       Z=dU Z>dV Z?y)Xa  Operations often used for initializing tensors.

All variable initializers returned by functions in this file should have the
following signature:

def _initializer(shape, dtype=dtypes.float32, partition_info=None):
  Args:
    shape: List of `int` representing the shape of the output `Tensor`. Some
      initializers may also be able to accept a `Tensor`.
    dtype: (Optional) Type of the output `Tensor`.
    partition_info: (Optional) variable_scope._PartitionInfo object holding
      additional information about how the variable is partitioned. May be
      `None` if the variable is not partitioned.

  Returns:
    A `Tensor` of type `dtype` and `shape`.
    N)constant_op)dtypes)tensor_shape)	array_ops)array_ops_stack)gen_linalg_ops)linalg_ops_impl)math_ops)
random_ops)deprecation)
deprecated)deprecated_arg_values)deprecated_args)	tf_exportc                   .    e Zd ZdZddZd Zed        Zy)InitializerzAInitializer base class: all initializers inherit from this class.Nc                     t         )a4  Returns a tensor object initialized as specified by the initializer.

    Args:
      shape: Shape of the tensor.
      dtype: Optional dtype of the tensor. If not provided use the initializer
        dtype.
      partition_info: Optional information about the possible partitioning of a
        tensor.
    NotImplementedErrorselfshapedtypepartition_infos       N/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/ops/init_ops.py__call__zInitializer.__call__7   s
         c                     i S )zReturns the configuration of the initializer as a JSON-serializable dict.

    Returns:
      A JSON-serializable Python dict.
     r   s    r   
get_configzInitializer.get_configC   s	     Ir   c                      | di |S )a{  Instantiates an initializer from a configuration dictionary.

    Example:

    ```python
    initializer = RandomUniform(-1, 1)
    config = initializer.get_config()
    initializer = RandomUniform.from_config(config)
    ```

    Args:
      config: A Python dictionary. It will typically be the output of
        `get_config`.

    Returns:
      An Initializer instance.
    r   r   )clsconfigs     r   from_configzInitializer.from_configK   s    & ==r   NN)__name__
__module____qualname____doc__r   r!   classmethodr%   r   r   r   r   r   4   s#    I
  r   r   zinitializers.zeroszeros_initializer)v1c                   V    e Zd ZdZ eddd      ej                  fd       ZddZd Z	y)	Zerosa  Initializer that generates tensors initialized to 0.

  @compatibility(TF2)
  `tf.compat.v1.zeros_initializer` is compatible with eager execution
  and `tf.function`.

  To migrate to TF2, please use `tf.zeros_initializer` instead. The `dtype`
  argument in `tf.compat.v1.zeros_initializer.__init__()` does not exist in
  `tf.zeros_initializer.__init__()`. However, you can specify the `dtype` in
  `__call__()` in both cases.

  #### Structural Mapping to TF2

  Before:

  ```python
  initializer = tf.compat.v1.zeros_initializer(dtype=tf.float32)
  variable = tf.Variable(initializer(shape=[3, 3]))
  ```

  After:

  ```python
  initializer = tf.zeros_initializer()
  variable = tf.Variable(initializer(shape=[3, 3], dtype=tf.float32))
  ```

  #### How to Map Arguments

  | TF1 Arg Name         | TF2 Arg Name     | Note                       |
  | :------------------- | :--------------- | :------------------------- |
  | `dtype`              | `dtype`          | In `__call__()` method     |
  | `partition_info`     | - |  (`__call__` arg in TF1) Not supported    |


  #### Before & After Usage Example

  Before:

  >>> initializer = tf.compat.v1.zeros_initializer(dtype=tf.float32)
  >>> tf.Variable(initializer(shape=[3])).numpy()
  array([0., 0., 0.], dtype=float32)
  >>> tf.Variable(initializer(shape=[3, 3])).numpy()
  array([[0., 0., 0.],
         [0., 0., 0.],
         [0., 0., 0.]], dtype=float32)
  >>> initializer = tf.compat.v1.zeros_initializer()
  >>> tf.Variable(initializer(shape=[3], dtype=tf.float32)).numpy()
  array([0., 0., 0.], dtype=float32)
  >>> tf.Variable(initializer(shape=[3, 3], dtype=tf.float32)).numpy()
  array([[0., 0., 0.],
         [0., 0., 0.],
         [0., 0., 0.]], dtype=float32)

  After:

  >>> initializer = tf.zeros_initializer()
  >>> tf.Variable(initializer(shape=[3], dtype=tf.float32)).numpy()
  array([0., 0., 0.], dtype=float32)
  >>> tf.Variable(initializer(shape=[3, 3], dtype=tf.float32)).numpy()
  array([[0., 0., 0.],
         [0., 0., 0.],
         [0., 0., 0.]], dtype=float32)

  @end_compatibility
  NZCall initializer instance with the dtype argument instead of passing it to the constructorr   c                 8    t        j                  |      | _        y Nr   as_dtyper   r   r   s     r   __init__zZeros.__init__        'DJr   c                 J    || j                   }t        j                  ||      S r2   )r   r   zerosr   s       r   r   zZeros.__call__   s!    }jje??5%((r   c                 2    d| j                   j                  iS Nr   r   namer    s    r   r!   zZeros.get_config       TZZ__%%r   r&   
r'   r(   r)   r*   r   r   float32r6   r   r!   r   r   r   r/   r/   a   sA    AF 467>@ ">> (@()
&r   r/   zinitializers.onesones_initializerc                   V    e Zd ZdZ eddd      ej                  fd       ZddZd Z	y)	Onesa:  Initializer that generates tensors initialized to 1.

  @compatibility(TF2)
  This API is compatible with TF2 behavior and `tf.function`, and can be
  migrated immediately with `tf.keras.initializers.ones`.

  Before:
  >>> initializer = tf.compat.v1.keras.initializers.ones()
  >>> initializer((1, 1))
  <tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[1.]], dtype=float32)>

  After:
  >>> initializer = tf.keras.initializers.ones()
  >>> initializer((1, 1))
  <tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[1.]], dtype=float32)>

  @end_compatibility
  Nr0   r   c                 8    t        j                  |      | _        y r2   r3   r5   s     r   r6   zOnes.__init__   r7   r   c                 J    || j                   }t        j                  ||      S r2   )r   r   onesr   s       r   r   zOnes.__call__   s!    }jje>>%''r   c                 2    d| j                   j                  iS r;   r<   r    s    r   r!   zOnes.get_config   r>   r   r&   r?   r   r   r   rC   rC      s?    & 467>@ ">> (@((
&r   rC   zinitializers.constantconstant_initializerc                   t    e Zd ZdZ eddd       eddd      dej                  dfd	              Zdd
Zd Z	y)Constantai  Initializer that generates tensors with constant values.

  The resulting tensor is populated with values of type `dtype`, as
  specified by arguments `value` following the desired `shape` of the
  new tensor (see examples below).

  The argument `value` can be a constant value, or a list of values of type
  `dtype`. If `value` is a list, then the length of the list must be less
  than or equal to the number of elements implied by the desired shape of the
  tensor. In the case where the total number of elements in `value` is less
  than the number of elements required by the tensor shape, the last element
  in `value` will be used to fill the remaining entries. If the total number of
  elements in `value` is greater than the number of elements required by the
  tensor shape, the initializer will raise a `ValueError`.

  Args:
    value: A Python scalar, list or tuple of values, or a N-dimensional numpy
      array. All elements of the initialized variable will be set to the
      corresponding value in the `value` argument.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer.
    verify_shape: Boolean that enables verification of the shape of `value`. If
      `True`, the initializer will throw an error if the shape of `value` is not
      compatible with the shape of the initialized tensor.

  Raises:
    TypeError: If the input `value` is not one of the expected types.

  Examples:
    The following example can be rewritten using a numpy.ndarray instead
    of the `value` list, even reshaped, as shown in the two commented lines
    below the `value` list initialization.

  >>> value = [0, 1, 2, 3, 4, 5, 6, 7]
  >>> init = tf.compat.v1.constant_initializer(value)
  >>> # fitting shape
  >>> with tf.compat.v1.Session():
  ...   x = tf.compat.v1.get_variable('x', shape=[2, 4], initializer=init)
  ...   x.initializer.run()
  ...   print(x.eval())
  [[0. 1. 2. 3.]
   [4. 5. 6. 7.]]
  >>> # Larger shape
  >>> with tf.compat.v1.Session():
  ...   y = tf.compat.v1.get_variable('y', shape=[3, 4], initializer=init)
  ...   y.initializer.run()
  ...   print(y.eval())
  [[0.  1.  2.  3.]
   [4.  5.  6.  7.]
   [7.  7.  7.  7.]]
  >>> # Smaller shape
  >>> with tf.compat.v1.Session():
  ...   z = tf.compat.v1.get_variable('z', shape=[2, 3], initializer=init)
  Traceback (most recent call last):
  ...
  ValueError: Too many elements provided. Needed at most 6, but received 8
  >>> # Shape verification
  >>> init_verify = tf.compat.v1.constant_initializer(value, verify_shape=True)
  >>> with tf.compat.v1.Session():
  ...  u = tf.compat.v1.get_variable('u', shape=[3, 4],
  ...                                initializer=init_verify)
  Traceback (most recent call last):
  ...
  TypeError: Expected Tensor's shape: (3, 4), got (8,).

  @compatibility(TF2)
  Although it is a legacy API endpoint, `tf.compat.v1.constant_initializer`
  is compatible with eager execution and `tf.function`.

  To migrate to a non-legacy TF2 API, please use `tf.constant_initializer`
  instead. The `dtype`
  argument in `tf.compat.v1.constant_initializer.__init__()` does not exist in
  `tf.constant_initializer.__init__()`. However, you can specify the `dtype` in
  `__call__()` in both cases.

  In the `compat.v1` symbol, if `verify_shape` is set to `True`, an exception
  is raised when initializing a variable with a different shape from
  `value`. If set to `False`, `value` is reshaped to initialize the variable
  if necessary. An exception would only be raised when the number of
  elements are different.

  The `verify_shape` argument is not supported in TF2. Using
  `tf.constant_initializer` is equivalent to setting `verify_shape` to `False`.

  #### Structural Mapping to TF2

  Before:

  ```python
  value = [0, 1, 2, 3, 4, 5, 6, 7]
  initializer = tf.compat.v1.constant_initializer(
      value=value,
      dtype=tf.float32,
      verify_shape=False)
  variable = tf.Variable(initializer(shape=[2, 4]))
  ```

  After:

  ```python
  value = [0, 1, 2, 3, 4, 5, 6, 7]
  initializer = tf.constant_initializer(value=value)
  tf.Variable(initializer(shape=[2, 4], dtype=tf.float32))
  ```

  #### How to Map Arguments

  | TF1 Arg Name          | TF2 Arg Name     | Note                        |
  | :-------------------- | :--------------- | :-------------------------- |
  | `value`               | `value`          | In constructor              |
  | `dtype`               | `dtype`          | In `__call__()` method      |
  | `verify_shape`        | Not Supported    | Equivalent to set to `False`|
  | `partition_info`      | - |  (`__call__` arg in TF1) Not supported     |


  #### Before & After Usage Example

  Before:

  >>> value = [1., 2., 3., 4.]
  >>> initializer = tf.compat.v1.constant_initializer(
  ...     value=value, dtype=tf.float32, verify_shape=True)
  >>> tf.Variable(initializer(shape=[2, 2])).numpy()
  Traceback (most recent call last):
  ...
  TypeError: Expected Tensor's shape: (2, 2), got (4,).
  >>> initializer = tf.compat.v1.constant_initializer(
  ...     value=value, dtype=tf.float32, verify_shape=False)
  >>> tf.Variable(initializer(shape=[2, 2])).numpy()
  array([[1., 2.],
         [3., 4.]], dtype=float32)

  After:

  >>> value = [1., 2., 3., 4.]
  >>> initializer = tf.constant_initializer(value=value)
  >>> tf.Variable(initializer(shape=[2, 2], dtype=tf.float32)).numpy()
  array([[1., 2.],
         [3., 4.]], dtype=float32)

  @end_compatibility
  Nr0   r   zCObjects must now be the required shape or no shape can be specifiedverify_shaper   Fc                    t        j                  |      sJt        |t        t        t         j
                  f      s%t        d| dt        |      j                   d      || _	        t        j                  |      | _        || _        y )NzInvalid type for initial value=z
 of type: zD. Expected Python scalar, list or tuple of values, or numpy.ndarray.)npisscalar
isinstancelisttuplendarray	TypeErrortyper'   valuer   r4   r   _verify_shape)r   rU   r   rK   s       r   r6   zConstant.__init__m  su     KK*UT5"**4M"N+E7*%[!!" #&&' '
 DJ'DJ%Dr   c                     || j                   }|| j                  }t        j                  | j                  |||      S )N)r   r   rK   )r   rV   r   constant_v1rU   )r   r   r   r   rK   s        r   r   zConstant.__call__}  sC    }jje''l""

%u<I Ir   c                 H    | j                   | j                  j                  dS )N)rU   r   )rU   r   r=   r    s    r   r!   zConstant.get_config  s    
 ZZ$**//::r   )NNNr?   r   r   r   rJ   rJ      s]    M^ 467>@ 4 &'57FNN 	&7@
	&I;r   rJ   zinitializers.random_uniformrandom_uniform_initializerc                   \    e Zd ZdZ eddd      dddej                  fd       Zd	dZd Z	y)
RandomUniformaR  Initializer that generates tensors with a uniform distribution.

  Args:
    minval: A python scalar or a scalar tensor. Lower bound of the range of
      random values to generate.
    maxval: A python scalar or a scalar tensor. Upper bound of the range of
      random values to generate.  Defaults to 1 for float types.
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer.

  @compatibility(TF2)
  Although it is a legacy compat.v1 API, this symbol is compatible with eager
  execution and `tf.function`.

  To switch to TF2, switch to using either
  `tf.initializers.RandomUniform` or `tf.keras.initializers.RandomUniform`
  (neither from `compat.v1`) and
  pass the dtype when calling the initializer. Keep in mind that
  the default minval, maxval and the behavior of fixed seeds have changed.

  #### Structural Mapping to TF2

  Before:

  ```python
  initializer = tf.compat.v1.random_uniform_initializer(
    minval=minval,
    maxval=maxval,
    seed=seed,
    dtype=dtype)

  weight_one = tf.Variable(initializer(shape_one))
  weight_two = tf.Variable(initializer(shape_two))
  ```

  After:

  ```python
  initializer = tf.initializers.RandomUniform(
    minval=minval,
    maxval=maxval,
    seed=seed)

  weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
  weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
  ```

  #### How to Map Arguments

  | TF1 Arg Name          | TF2 Arg Name    | Note                       |
  | :-------------------- | :-------------- | :------------------------- |
  | `minval`               | `minval`    | Default changes from 0 to -0.05 |
  | `maxval`         | `maxval`        | Default changes from 1.0 to 0.05 |
  | `seed`             | `seed` |  |
  | `dtype` | `dtype`   | The TF2 native api only takes it  |
  :                     :      : as a `__call__` arg, not a constructor arg. :
  | `partition_info`     | - |  (`__call__` arg in TF1) Not supported       |

  @end_compatibility
  Nr0   r           c                 b    || _         || _        || _        t        j                  |      | _        y r2   )minvalmaxvalseedr   r4   r   )r   r_   r`   ra   r   s        r   r6   zRandomUniform.__init__  s)     DKDKDI'DJr   c                     || j                   }t        j                  || j                  | j                  || j
                        S Nra   )r   r   random_uniformr_   r`   ra   r   s       r   r   zRandomUniform.__call__  s<    }jje$$t{{DKKTYY@ @r   c                 t    | j                   | j                  | j                  | j                  j                  dS )N)r_   r`   ra   r   )r_   r`   ra   r   r=   r    s    r   r!   zRandomUniform.get_config  s,    ++++			 r   r&   r?   r   r   r   r\   r\     sG    =~ 467>@ t$fnn (@(@r   r\   zinitializers.random_normalrandom_normal_initializerc                   \    e Zd ZdZ eddd      dddej                  fd       Zd
dZd	 Z	y)RandomNormalaY  Initializer that generates tensors with a normal distribution.

  Args:
    mean: a python scalar or a scalar tensor. Mean of the random values to
      generate.
    stddev: a python scalar or a scalar tensor. Standard deviation of the random
      values to generate.
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.

  @compatibility(TF2)
  Although it is a legacy `compat.v1` API, this symbol is compatible with eager
  execution and `tf.function`.

  To switch to TF2, switch to using either
  `tf.initializers.RandomNormal` or `tf.keras.initializers.RandomNormal`
  (neither from `compat.v1`) and
  pass the dtype when calling the initializer. Keep in mind that
  the default stddev and the behavior of fixed seeds have changed.

  #### Structural Mapping to TF2

  Before:

  ```python
  initializer = tf.compat.v1.random_normal_initializer(
    mean=mean,
    stddev=stddev,
    seed=seed,
    dtype=dtype)

  weight_one = tf.Variable(initializer(shape_one))
  weight_two = tf.Variable(initializer(shape_two))
  ```

  After:

  ```python
  initializer = tf.initializers.RandomNormal(
    mean=mean,
    seed=seed,
    stddev=stddev)

  weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
  weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
  ```

  #### How to Map Arguments

  | TF1 Arg Name       | TF2 Arg Name    | Note                       |
  | :----------------- | :-------------- | :------------------------- |
  | `mean`             | `mean`          | No change to defaults |
  | `stddev`           | `stddev`        | Default changes from 1.0 to 0.05 |
  | `seed`             | `seed`          |                                  |
  | `dtype`            | `dtype`  | The TF2 native api only takes it as a |
  :                    :          : `__call__` arg, not a constructor arg. :
  | `partition_info`   | -     |  (`__call__` arg in TF1) Not supported.  |

  @end_compatibility
  Nr0   r   r]         ?c                 t    || _         || _        || _        t        t	        j
                  |            | _        y r2   meanstddevra   _assert_float_dtyper   r4   r   r   rm   rn   ra   r   s        r   r6   zRandomNormal.__init__)  .     DIDKDI$V__U%;<DJr   c                     || j                   }t        j                  || j                  | j                  || j
                        S rc   )r   r   random_normalrm   rn   ra   r   s       r   r   zRandomNormal.__call__2  s:    }jje##tyy$++u499> >r   c                 t    | j                   | j                  | j                  | j                  j                  dS N)rm   rn   ra   r   rm   rn   ra   r   r=   r    s    r   r!   zRandomNormal.get_config8  ,    		++			 r   r&   r?   r   r   r   ri   ri     sF    =~ 467>@ cFNN =@=>r   ri   zinitializers.truncated_normaltruncated_normal_initializerc                   \    e Zd ZdZ eddd      dddej                  fd       Zd
dZd	 Z	y)TruncatedNormala.	  Initializer that generates a truncated normal distribution.

  These values are similar to values from a `random_normal_initializer`
  except that values more than two standard deviations from the mean
  are discarded and re-drawn. This is the recommended initializer for
  neural network weights and filters.

  Args:
    mean: a python scalar or a scalar tensor. Mean of the random values to
      generate.
    stddev: a python scalar or a scalar tensor. Standard deviation of the random
      values to generate.
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.

  @compatibility(TF2)
  Although it is a legacy `compat.v1` API, this symbol is compatible with eager
  execution and `tf.function`.

  To switch to TF2, switch to using either
  `tf.initializers.truncated_normal` or `tf.keras.initializers.TruncatedNormal`
  (neither from `compat.v1`) and
  pass the dtype when calling the initializer. Keep in mind that
  the default stddev and the behavior of fixed seeds have changed.

  #### Structural Mapping to TF2

  Before:

  ```python
  initializer = tf.compat.v1.truncated_normal_initializer(
    mean=mean,
    stddev=stddev,
    seed=seed,
    dtype=dtype)

  weight_one = tf.Variable(initializer(shape_one))
  weight_two = tf.Variable(initializer(shape_two))
  ```

  After:

  ```python
  initializer = tf.initializers.truncated_normal(
    mean=mean,
    seed=seed,
    stddev=stddev)

  weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
  weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
  ```

  #### How to Map Arguments

  | TF1 Arg Name          | TF2 Arg Name    | Note                       |
  | :-------------------- | :-------------- | :------------------------- |
  | `mean`               | `mean`        | No change to defaults |
  | `stddev`         | `stddev`        | Default changes from 1.0 to 0.05 |
  | `seed`             | `seed` | |
  | `dtype` | `dtype`   | The TF2 native api only takes it  |
  :                     :      : as a `__call__` arg, not a constructor arg. :
  | `partition_info`     | - |  (`__call__` arg in TF1) Not supported       |

  @end_compatibility
  Nr0   r   r]   rj   c                 t    || _         || _        || _        t        t	        j
                  |            | _        y r2   rl   rp   s        r   r6   zTruncatedNormal.__init__  rq   r   c                     || j                   }t        j                  || j                  | j                  || j
                        S rc   )r   r   truncated_normalrm   rn   ra   r   s       r   r   zTruncatedNormal.__call__  s:    }jje&&tyy$++u499> >r   c                 t    | j                   | j                  | j                  | j                  j                  dS ru   rv   r    s    r   r!   zTruncatedNormal.get_config  rw   r   r&   r?   r   r   r   rz   rz   A  sG    BH 467>@ cFNN =@=>r   rz   z!initializers.uniform_unit_scaling uniform_unit_scaling_initializerc                   r    e Zd ZdZ eddd       edd      ddej                  fd              Zd
dZ	d	 Z
y)UniformUnitScalinga  Initializer that generates tensors without scaling variance.

  When initializing a deep network, it is in principle advantageous to keep
  the scale of the input variance constant, so it does not explode or diminish
  by reaching the final layer. If the input is `x` and the operation `x * W`,
  and we want to initialize `W` uniformly at random, we need to pick `W` from

      [-sqrt(3) / sqrt(dim), sqrt(3) / sqrt(dim)]

  to keep the scale intact, where `dim = W.shape[0]` (the size of the input).
  A similar calculation for convolutional networks gives an analogous result
  with `dim` equal to the product of the first 3 dimensions.  When
  nonlinearities are present, we need to multiply this by a constant `factor`.
  See (Sussillo et al., 2014) for deeper motivation, experiments
  and the calculation of constants. In section 2.3 there, the constants were
  numerically computed: for a linear layer it's 1.0, relu: ~1.43, tanh: ~1.15.

  Args:
    factor: Float.  A multiplicative factor by which the values will be scaled.
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.
  References:
      [Sussillo et al., 2014](https://arxiv.org/abs/1412.6558)
      ([pdf](http://arxiv.org/pdf/1412.6558.pdf))
  Nr0   r   zbUse tf.initializers.variance_scaling instead with distribution=uniform to get equivalent behavior.rj   c                 f    || _         || _        t        t        j                  |            | _        y r2   )factorra   ro   r   r4   r   )r   r   ra   r   s       r   r6   zUniformUnitScaling.__init__  s'     DKDI$V__U%;<DJr   c                    || j                   }|}||j                  }d}|d d D ]  }|t        |      z  } t        |d      }t	        j
                  d|z        | j                  z  }t        j                  || ||| j                        S )Nrj      rd   )
r   
full_shapefloatmaxmathsqrtr   r   re   ra   )r   r   r   r   scale_shape
input_sizedimmax_vals           r   r   zUniformUnitScaling.__call__  s    }jjeK!"--kJ 3B E#Jj Z%JiiJ'$++5G$$x%dii9 9r   c                 ^    | j                   | j                  | j                  j                  dS )N)r   ra   r   )r   ra   r   r=   r    s    r   r!   zUniformUnitScaling.get_config  s    kk499tzzOOr   r&   )r'   r(   r)   r*   r   r   r   r@   r6   r   r!   r   r   r   r   r     sZ    8 467>@ d45  d&.. =5@=
9&Pr   r   zinitializers.variance_scalingvariance_scaling_initializerc                   z    e Zd ZdZ eddd       eddd      dd	d
dej                  fd              ZddZ	d Z
y)VarianceScalingah  Initializer capable of adapting its scale to the shape of weights tensors.

  @compatibility(TF2)
  Although it is a legacy `compat.v1` API, this symbol is compatible with eager
  execution and `tf.function`.

  To switch to TF2 APIs, move to using either
  `tf.initializers.variance_scaling` or `tf.keras.initializers.VarianceScaling`
  (neither from `compat.v1`) and
  pass the dtype when calling the initializer.

  #### Structural Mapping to TF2

  Before:

  ```python
  initializer = tf.compat.v1.variance_scaling_initializer(
    scale=scale,
    mode=mode,
    distribution=distribution
    seed=seed,
    dtype=dtype)

  weight_one = tf.Variable(initializer(shape_one))
  weight_two = tf.Variable(initializer(shape_two))
  ```

  After:

  ```python
  initializer = tf.keras.initializers.VarianceScaling(
    scale=scale,
    mode=mode,
    distribution=distribution
    seed=seed)

  weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
  weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
  ```

  #### How to Map Arguments

  | TF1 Arg Name       | TF2 Arg Name    | Note                       |
  | :----------------- | :-------------- | :------------------------- |
  | `scale`            | `scale`        | No change to defaults       |
  | `mode`             | `mode`         | No change to defaults       |
  | `distribution`     | `distribution` | No change to defaults.      |
  :                    :                : 'normal' maps to 'truncated_normal' :
  | `seed`             | `seed`         | |
  | `dtype`        |  `dtype` | The TF2 api only takes it  |
  :                :          : as a `__call__` arg, not a constructor arg. :
  | `partition_info`     | - |  (`__call__` arg in TF1) Not supported       |

  @end_compatibility

  With `distribution="truncated_normal" or "untruncated_normal"`,
  samples are drawn from a truncated/untruncated normal
  distribution with a mean of zero and a standard deviation (after truncation,
  if used) `stddev = sqrt(scale / n)`
  where n is:
    - number of input units in the weight tensor, if mode = "fan_in"
    - number of output units, if mode = "fan_out"
    - average of the numbers of input and output units, if mode = "fan_avg"

  With `distribution="uniform"`, samples are drawn from a uniform distribution
  within [-limit, limit], with `limit = sqrt(3 * scale / n)`.

  Args:
    scale: Scaling factor (positive float).
    mode: One of "fan_in", "fan_out", "fan_avg".
    distribution: Random distribution to use. One of "normal", "uniform".
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.

  Raises:
    ValueError: In case of an invalid value for the "scale", mode" or
      "distribution" arguments.
  Nr0   r   z5`normal` is a deprecated alias for `truncated_normal`normal)distributionrj   fan_inr}   c                    |dk  rt        d|       |dvrt        d|       |j                         }|dvrt        d|       || _        || _        || _        || _        t        t        j                  |            | _	        y )Nr]   z5Argument `scale` must be a positive float. Received: >   r   fan_avgfan_outzMArgument `mode` should be one of ('fan_in', 'fan_out', 'fan_avg'). Received: >   r   uniformr}   untruncated_normalzsArgument `distribution` should be one of ('normal', uniform', 'truncated_normal', 'untruncated_normal'). Received: )

ValueErrorlowerscalemoder   ra   ro   r   r4   r   )r   r   r   r   ra   r   s         r   r6   zVarianceScaling.__init__:  s     {N" # #33 004v7 8 8%%'L    $$0>3 4 4 DJDI$DDI$V__U%;<DJr   c                    || j                   }| j                  }|}||j                  }t        |      \  }}| j                  dk(  r|t        d|      z  }n4| j                  dk(  r|t        d|      z  }n|t        d||z   dz        z  }| j                  dk(  s| j                  dk(  r<t        j                  |      dz  }t        j                  |d||| j                  	      S | j                  d
k(  r9t        j                  |      }t        j                  |d||| j                  	      S t        j                  d|z        }	t        j                  ||	 |	|| j                  	      S )Nr   rj   r          @r   r}   g۶%?r]   rd   r   g      @)r   r   r   _compute_fansr   r   r   r   r   r   r}   ra   rs   re   )
r   r   r   r   r   r   r   r   rn   limits
             r   r   zVarianceScaling.__call__Z  sS   }jjeJJEK!"--k#K0OFGyyHs2ve	i	s2wes2(B.//eH$(9(9=O(Oyy"44f((
fe$))5 5			2	2yyf%%eS&%diiPPiie$e&&
%DII7 7r   c                     | j                   | j                  | j                  | j                  | j                  j
                  dS )N)r   r   r   ra   r   )r   r   r   ra   r   r=   r    s    r   r!   zVarianceScaling.get_configu  s5    		))		 r   r&   )r'   r(   r)   r*   r   r   r   r@   r6   r   r!   r   r   r   r   r     se    Ob 467>@ 
=
 .^^=	@=276r   r   zinitializers.orthogonalorthogonal_initializerc                   Z    e Zd ZdZ eddd      ddej                  fd       Zd	dZd Z	y)

Orthogonala  Initializer that generates an orthogonal matrix.

  If the shape of the tensor to initialize is two-dimensional, it is initialized
  with an orthogonal matrix obtained from the QR decomposition of a matrix of
  random numbers drawn from a normal distribution.
  If the matrix has fewer rows than columns then the output will have orthogonal
  rows. Otherwise, the output will have orthogonal columns.

  If the shape of the tensor to initialize is more than two-dimensional,
  a matrix of shape `(shape[0] * ... * shape[n - 2], shape[n - 1])`
  is initialized, where `n` is the length of the shape vector.
  The matrix is subsequently reshaped to give a tensor of the desired shape.

  Args:
    gain: multiplicative factor to apply to the orthogonal matrix
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.
  References:
      [Saxe et al., 2014](https://openreview.net/forum?id=_wzZwKpTDF_9C)
      ([pdf](https://arxiv.org/pdf/1312.6120.pdf))
  Nr0   r   rj   c                 f    || _         t        t        j                  |            | _        || _        y r2   gainro   r   r4   r   ra   r   r   ra   r   s       r   r6   zOrthogonal.__init__  s'     DI$V__U%;<DJDIr   c                    || j                   }t        |      dk  rt        d|       d}|d d D ]  }||z  }	 t        |      }t        |d         }||k  r||f}n||f}t	        j
                  ||| j                        }t        j                  |d      \  }	}
t        j                  |
      }|	t        j                  |      z  }	||k  rt        j                  |	      }	| j                  t        j                  |	|      z  S )N   iThe tensor to initialize, specified by argument `shape` must be at least two-dimensional. Received shape=   r   r   ra   Ffull_matrices)r   lenr   intr   rs   ra   r   qrr   	diag_partr
   signmatrix_transposer   reshape)r   r   r   r   num_rowsr   num_cols
flat_shapeaqrds               r   r   zOrthogonal.__call__  s   }jje
5zA~ L" # #
 HSbz #oh8}H59~H(h'jh'j 	  5tyyIAQe4DAqAAq	A(

$
$Q
'a99y((E222r   c                 ^    | j                   | j                  | j                  j                  dS N)r   ra   r   r   ra   r   r=   r    s    r   r!   zOrthogonal.get_config      IItyy4::??KKr   r&   r?   r   r   r   r   r     sD    0 467>@ D @
3>Lr   r   c                   @    e Zd ZdZddej
                  fdZddZd Zy)ConvolutionDeltaOrthogonala  Initializer that generates a delta orthogonal kernel for ConvNets.

  The shape of the tensor must have length 3, 4 or 5. The number of input
  filters must not exceed the number of output filters. The center pixels of the
  tensor form an orthogonal matrix. Other pixels are set to be zero. See
  algorithm 2 in (Xiao et al., 2018).


  Args:
    gain: Multiplicative factor to apply to the orthogonal matrix. Default is 1.
      The 2-norm of an input is multiplied by a factor of `gain` after applying
      this convolution.
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.
  References:
      [Xiao et al., 2018](http://proceedings.mlr.press/v80/xiao18a.html)
      ([pdf](http://proceedings.mlr.press/v80/xiao18a/xiao18a.pdf))
  rj   Nc                 f    || _         t        t        j                  |            | _        || _        y r2   r   r   s       r   r6   z#ConvolutionDeltaOrthogonal.__init__  %    DI$V__U%;<DJDIr   c                    || j                   }t        |      dk  st        |      dkD  rt        d|       |d   |d   kD  rt        d|d    d|d    d      t        j                  |d   |d   g|| j
                  	      }t        j                  |d
      \  }}t        j                  |      }|t        j                  |      z  }|d |d   d d f   }|t        j                  | j                  |      z  }t        |      dk(  r8t        j                  |d   dz
  dz  ggt        j                  |d      |      }|S t        |      dk(  rBt        j                  |d   dz
  dz  |d   dz
  dz  ggt        j                  |d      |      }|S t        j                  |d   dz
  dz  |d   dz
  dz  |d   dz
  dz  ggt        j                  |d      |      }|S )Nr      zThe tensor to initialize, specified by argument `shape` must be at least three-dimensional and at most five-dimensional. Received shape=r   #In_filters, specified by shape[-2]=< cannot be greater than out_filters, specified by shape[-1]=.r   Fr   r   r   r   r      )r   r   r   r   rs   ra   r   r   r   r   r
   r   castr   
scatter_ndexpand_dims)	r   r   r   r   r   r   r   r   weights	            r   r   z#ConvolutionDeltaOrthogonal.__call__  s'   }jje
5zA~Ua ;;@'C D D Ry59<U2YK H$$)"I;a1 2 2
 	  %)U2Y!7',&*ii	1A Qe4DAqAAq	A	*59*a-Atyy	..A
5zQ##uQx!|&9%:$;$-$9$9!Q$?Hf M 
Uq##uQx!|&9',Qx!|&9&; %<$-$9$9!Q$?Hf M ##uQx!|&9E!HqLQ;N',Qx!|&9&; %<$-$9$9!Q$?Hf Mr   c                 ^    | j                   | j                  | j                  j                  dS r   r   r    s    r   r!   z%ConvolutionDeltaOrthogonal.get_config	  r   r   r&   )	r'   r(   r)   r*   r   r@   r6   r   r!   r   r   r   r   r     s%    * D 
$LLr   r   c                   L    e Zd ZdZddej
                  fdZd	dZd Zd Z	d Z
y)
ConvolutionOrthogonala  Initializer that generates orthogonal kernel for ConvNets.

  Base class used to construct 1D, 2D and 3D orthogonal kernels for convolution.

  Args:
    gain: multiplicative factor to apply to the orthogonal matrix. Default is 1.
      The 2-norm of an input is multiplied by a factor of `gain` after applying
      this convolution.
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.
  References:
      [Xiao et al., 2018](http://proceedings.mlr.press/v80/xiao18a.html)
      ([pdf](http://proceedings.mlr.press/v80/xiao18a/xiao18a.pdf))
  rj   Nc                 f    || _         t        t        j                  |            | _        || _        y r2   r   r   s       r   r6   zConvolutionOrthogonal.__init__  r   r   c                     t         r2   r   r   s       r   r   zConvolutionOrthogonal.__call__$  s    
r   c                 ^    | j                   | j                  | j                  j                  dS r   r   r    s    r   r!   z ConvolutionOrthogonal.get_config'  r   r   c                 .   t        j                  ||g| j                  | j                        }| j                  r| xj                  dz  c_        t	        j
                  |      \  }}t        j                  |      }|t        j                  |      z  }|S )zxConstruct an n x n orthogonal matrix.

    Args:
      n: Dimension.

    Returns:
      A n x n orthogonal matrix.
    r   r   )
r   rs   r   ra   r   r   r   r   r
   r   )r   nr   r   r   r   s         r   _orthogonal_matrixz(ConvolutionOrthogonal._orthogonal_matrix+  st     	  !Qtzz		JAyy
ii1niQDAqAAq	AHr   c                 j   | j                  |      }t        j                  t        j                  |g| j
                        dkD  | j                        }| j
                  r| xj
                  dz  c_        t        j                  ||      }t        j                  |t        j                  |            S )zCompute a n x n symmetric projection matrix.

    Args:
      n: Dimension.

    Returns:
      A n x n symmetric projection matrix, i.e. a matrix P s.t. P=P*P, P=P^T.
    rd   r   r   )r   r
   r   r   rs   ra   r   multiplymatmulr   r   )r   r   r   maskcs        r   _symmetric_projectionz+ConvolutionOrthogonal._symmetric_projection=  s     	"A==  !499594::GDyy
ii1ni!T"A??1i88;<<r   r&   )r'   r(   r)   r*   r   r@   r6   r   r!   r   r   r   r   r   r   r     s.    " D 
L$=r   r   c                   0    e Zd ZdZddZd Zd Zd Zd Zy)	ConvolutionOrthogonal2Da  Initializer that generates a 2D orthogonal kernel for ConvNets.

  The shape of the tensor must have length 4. The number of input
  filters must not exceed the number of output filters.
  The orthogonality(==isometry) is exact when the inputs are circular padded.
  There are finite-width effects with non-circular padding (e.g. zero padding).
  See algorithm 1 in (Xiao et al., 2018).

  Args:
    gain: Multiplicative factor to apply to the orthogonal matrix. Default is 1.
      This has the effect of scaling the output 2-norm by a factor of `gain`.
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.
  References:
      [Xiao et al., 2018](http://proceedings.mlr.press/v80/xiao18a.html)
      ([pdf](http://proceedings.mlr.press/v80/xiao18a/xiao18a.pdf))
  Nc                 f   || j                   }t        |      dk7  rt        d|       |d   |d   kD  rt        d|d    d|d    d      |d   |d	   k7  rt        d
|d    d|d	    d      | j                  |d   |d   |d         }|t	        j
                  | j                  |      z  }|S )Nr   z\The tensor to initialize, specified by argument `shape` must be four-dimensional. Received: r   r   r   r   r   r   r   $Kernel sizes, specified by shape[0]=z and shape[1]= must be equal.r   r   r   r   r   r   _orthogonal_kernelr
   r   r   r   r   r   r   kernels        r   r   z ConvolutionOrthogonal2D.__call__e  s    }jje
5zQ ??DgG H H Ry59<U2YK H$$)"I;a1 2 2 Qx58=eAhZ H##(8*O= > > $$U1XuQxqBF
hmmDIIU33FMr   c                     t        j                  t        |      D cg c]3  }t        j                  t        |      D cg c]	  }|||f    c}      5 c}}      S c c}w c c}}w )zConvert a dictionary to a tensor.

    Args:
      x: A k1 * k2 dictionary.
      k1: First dimension of x.
      k2: Second dimension of x.

    Returns:
      A k1 * k2 tensor.
    r   stackrange)r   xk1k2ijs         r   _dict_to_tensorz'ConvolutionOrthogonal2D._dict_to_tensory  s]       EJ2Y"P@Ab	:1qAw:;"P Q Q:"Ps   !A#
A	A#
A#
c                    |j                   j                         |j                   j                         k7  r&t        d|j                    d|j                    d      |j                   j                         d   }i }t        j                  || j
                        }t        j                  ||      |d<   t        j                  |||z
        |d<   t        j                  ||z
  |      |d<   t        j                  ||z
  ||z
        |d	<   |S )
a_  Construct a 2 x 2 kernel.

    Used to construct orthgonal kernel.

    Args:
      p1: A symmetric projection matrix.
      p2: A symmetric projection matrix.

    Returns:
      A 2 x 2 kernel [[p1p2,         p1(1-p2)],
                      [(1-p1)p2, (1-p1)(1-p2)]].
    Raises:
      ValueError: If the dimensions of p1 and p2 are different.
    BThe dimension of the matrices must be the same. Received p1.shape=z and p2.shape=r   r   r   r   r   r   r   )r   r   )r   r   )r   as_listr   r	   eyer   r
   r   )r   p1p2r   	kernel2x2r   s         r   _block_orthz#ConvolutionOrthogonal2D._block_orth  s     
xxRXX--// ,,.HH:^BHH:QP Q Q
1AI


atzz
2Coob"-IdOoob385IdOoosRx"5IdOoosRx38=IdOr   c                     |d   j                   j                         d   }||d   j                   j                         d   k7  r,t        d|d   j                    d|d   j                    d      t        t	        j
                  t        |                  }t        t	        j
                  t        |                  }i }||z   dz
  }t        |      D ]  }t        |      D ]  }	t        j                  ||g| j                        |||	f<   t        t        ||dz               D ]d  }
t        t        ||	dz               D ]G  }||
z
  |k  s|	|z
  |k  s|||	fxx   t        j                  ||
|f   |||
z
  |	|z
  f         z  cc<   I f   |S )aO  Matrix convolution.

    Args:
      m1: A k x k dictionary, each element is a n x n matrix.
      m2: A l x l dictionary, each element is a n x n matrix.

    Returns:
      (k + l - 1) * (k + l - 1) dictionary each element is a n x n matrix.
    Raises:
      ValueError: if the entries of m1 and m2 are of different dimensions.
    r   r   zYThe entries in matrices m1 and m2 must have the same dimensions. Received m1[0, 0].shape=z and m2[0, 0].shape=r   r   )r   r   r   r   rM   r   r   r   r   r9   r   minr
   r   )r   m1m2r   klresultsizer   r   index1index2s               r   _matrix_convz$ConvolutionOrthogonal2D._matrix_conv  s    
D  "1%ARX$$&q)) >>@hnn=M N--/X^^,<A? @ @ 	BGGCGABGGCGAFq519D4[ JT{ J! 1vtzz:q!tC1q5M* 	JFc!QUm, JfF
aQZ1$4QTlhoob.@.0VQZ1G.HJ JlJ	JJJ Mr   c                 r   ||kD  rt        d| d| d      | j                  |      d|ddf   }|dk(  r*t        j                  t        j                  |d      d      S | j	                  | j                  |      | j                  |            }t        |dz
        D ]D  }| j	                  | j                  |      | j                  |            }| j                  ||      }F t        |      D ]2  }t        |      D ]"  }	t        j                  ||||	f         |||	f<   $ 4 | j                  |||      S a  Construct orthogonal kernel for convolution.

    Args:
      ksize: Kernel size.
      cin: Number of input channels.
      cout: Number of output channels.

    Returns:
      An [ksize, ksize, cin, cout] orthogonal kernel.
    Raises:
      ValueError: If cin > cout.
    "The number of input channels (cin=4) cannot exceed the number of output channels (cout=).r   Nr   r   r   r   r   r   r   r   r   r  r
   r   r   )
r   ksizecincoutorthp_tempr   r   s
             r   r   z*ConvolutionOrthogonal2D._orthogonal_kernel  sY    Tz;C5 A??CfBH I I""4(32Dz""9#8#8q#A1EE""4($*D*DT*J	LA519 %

$
$T
*D,F,Ft,LNd


At
$a% 5\ 1U| 1!//$!Q$0!Q$11 5%00r   r&   	r'   r(   r)   r*   r   r   r   r  r   r   r   r   r   r   P  s"    ((Q8B1r   r   c                   0    e Zd ZdZddZd Zd Zd Zd Zy)	ConvolutionOrthogonal1Da  Initializer that generates a 1D orthogonal kernel for ConvNets.

  The shape of the tensor must have length 3. The number of input
  filters must not exceed the number of output filters.
  The orthogonality(==isometry) is exact when the inputs are circular padded.
  There are finite-width effects with non-circular padding (e.g. zero padding).
  See algorithm 1 in (Xiao et al., 2018).

  Args:
    gain: Multiplicative factor to apply to the orthogonal matrix. Default is 1.
      The 2-norm of an input is multiplied by a factor of `gain` after applying
      this convolution.
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.
  References:
      [Xiao et al., 2018](http://proceedings.mlr.press/v80/xiao18a.html)
      ([pdf](http://proceedings.mlr.press/v80/xiao18a/xiao18a.pdf))
  Nc                     || j                   }t        |      dk7  rt        d|       |d   |d   kD  rt        d|d    d|d    d      | j                  |d   |d   |d         }|t	        j
                  | j                  |	      z  }|S )
Nr   zbThe tensor to initialize, specified by argument `shape` must be three-dimensional. Received shape=r   r   r   r   r   r   r   r   r   s        r   r   z ConvolutionOrthogonal1D.__call__  s    }jje
5zQ EEJGM N N Ry59<U2YK H$$)"I;a1 2 2 $$U1XuRy%)DF
hmmDIIU33FMr   c                 j    t        j                  t        |      D cg c]  }||   	 c}      S c c}w )zConvert a dictionary to a tensor.

    Args:
      x: A dictionary of length k.
      k: Dimension of x.

    Returns:
      A tensor with the same dimension.
    r   )r   r   r  r   s       r   r   z'ConvolutionOrthogonal1D._dict_to_tensor  s+       a!91!A$!9::!9s   0c                     |j                   j                         d   }i }t        j                  || j                        }||d<   ||z
  |d<   |S )zConstruct a kernel.

    Used to construct orthgonal kernel.

    Args:
      projection_matrix: A symmetric projection matrix of size n x n.

    Returns:
      [projection_matrix, (1 - projection_matrix)].
    r   r   r   )r   r   r	   r   r   )r   projection_matrixr   r   r   s        r   r   z#ConvolutionOrthogonal1D._block_orth  sU     	'')!,AF


atzz
2C!F1I''F1IMr   c                 .   |d   j                   j                         d   }||d   j                   j                         d   k7  r,t        d|d   j                    d|d   j                    d      t        |      }t        |      }i }||z   dz
  }t	        |      D ]w  }t        j                  ||g| j                        ||<   t	        t        ||dz               D ]5  }	||	z
  |k  s||xx   t        j                  ||	   |||	z
           z  cc<   7 y |S )aN  Matrix convolution.

    Args:
      m1: A dictionary of length k, each element is a n x n matrix.
      m2: A dictionary of length l, each element is a n x n matrix.

    Returns:
      (k + l - 1)  dictionary each element is a n x n matrix.
    Raises:
      ValueError: Ff the entries of m1 and m2 are of different dimensions.
    r   zVThe entries in matrices m1 and m2 must have the same dimensions. Received m1[0].shape=z and m2[0].shape=r   r   )r   r   r   r   r   r   r9   r   r  r
   r   )
r   r  r  r   r  r  r  r  r   indexs
             r   r  z$ConvolutionOrthogonal1D._matrix_conv+  s$    
A"ARUMM!!#A&& ;;=a5;;- H**,Q%++a9 : : 	BABAFq519D4[ A//1a&$**5fQiQA' A%I?
)xr%y"QY-@
@)AA
 Mr   c                    ||kD  rt        d| d| d      | j                  |      d|ddf   }|dk(  rt        j                  |d      S | j	                  | j                  |            }t        |dz
        D ]4  }| j	                  | j                  |            }| j                  ||      }6 t        |      D ]  }t        j                  |||         ||<     | j                  ||      S r  r  )	r   r  r  r  r  r  r  r  r   s	            r   r   z*ConvolutionOrthogonal1D._orthogonal_kernelI  s    Tz;C5 A??CfBH I I""4(32Dz""4++33D9:A519 %d88>?d


At
$a% 5\ )__T1Q4(ad) 5))r   r&   r  r   r   r   r  r    s     * ;$<*r   r  c                   0    e Zd ZdZddZd Zd Zd Zd Zy)	ConvolutionOrthogonal3Da  Initializer that generates a 3D orthogonal kernel for ConvNets.

  The shape of the tensor must have length 5. The number of input
  filters must not exceed the number of output filters.
  The orthogonality(==isometry) is exact when the inputs are circular padded.
  There are finite-width effects with non-circular padding (e.g. zero padding).
  See algorithm 1 (Xiao et al., 2018).

  Args:
    gain: Multiplicative factor to apply to the orthogonal matrix. Default is 1.
      The 2-norm of an input is multiplied by a factor of `gain` after applying
      this convolution.
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.
  References:
      [Xiao et al., 2018](http://proceedings.mlr.press/v80/xiao18a.html)
      ([pdf](http://proceedings.mlr.press/v80/xiao18a/xiao18a.pdf))
  Nc           	         || j                   }t        |      dk7  rt        d|       |d   |d   kD  rt        d|d    d|d    d      |d   |d	   k7  s|d   |d
   k7  rt        d|d    d|d	    d|d
    d      | j                  |d   |d   |d         }|t	        j
                  | j                  |      z  }|S )Nr   zaThe tensor to initialize, specified by argument `shape` must be five-dimensional. Received shape=r   r   r   r   r   r   r   r   r   z,  shape[1]=z and shape[2]=r   r   r   r   s        r   r   z ConvolutionOrthogonal3D.__call__}  s   }jje
5zQ DDI7L M M Ry59<U2YK H$$)"I;a1 2 2 Qx58uQx583=eAhZ H##(8*N58* E   ! ! $$U1XuRy%)DF
hmmDIIU33FMr   c                 >   t        j                  t        |      D cg c]`  }t        j                  t        |      D cg c]4  }t        j                  t        |      D cg c]
  }||||f    c}      6 c}}      b c}}}      S c c}w c c}}w c c}}}w )zConvert a dictionary to a tensor.

    Args:
      x: A k1 * k2 dictionary.
      k1: First dimension of x.
      k2: Second dimension of x.
      k3: Third dimension of x.

    Returns:
      A k1 * k2 * k3 tensor.
    r   )r   r   r   r   k3r   r   r  s           r   r   z'ConvolutionOrthogonal3D._dict_to_tensor  s       ',Ry"2 "2"# #2"7"7)	 
		E"I>q!Q'
>	? 	# "2 3 3> 	"2s)   "B!B"B"1	B:
BBBc                    |j                   j                         }||j                   j                         k7  s||j                   j                         k7  r3t        d|j                    d|j                    d|j                    d      |d   }t        j                  || j
                        i }d }fd}d	D ]5  }	d	D ].  }
d	D ]'  } | ||	|       ||
|       |||            ||	|
|f<   ) 0 7 |S )
aE  Construct a 3 x 3 kernel.

    Used to construct orthgonal kernel.

    Args:
      p1: A symmetric projection matrix.
      p2: A symmetric projection matrix.
      p3: A symmetric projection matrix.

    Returns:
      A 2 x 2 x 2 kernel.
    Raises:
      ValueError: If the dimensions of p1, p2 and p3 are different.
    r   z, p2.shape=z and p3.shape=r   r   r   c                 V    t        j                  t        j                  | |      |      S r2   )r
   r   )r   r   p3s      r   r   z3ConvolutionOrthogonal3D._block_orth.<locals>.matmul  s    __X__R4b99r   c                 &    | |z  d| z
  |z
  z  z   S )zReturn p or (1-p).r   r   )r   r  r   s     r   r   z1ConvolutionOrthogonal3D._block_orth.<locals>.cast  s    Ua!ea(((r   r   )r   r   r   r	   r   r   )r   r   r   r*  p1_shaper   kernel2x2x2r   r   r   r   r  r   s               @r   r   z#ConvolutionOrthogonal3D._block_orth  s    xx!H288##%%RXX5E5E5G)G ,,.HH:[
 K$$&HH:Q0 1 1 	A


atzz
2CK:)  O O! 	OA!'QT!R[$q"+!N+aAg
	OOO r   c                    |d   j                   j                         d   }||d   j                   j                         d   k7  r,t        d|d   j                    d|d   j                    d      t        t	        j
                  t        |                  }t        t	        j
                  t        |                  }i }||z   dz
  }t        |      D ]  }t        |      D ]  }	t        |      D ]  }
t        j                  ||g| j                        |||	|
f<   t        t        ||dz               D ]  }t        t        ||	dz               D ]s  }t        t        ||
dz               D ]V  }||z
  |k  s|	|z
  |k  s|
|z
  |k  s|||	|
fxx   t        j                  ||||f   |||z
  |	|z
  |
|z
  f         z  cc<   X u     |S )ar  Matrix convolution.

    Args:
      m1: is a k x k x k  dictionary, each element is a n x n matrix.
      m2: is a l x l x l dictionary, each element is a n x n matrix.

    Returns:
      (k + l - 1) x (k + l - 1) x (k + l - 1) dictionary each
      element is a n x n matrix.
    Raises:
      ValueError: if the entries of m1 and m2 are of different dimensions.
    )r   r   r   r   z\The entries in matrices m1 and m2 must have the same dimensions. Received m1[0, 0, 0].shape=z and m2[0, 0, 0].shape=r   r   )r   r   r   r   rM   cbrtr   r   r   r9   r   r  r
   r   )r   r  r  r   r  r  r  r  r   r   r   r	  r
  index3s                 r   r  z$ConvolutionOrthogonal3D._matrix_conv  s    
G##%a(AR['')!,, AW+++,,CW+++,A/ 0 0 	BGGCGABGGCGAFq519D4[ 
>T{ 	>!t 	>A%OOQFDJJ?&Aq/c!QUm, >fAq1u. >!#aQ-0 >&J!#Vq(8a&jA=MAq/X__/0VQZV;<&> >/>>>	>	>
> Mr   c           
          ||kD  rt        d| d| d      | j                  |      d|ddf   }|dk(  r>t        j                  t        j                  t        j                  |d      d      d      S | j	                  | j                  |      | j                  |      | j                  |            }t        |dz
        D ]T  }| j	                  | j                  |      | j                  |      | j                  |            }| j                  ||      }V t        |      D ]D  }t        |      D ]4  }	t        |      D ]$  }
t        j                  ||||	|
f         |||	|
f<   & 6 F | j                  ||||      S )a  Construct orthogonal kernel for convolution.

    Args:
      ksize: Kernel size.
      cin: Number of input channels.
      cout: Number of output channels.

    Returns:
      An [ksize, ksize, ksize, cin, cout] orthogonal kernel.
    Raises:
      ValueError: If cin > cout.
    r  r  r  r   Nr   r   r  )r   r  r  r  r  r  r  r  r   r   r  s              r   r   z*ConvolutionOrthogonal3D._orthogonal_kernel  s    Tz;C5 A??CfBH I I""4(32Dz""


	 5 5dA >
BAG G 	""4($*D*DT*J""4(	*A 519 %

$
$T
*D,F,Ft,L

$
$T
*,d 

At
$a	%
 5\ 9U| 9!u 	9AtQq!QwZ8!Aq!G*	999
 5%77r   r&   r  r   r   r   r$  r$  g  s"    **3"#J$L"8r   r$  zinitializers.identityc                   X    e Zd ZdZ eddd      dej                  fd       Zd	dZd Z	y)
Identitya,  Initializer that generates the identity matrix.

  Only use for 2D matrices.

  Args:
    gain: Multiplicative factor to apply to the identity matrix.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.
  Nr0   r   rj   c                 X    || _         t        t        j                  |            | _        y r2   )r   ro   r   r4   r   )r   r   r   s      r   r6   zIdentity.__init__   s      DI$V__U%;<DJr   c                 X   ||n|j                   }t        |      dk7  rt        d|       || j                  }t	        |t
        j                        r|j                         }t        j                  |d|i}|!t        j                  ||j                  |      }| j                  |z  S )Nr   r   r   )r   r   r   r   rO   r   TensorShaper   r	   r   r   slice
var_offsetr   )r   r   r   r   r   initializers         r   r   zIdentity.__call__'  s    (0n6O6OJ
:! L" # # }jje*l667%%'j!%%z??K!OOK1J1J$)+k99{""r   c                 H    | j                   | j                  j                  dS )N)r   r   )r   r   r=   r    s    r   r!   zIdentity.get_config7      II

88r   r&   r?   r   r   r   r3  r3    sA     467>@ V^^ =@=# 9r   r3  glorot_uniform_initializerzinitializers.glorot_uniformc                   \     e Zd ZdZ eddd      dej                  f fd	       Zd Z xZ	S )GlorotUniforma  The Glorot uniform initializer, also called Xavier uniform initializer.

  It draws samples from a uniform distribution within [-limit, limit]
  where `limit` is `sqrt(6 / (fan_in + fan_out))`
  where `fan_in` is the number of input units in the weight tensor
  and `fan_out` is the number of output units in the weight tensor.

  Args:
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.
  References:
      [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html)
      ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf))
  Nr0   r   c                 4    t         t        |   ddd|       y )Nrj   r   r   r   r   r   ra   )superr>  r6   r   ra   r   	__class__s      r   r6   zGlorotUniform.__init__P  s#     
-'		 ( Fr   c                 H    | j                   | j                  j                  dS N)ra   r   ra   r   r=   r    s    r   r!   zGlorotUniform.get_configW  r;  r   
r'   r(   r)   r*   r   r   r@   r6   r!   __classcell__rC  s   @r   r>  r>  ;  s?    " 467>@ fnn F@F9r   r>  glorot_normal_initializerzinitializers.glorot_normalc                   \     e Zd ZdZ eddd      dej                  f fd	       Zd Z xZ	S )GlorotNormala)  The Glorot normal initializer, also called Xavier normal initializer.

  It draws samples from a truncated normal distribution centered on 0
  with standard deviation (after truncation) given by
  `stddev = sqrt(2 / (fan_in + fan_out))` where `fan_in` is the number
  of input units in the weight tensor and `fan_out` is the number of
  output units in the weight tensor.

  Args:
    seed: A Python integer. Used to create random seeds. See
      `tf.compat.v1.set_random_seed` for behavior.
    dtype: Default data type, used if no `dtype` argument is provided when
      calling the initializer. Only floating point types are supported.
  References:
      [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html)
      ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf))
  Nr0   r   c                 4    t         t        |   ddd|       y )Nrj   r   r}   r@  )rA  rL  r6   rB  s      r   r6   zGlorotNormal.__init__q  s$     
,&	0B ' Or   c                 H    | j                   | j                  j                  dS rE  rF  r    s    r   r!   zGlorotNormal.get_configx  r;  r   rG  rI  s   @r   rL  rL  [  s?    $ 467>@ fnn O@O9r   rL  zinitializers.lecun_normalc                      t        ddd|       S )a  LeCun normal initializer.

  It draws samples from a truncated normal distribution centered on 0
  with standard deviation (after truncation) given by
  `stddev = sqrt(1 / fan_in)` where `fan_in` is the number of
  input units in the weight tensor.

  Args:
      seed: A Python integer. Used to seed the random generator.

  Returns:
      An initializer.

  References:
      - Self-Normalizing Neural Networks,
      [Klambauer et al.,
      2017](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks)
      # pylint: disable=line-too-long
      ([pdf](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf))
      - Efficient Backprop,
      [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)
  rj   r   r}   r@  r   rd   s    r   lecun_normalrQ    s    0 
X,>T
K Kr   zinitializers.lecun_uniformc                      t        ddd|       S )a  LeCun uniform initializer.

  It draws samples from a uniform distribution within [-limit, limit]
  where `limit` is `sqrt(3 / fan_in)`
  where `fan_in` is the number of input units in the weight tensor.

  Args:
      seed: A Python integer. Used to seed the random generator.

  Returns:
      An initializer.

  References:
      - Self-Normalizing Neural Networks,
      [Klambauer et al.,
      2017](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks)
      # pylint: disable=line-too-long
      ([pdf](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf))
      - Efficient Backprop,
      [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)
  rj   r   r   r@  rP  rd   s    r   lecun_uniformrS    s    . 
XID
B Br   zinitializers.he_normalc                      t        ddd|       S )a  He normal initializer.

  It draws samples from a truncated normal distribution centered on 0
  with standard deviation (after truncation) given by
  `stddev = sqrt(2 / fan_in)` where `fan_in` is the number of
  input units in the weight tensor.

  Args:
      seed: A Python integer. Used to seed the random generator.

  Returns:
      An initializer.

  References:
      [He et al., 2015]
      (https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html)
      # pylint: disable=line-too-long
      ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf))
  r   r   r}   r@  rP  rd   s    r   	he_normalrU    s    * 
X,>T
K Kr   zinitializers.he_uniformc                      t        ddd|       S )a  He uniform variance scaling initializer.

  It draws samples from a uniform distribution within [-limit, limit]
  where `limit` is `sqrt(6 / fan_in)`
  where `fan_in` is the number of input units in the weight tensor.

  Args:
      seed: A Python integer. Used to seed the random generator.

  Returns:
      An initializer.

  References:
      [He et al., 2015]
      (https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html)
      # pylint: disable=line-too-long
      ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf))
  r   r   r   r@  rP  rd   s    r   
he_uniformrW    s    ( 
XID
B Br   c                     t        |       dk  rdx}}nPt        |       dk(  r| d   x}}n:t        |       dk(  r| d   }| d   }n!d}| dd D ]  }||z  }	 | d   |z  }| d   |z  }t        |      t        |      fS )zComputes the number of input and output units for a weight shape.

  Args:
    shape: Integer shape tuple or TF tensor shape.

  Returns:
    A tuple of integer scalars (fan_in, fan_out).
  r   r   r   Nr   r   )r   r   )r   r   r   receptive_field_sizer   s        r   r   r     s     	Z!^FW
5zQQxFW
5zQ1XFAhG Sbz "c!"2Y--FBi..G	Vc'l	""r   c                 <    | j                   st        d|  d      | S )zValidate and return floating point type based on `dtype`.

  `dtype` must be a floating point type.

  Args:
    dtype: The data type to validate.

  Returns:
    Validated type.

  Raises:
    ValueError: if `dtype` is not a floating point type.
  z=Argument `dtype` is expected to be floating point. Received: r   )is_floatingr   r   s    r   ro   ro     s0     
		
 ""'+ , ,	,r   r2   )@r*   r   numpyrM   tensorflow.python.frameworkr   r   r   tensorflow.python.opsr   r   r   r	   r
   r   tensorflow.python.utilr   "tensorflow.python.util.deprecationr   r   r    tensorflow.python.util.tf_exportr   r   deprecated_endpointsr/   rC   rJ   r\   ri   rz   r   r   r   r   r   r   r  r$  r3  r>  rL  r,   rA   rH   rZ   rg   rx   r   r   r<  rJ  r   identity_initializerconvolutional_delta_orthogonalconvolutional_orthogonal_1dconvolutional_orthogonal_2dconvolutional_orthogonal_3drQ  rS  rU  rW  r   ro   r   r   r   <module>rh     s  "   3 . 4 + 1 0 1 * , . 9 D > 6* *Z #%89:!!!"67P&K P& 8 ;P&f "$678!!!"57IJ &;  & K 9 &F &(>?@!!!"89m;{ m; : Am;` ,.JKL!!!"?@UK U A MUp +-HIJ!!!">?U; U @ KUp .0NOP!!!"A"@BZk ZB QZz ')K  "!!"D"EG<P <PG
<P~ .0NOP!!!"A"@BTk TB QTn (*BCD!!!";":<AL AL< EALLBL BLJ@=K @=FS13 S1l~*3 ~*Bi83 i8X &'(!!!"9:#9{ #9 ; )#9L +-JKL!!!">"?A9O 9A M9: *,HIJ!!!"=">@9? 9@ K9B    * ( . #5  . * ( #  !; 5 5 5  *+,K -K6 +,-B .B4 '()K *K0 ()*B +B4#6r   