# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Matern kernels."""

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

import numpy as np
import tensorflow as tf
from tensorflow_probability.python.positive_semidefinite_kernels import positive_semidefinite_kernel as psd_kernel
from tensorflow_probability.python.positive_semidefinite_kernels.internal import util

__all__ = [
    'MaternOneHalf',
    'MaternThreeHalves',
    'MaternFiveHalves',
]

def _validate_arg_if_not_none(arg, assertion, validate_args):
  if arg is None:
    return arg
  with tf.control_dependencies([assertion(arg)] if validate_args else []):
    result = tf.identity(arg)
  return result

class _AmplitudeLengthScaleMixin(object):
  """Shared logic for amplitude/length_scale parameterized kernels."""

  def _init_params(self, amplitude, length_scale, validate_args):
    """Shared init logic for `amplitude` and `length_scale` params.

    Args:
      amplitude: `Tensor` (or convertible) or `None` to convert, validate.
      length_scale: `Tensor` (or convertible) or `None` to convert, validate.
      validate_args: If `True`, parameters are checked for validity despite
        possibly degrading runtime performance

    Returns:
      dtype: The common `DType` of the parameters.
    """
    dtype = util.maybe_get_common_dtype(
        [amplitude, length_scale])
    if amplitude is not None:
      amplitude = tf.convert_to_tensor(
          value=amplitude, name='amplitude', dtype=dtype)
    self._amplitude = _validate_arg_if_not_none(
        amplitude, tf.compat.v1.assert_positive, validate_args)
    if length_scale is not None:
      length_scale = tf.convert_to_tensor(
          value=length_scale, name='length_scale', dtype=dtype)
    self._length_scale = _validate_arg_if_not_none(
        length_scale, tf.compat.v1.assert_positive, validate_args)
    return dtype

  @property
  def amplitude(self):
    """Amplitude parameter."""
    return self._amplitude

  @property
  def length_scale(self):
    """Length scale parameter."""
    return self._length_scale

  def _batch_shape(self):
    scalar_shape = tf.TensorShape([])
    return tf.broadcast_static_shape(
        scalar_shape if self.amplitude is None else self.amplitude.shape,
        scalar_shape if self.length_scale is None else self.length_scale.shape)

  def _batch_shape_tensor(self):
    return tf.broadcast_dynamic_shape(
        [] if self.amplitude is None else tf.shape(input=self.amplitude),
        [] if self.length_scale is None else tf.shape(input=self.length_scale))

class MaternOneHalf(_AmplitudeLengthScaleMixin,
                    psd_kernel.PositiveSemidefiniteKernel):
  """Matern Kernel with parameter 1/2.

  This kernel is part of the Matern family of kernels, with parameter 1/2.
  Also known as the Exponential or Laplacian Kernel, a Gaussian process
  parameterized by this kernel, is also known as an Ornstein-Uhlenbeck process
  (https://en.wikipedia.org/wiki/Ornstein%E2%80%93Uhlenbeck_process).

  The kernel has the following form:

  ```none
    k(x, y) = amplitude**2  * exp(-||x - y|| / length_scale)
  ```

  where the double-bars represent vector length (i.e. Euclidean, or L2 Norm).
  This kernel, acts over the space `S = R^(D1 x D2 .. x Dd)`.
  """

  def __init__(self,
               amplitude=None,
               length_scale=None,
               feature_ndims=1,
               validate_args=False,
               name='MaternOneHalf'):
    """Construct a MaternOneHalf kernel instance.

    Args:
      amplitude: Positive floating point `Tensor` that controls the maximum
        value of the kernel. Must be broadcastable with `length_scale` and
        inputs to `apply` and `matrix` methods. A value of `None` is treated
        like 1.
      length_scale: Positive floating point `Tensor` that controls how sharp or
        wide the kernel shape is. This provides a characteristic "unit" of
        length against which `||x - y||` can be compared for scale. Must be
        broadcastable with `amplitude` and inputs to `apply` and `matrix`
        methods. A value of `None` is treated like 1.
      feature_ndims: Python `int` number of rightmost dims to include in the
        squared difference norm in the exponential.
      validate_args: If `True`, parameters are checked for validity despite
        possibly degrading runtime performance
      name: Python `str` name prefixed to Ops created by this class.
    """
    with tf.compat.v1.name_scope(
        name, values=[amplitude, length_scale]) as name:
      dtype = super(MaternOneHalf, self)._init_params(amplitude, length_scale,
                                                      validate_args)
    super(MaternOneHalf, self).__init__(feature_ndims, dtype=dtype, name=name)

  def _apply(self, x1, x2, param_expansion_ndims=0):
    # Use util.sqrt_with_finite_grads to avoid NaN gradients when `x1 == x2`.
    norm = util.sqrt_with_finite_grads(
        util.sum_rightmost_ndims_preserving_shape(
            tf.math.squared_difference(x1, x2), self.feature_ndims))
    if self.length_scale is not None:
      length_scale = util.pad_shape_right_with_ones(
          self.length_scale, ndims=param_expansion_ndims)
      norm /= length_scale
    log_result = -norm

    if self.amplitude is not None:
      amplitude = util.pad_shape_right_with_ones(
          self.amplitude, ndims=param_expansion_ndims)
      log_result += 2. * tf.math.log(amplitude)
    return tf.exp(log_result)

class MaternThreeHalves(_AmplitudeLengthScaleMixin,
                        psd_kernel.PositiveSemidefiniteKernel):
  """Matern Kernel with parameter 3/2.

  This kernel is part of the Matern family of kernels, with parameter 3/2.

  ```none
    z = sqrt(3) * ||x - y|| / length_scale
    k(x, y) = (1 + z) * exp(-z)
  ```

  where the double-bars represent vector length (i.e. Euclidean, or L2 Norm).
  This kernel, acts over the space `S = R^(D1 x D2 .. x Dd)`.
  """

  def __init__(self,
               amplitude=None,
               length_scale=None,
               feature_ndims=1,
               validate_args=False,
               name='MaternThreeHalves'):
    """Construct a MaternThreeHalves kernel instance.

    Args:
      amplitude: Positive floating point `Tensor` that controls the maximum
        value of the kernel. Must be broadcastable with `length_scale` and
        inputs to `apply` and `matrix` methods. A value of `None` is treated
        like 1.
      length_scale: Positive floating point `Tensor` that controls how sharp or
        wide the kernel shape is. This provides a characteristic "unit" of
        length against which `||x - y||` can be compared for scale. Must be
        broadcastable with `amplitude` and inputs to `apply` and `matrix`
        methods. A value of `None` is treated like 1.
      feature_ndims: Python `int` number of rightmost dims to include in the
        squared difference norm in the exponential.
      validate_args: If `True`, parameters are checked for validity despite
        possibly degrading runtime performance
      name: Python `str` name prefixed to Ops created by this class.
    """
    with tf.compat.v1.name_scope(
        name, values=[amplitude, length_scale]) as name:
      dtype = super(MaternThreeHalves, self)._init_params(
          amplitude, length_scale, validate_args)
    super(MaternThreeHalves, self).__init__(
        feature_ndims, dtype=dtype, name=name)

  def _apply(self, x1, x2, param_expansion_ndims=0):
    # Use util.sqrt_with_finite_grads to avoid NaN gradients when `x1 == x2`.
    norm = util.sqrt_with_finite_grads(
        util.sum_rightmost_ndims_preserving_shape(
            tf.math.squared_difference(x1, x2), self.feature_ndims))
    if self.length_scale is not None:
      length_scale = util.pad_shape_right_with_ones(
          self.length_scale, ndims=param_expansion_ndims)
      norm /= length_scale
    series_term = np.sqrt(3) * norm
    log_result = tf.math.log1p(series_term) - series_term

    if self.amplitude is not None:
      amplitude = util.pad_shape_right_with_ones(self.amplitude,
                                                 param_expansion_ndims)
      log_result += 2. * tf.math.log(amplitude)
    return tf.exp(log_result)

class MaternFiveHalves(_AmplitudeLengthScaleMixin,
                       psd_kernel.PositiveSemidefiniteKernel):
  """Matern 5/2 Kernel.

  This kernel is part of the Matern family of kernels, with parameter 5/2.

  ```none
    z = sqrt(5) * ||x - y|| / length_scale
    k(x, y) = (1 + z + (z ** 2) / 3) * exp(-z)
  ```

  where the double-bars represent vector length (i.e. Euclidean, or L2 Norm).
  This kernel, acts over the space `S = R^(D1 x D2 .. x Dd)`.
  """

  def __init__(self,
               amplitude=None,
               length_scale=None,
               feature_ndims=1,
               validate_args=False,
               name='MaternFiveHalves'):
    """Construct a MaternFiveHalves kernel instance.

    Args:
      amplitude: Positive floating point `Tensor` that controls the maximum
        value of the kernel. Must be broadcastable with `length_scale` and
        inputs to `apply` and `matrix` methods. A value of `None` is treated
        like 1.
      length_scale: Positive floating point `Tensor` that controls how sharp or
        wide the kernel shape is. This provides a characteristic "unit" of
        length against which `||x - y||` can be compared for scale. Must be
        broadcastable with `amplitude`, and inputs to `apply` and `matrix`
        methods. A value of `None` is treated like 1.
      feature_ndims: Python `int` number of rightmost dims to include in the
        squared difference norm in the exponential.
      validate_args: If `True`, parameters are checked for validity despite
        possibly degrading runtime performance
      name: Python `str` name prefixed to Ops created by this class.
    """
    with tf.compat.v1.name_scope(
        name, values=[amplitude, length_scale]) as name:
      dtype = super(MaternFiveHalves, self)._init_params(
          amplitude, length_scale, validate_args)
    super(MaternFiveHalves, self).__init__(
        feature_ndims, dtype=dtype, name=name)

  def _apply(self, x1, x2, param_expansion_ndims=0):
    # Use util.sqrt_with_finite_grads to avoid NaN gradients when `x1 == x2`.
    norm = util.sqrt_with_finite_grads(
        util.sum_rightmost_ndims_preserving_shape(
            tf.math.squared_difference(x1, x2), self.feature_ndims))
    if self.length_scale is not None:
      length_scale = util.pad_shape_right_with_ones(
          self.length_scale, ndims=param_expansion_ndims)
      norm /= length_scale
    series_term = np.sqrt(5) * norm
    log_result = tf.math.log1p(series_term + series_term**2 / 3.) - series_term

    if self.amplitude is not None:
      amplitude = util.pad_shape_right_with_ones(self.amplitude,
                                                 param_expansion_ndims)
      log_result += 2. * tf.math.log(amplitude)
    return tf.exp(log_result)


# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Registration and usage mechanisms for KL-divergences."""

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

import tensorflow.compat.v2 as tf
from tensorflow.python.util import tf_inspect  # pylint: disable=g-direct-tensorflow-import

_DIVERGENCES = {}

__all__ = [
    "RegisterKL",
    "kl_divergence",
]

def _registered_kl(type_a, type_b):
  """Get the KL function registered for classes a and b."""
  hierarchy_a = tf_inspect.getmro(type_a)
  hierarchy_b = tf_inspect.getmro(type_b)
  dist_to_children = None
  kl_fn = None
  for mro_to_a, parent_a in enumerate(hierarchy_a):
    for mro_to_b, parent_b in enumerate(hierarchy_b):
      candidate_dist = mro_to_a + mro_to_b
      candidate_kl_fn = _DIVERGENCES.get((parent_a, parent_b), None)
      if not kl_fn or (candidate_kl_fn and candidate_dist < dist_to_children):
        dist_to_children = candidate_dist
        kl_fn = candidate_kl_fn
  return kl_fn

def kl_divergence(distribution_a, distribution_b,
                  allow_nan_stats=True, name=None):
  """Get the KL-divergence KL(distribution_a || distribution_b).

  If there is no KL method registered specifically for `type(distribution_a)`
  and `type(distribution_b)`, then the class hierarchies of these types are
  searched.

  If one KL method is registered between any pairs of classes in these two
  parent hierarchies, it is used.

  If more than one such registered method exists, the method whose registered
  classes have the shortest sum MRO paths to the input types is used.

  If more than one such shortest path exists, the first method
  identified in the search is used (favoring a shorter MRO distance to
  `type(distribution_a)`).

  Args:
    distribution_a: The first distribution.
    distribution_b: The second distribution.
    allow_nan_stats: Python `bool`, default `True`. When `True`,
      statistics (e.g., mean, mode, variance) use the value "`NaN`" to
      indicate the result is undefined. When `False`, an exception is raised
      if one or more of the statistic's batch members are undefined.
    name: Python `str` name prefixed to Ops created by this class.

  Returns:
    A Tensor with the batchwise KL-divergence between `distribution_a`
    and `distribution_b`.

  Raises:
    NotImplementedError: If no KL method is defined for distribution types
      of `distribution_a` and `distribution_b`.
  """
  kl_fn = _registered_kl(type(distribution_a), type(distribution_b))
  if kl_fn is None:
    raise NotImplementedError(
        "No KL(distribution_a || distribution_b) registered for distribution_a "
        "type {} and distribution_b type {}".format(
            type(distribution_a).__name__, type(distribution_b).__name__))

  with tf.name_scope("KullbackLeibler"):
    kl_t = kl_fn(distribution_a, distribution_b, name=name)
    if allow_nan_stats:
      return kl_t

    # Check KL for NaNs
    kl_t = tf.identity(kl_t, name="kl")

    with tf.control_dependencies([
        tf.Assert(
            tf.logical_not(tf.reduce_any(input_tensor=tf.math.is_nan(kl_t))),
            [
                ("KL calculation between {} and {} returned NaN values "
                 "(and was called with allow_nan_stats=False). Values:".format(
                     distribution_a.name, distribution_b.name)),
                kl_t
            ])
    ]):
      return tf.identity(kl_t, name="checked_kl")

def cross_entropy(ref, other,
                  allow_nan_stats=True, name=None):
  """Computes the (Shannon) cross entropy.

  Denote two distributions by `P` (`ref`) and `Q` (`other`). Assuming `P, Q`
  are absolutely continuous with respect to one another and permit densities
  `p(x) dr(x)` and `q(x) dr(x)`, (Shanon) cross entropy is defined as:

  ```none
  H[P, Q] = E_p[-log q(X)] = -int_F p(x) log q(x) dr(x)
  ```

  where `F` denotes the support of the random variable `X ~ P`.

  Args:
    ref: `tfd.Distribution` instance.
    other: `tfd.Distribution` instance.
    allow_nan_stats: Python `bool`, default `True`. When `True`,
      statistics (e.g., mean, mode, variance) use the value "`NaN`" to
      indicate the result is undefined. When `False`, an exception is raised
      if one or more of the statistic's batch members are undefined.
    name: Python `str` prepended to names of ops created by this function.

  Returns:
    cross_entropy: `ref.dtype` `Tensor` with shape `[B1, ..., Bn]`
      representing `n` different calculations of (Shanon) cross entropy.
  """
  with tf.name_scope(name or "cross_entropy"):
    return ref.entropy() + kl_divergence(
        ref, other, allow_nan_stats=allow_nan_stats)

class RegisterKL(object):
  """Decorator to register a KL divergence implementation function.

  Usage:

  @distributions.RegisterKL(distributions.Normal, distributions.Normal)
  def _kl_normal_mvn(norm_a, norm_b):
    # Return KL(norm_a || norm_b)
  """

  def __init__(self, dist_cls_a, dist_cls_b):
    """Initialize the KL registrar.

    Args:
      dist_cls_a: the class of the first argument of the KL divergence.
      dist_cls_b: the class of the second argument of the KL divergence.
    """
    self._key = (dist_cls_a, dist_cls_b)

  def __call__(self, kl_fn):
    """Perform the KL registration.

    Args:
      kl_fn: The function to use for the KL divergence.

    Returns:
      kl_fn

    Raises:
      TypeError: if kl_fn is not a callable.
      ValueError: if a KL divergence function has already been registered for
        the given argument classes.
    """
    if not callable(kl_fn):
      raise TypeError("kl_fn must be callable, received: %s" % kl_fn)
    if self._key in _DIVERGENCES:
      raise ValueError("KL(%s || %s) has already been registered to: %s"
                       % (self._key[0].__name__, self._key[1].__name__,
                          _DIVERGENCES[self._key]))
    _DIVERGENCES[self._key] = kl_fn
    return kl_fn


# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Liberated Pixel Cup [(LPC)][1] Sprites Dataset.

This file provides logic to download and build a version of the sprites
video sequence dataset as used in the Disentangled Sequential
Autoencoder paper [(Li and Mandt, 2018)][2].

#### References:

[1]: Liberated Pixel Cup. http://lpc.opengameart.org. Accessed:
     2018-07-20.
[2]: Yingzhen Li and Stephan Mandt. Disentangled Sequential Autoencoder.
     In _International Conference on Machine Learning_, 2018.
     https://arxiv.org/abs/1803.02991
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from collections import namedtuple
import os
import random
import zipfile

from absl import flags
from six.moves import urllib
import tensorflow as tf

__all__ = ["SpritesDataset"]

flags.DEFINE_string(
    "data_dir",
    default=os.path.join(
        os.getenv("TEST_TMPDIR", "/tmp"),
        os.path.join("disentangled_vae", "data")),
    help="Directory where the dataset is stored.")

DATA_SPRITES_URL = "https://github.com/jrconway3/Universal-LPC-spritesheet/archive/master.zip"
DATA_SPRITES_DIR = "Universal-LPC-spritesheet-master"
WIDTH = 832
HEIGHT = 1344
FRAME_SIZE = 64
CHANNELS = 4

SKIN_COLORS = [
    os.path.join("body", "male", "light.png"),
    os.path.join("body", "male", "tanned2.png"),
    os.path.join("body", "male", "darkelf.png"),
    os.path.join("body", "male", "darkelf2.png"),
    os.path.join("body", "male", "dark.png"),
    os.path.join("body", "male", "dark2.png")
]
HAIRSTYLES = [
    os.path.join("hair", "male", "messy2", "green2.png"),
    os.path.join("hair", "male", "ponytail", "blue2.png"),
    os.path.join("hair", "male", "messy1", "light-blonde.png"),
    os.path.join("hair", "male", "parted", "white.png"),
    os.path.join("hair", "male", "plain", "ruby-red.png"),
    os.path.join("hair", "male", "jewfro", "purple.png")
]
TOPS = [
    os.path.join(
        "torso", "shirts", "longsleeve", "male", "maroon_longsleeve.png"),
    os.path.join(
        "torso", "shirts", "longsleeve", "male", "teal_longsleeve.png"),
    os.path.join(
        "torso", "shirts", "longsleeve", "male", "white_longsleeve.png"),
    os.path.join("torso", "plate", "chest_male.png"),
    os.path.join("torso", "leather", "chest_male.png"),
    os.path.join("formal_male_no_th-sh", "shirt.png")
]
PANTS = [
    os.path.join("legs", "pants", "male", "white_pants_male.png"),
    os.path.join("legs", "armor", "male", "golden_greaves_male.png"),
    os.path.join("legs", "pants", "male", "red_pants_male.png"),
    os.path.join("legs", "armor", "male", "metal_pants_male.png"),
    os.path.join("legs", "pants", "male", "teal_pants_male.png"),
    os.path.join("formal_male_no_th-sh", "pants.png")
]

Action = namedtuple("Action", ["name", "start_row", "frames"])
ACTIONS = [
    Action("walk", 8, 9),
    Action("spellcast", 0, 7),
    Action("slash", 12, 6)
]

Direction = namedtuple("Direction", ["name", "row_offset"])
DIRECTIONS = [
    Direction("west", 1),
    Direction("south", 2),
    Direction("east", 3),
]

FLAGS = flags.FLAGS

def read_image(filepath):
  """Returns an image tensor."""
  im_bytes = tf.io.read_file(filepath)
  im = tf.image.decode_image(im_bytes, channels=CHANNELS)
  im = tf.image.convert_image_dtype(im, tf.float32)
  return im

def join_seq(seq):
  """Joins a sequence side-by-side into a single image."""
  return tf.concat(tf.unstack(seq), 1)

def download_sprites():
  """Downloads the sprites data and returns the saved filepath."""
  filepath = os.path.join(FLAGS.data_dir, DATA_SPRITES_DIR)
  if not tf.io.gfile.exists(filepath):
    if not tf.io.gfile.exists(FLAGS.data_dir):
      tf.io.gfile.makedirs(FLAGS.data_dir)
    zip_name = "{}.zip".format(filepath)
    urllib.request.urlretrieve(DATA_SPRITES_URL, zip_name)
    with zipfile.ZipFile(zip_name, "r") as zip_file:
      zip_file.extractall(FLAGS.data_dir)
    tf.io.gfile.remove(zip_name)
  return filepath

def create_character(skin, hair, top, pants):
  """Creates a character sprite from a set of attribute sprites."""
  dtype = skin.dtype
  hair_mask = tf.cast(hair[..., -1:] <= 0, dtype)
  top_mask = tf.cast(top[..., -1:] <= 0, dtype)
  pants_mask = tf.cast(pants[..., -1:] <= 0, dtype)
  char = (skin * hair_mask) + hair
  char = (char * top_mask) + top
  char = (char * pants_mask) + pants
  return char

def create_seq(character, action_metadata, direction, length=8, start=0):
  """Creates a sequence.

  Args:
    character: A character sprite tensor.
    action_metadata: An action metadata tuple.
    direction: An integer representing the direction, i.e., the row
      offset within each action group corresponding to a particular
      direction.
    length: Desired length of the sequence. If this is longer than
      the number of available frames, it will roll over to the
      beginning.
    start: Index of possible frames at which to start the sequence.

  Returns:
    A sequence tensor.
  """
  sprite_start = (action_metadata[0]+direction) * FRAME_SIZE
  sprite_end = (action_metadata[0]+direction+1) * FRAME_SIZE
  sprite_line = character[sprite_start:sprite_end, ...]

  # Extract 64x64 patches that are side-by-side in the sprite, and limit
  # to the actual number of frames for the given action.
  frames = tf.stack(tf.split(sprite_line, 13, axis=1))  # 13 is a hack
  frames = frames[0:action_metadata[1]]

  # Extract a slice of the desired length.
  # NOTE: Length could be longer than the number of frames, so tile as needed.
  frames = tf.roll(frames, shift=-start, axis=0)
  frames = tf.tile(frames, [2, 1, 1, 1])  # 2 is a hack
  frames = frames[:length]
  frames = tf.cast(frames, dtype=tf.float32)
  frames.set_shape([length, FRAME_SIZE, FRAME_SIZE, CHANNELS])
  return frames

def create_random_seq(character, action_metadata, direction, length=8):
  """Creates a random sequence."""
  start = tf.random.uniform([], maxval=action_metadata[1], dtype=tf.int32)
  return create_seq(character, action_metadata, direction, length, start)

def create_sprites_dataset(characters, actions, directions, channels=3,
                           length=8, shuffle=False, fake_data=False):
  """Creates a tf.data pipeline for the sprites dataset.

  Args:
    characters: A list of (skin, hair, top, pants) tuples containing
      relative paths to the sprite png image for each attribute.
    actions: A list of Actions.
    directions: A list of Directions.
    channels: Number of image channels to yield.
    length: Desired length of the sequences.
    shuffle: Whether or not to shuffle the characters and sequences
      start frame.
    fake_data: Boolean for whether or not to yield synthetic data.

  Returns:
    A tf.data.Dataset yielding (seq, skin label index, hair label index,
    top label index, pants label index, action label index, skin label
    name, hair label_name, top label name, pants label name, action
    label name) tuples.
  """
  if fake_data:
    dummy_image = tf.random.normal([HEIGHT, WIDTH, CHANNELS])
  else:
    basedir = download_sprites()

  action_names = [action.name for action in actions]
  action_metadata = [(action.start_row, action.frames) for action in actions]

  direction_rows = [direction.row_offset for direction in directions]

  chars = tf.data.Dataset.from_tensor_slices(characters)
  act_names = tf.data.Dataset.from_tensor_slices(action_names).repeat()
  acts_metadata = tf.data.Dataset.from_tensor_slices(action_metadata).repeat()
  dir_rows = tf.data.Dataset.from_tensor_slices(direction_rows).repeat()

  if shuffle:
    chars = chars.shuffle(len(characters))

  dataset = tf.data.Dataset.zip((chars, act_names, acts_metadata, dir_rows))

  skin_table = tf.contrib.lookup.index_table_from_tensor(sorted(SKIN_COLORS))
  hair_table = tf.contrib.lookup.index_table_from_tensor(sorted(HAIRSTYLES))
  top_table = tf.contrib.lookup.index_table_from_tensor(sorted(TOPS))
  pants_table = tf.contrib.lookup.index_table_from_tensor(sorted(PANTS))
  action_table = tf.contrib.lookup.index_table_from_tensor(sorted(action_names))

  def process_example(attrs, act_name, act_metadata, dir_row_offset):
    """Processes a dataset row."""
    skin_name = attrs[0]
    hair_name = attrs[1]
    top_name = attrs[2]
    pants_name = attrs[3]

    if fake_data:
      char = dummy_image
    else:
      skin = read_image(basedir + os.sep + skin_name)
      hair = read_image(basedir + os.sep + hair_name)
      top = read_image(basedir + os.sep + top_name)
      pants = read_image(basedir + os.sep + pants_name)
      char = create_character(skin, hair, top, pants)

    if shuffle:
      seq = create_random_seq(char, act_metadata, dir_row_offset, length)
    else:
      seq = create_seq(char, act_metadata, dir_row_offset, length)
    seq = seq[..., :channels]  # limit output channels

    skin_idx = skin_table.lookup(skin_name)
    hair_idx = hair_table.lookup(hair_name)
    top_idx = top_table.lookup(top_name)
    pants_idx = pants_table.lookup(pants_name)
    act_idx = action_table.lookup(act_name)

    return (seq, skin_idx, hair_idx, top_idx, pants_idx, act_idx,
            skin_name, hair_name, top_name, pants_name, act_name)

  dataset = dataset.map(process_example)
  return dataset

class SpritesDataset(object):
  """Liberated Pixel Cup [(LPC)][1] Sprites Dataset.

  This file provides logic to download and build a version of the
  sprites video sequence dataset as used in the Disentangled Sequential
  Autoencoder paper [(Li and Mandt, 2018)][2]. The dataset contains
  sprites (graphics files used to generate animated sequences) of human
  characters wearing a variety of clothing, and performing a variety of
  actions. The paper limits the dataset used for training to four
  attribute categories (skin color, hairstyles, tops, and pants), each
  of which are limited to include six variants. Thus, there are
  6^4 = 1296 possible animated characters in this dataset. The
  characters are shuffled and deterministically split such that 1000
  characters are used for the training set, and 296 are used for the
  testing set. The numbers are consistent with the paper, but the exact
  split is impossible to match given the currently available paper
  details. The actions are limited to three categories (walking,
  casting spells, and slashing), each with three viewing angles.
  Sequences of length T=8 frames are generated depicting a given
  character performing a given action, starting at a random frame in the
  sequence.

  Attributes:
    train: Training dataset with 1000 characters each performing an
      action.
    test: Testing dataset with 296 characters each performing an action.

  #### References:

  [1]: Liberated Pixel Cup. http://lpc.opengameart.org. Accessed:
       2018-07-20.
  [2]: Yingzhen Li and Stephan Mandt. Disentangled Sequential
       Autoencoder. In _International Conference on Machine Learning_,
       2018. https://arxiv.org/abs/1803.02991
  """

  def __init__(self, channels=3, shuffle_train=True, fake_data=False):
    """Creates the SpritesDataset and stores train and test datasets.

    The datasets yield (seq, skin label index, hair label index, top
    label index, pants label index, action label index, skin label name,
    hair label_name, top label name, pants label name, action label
    name) tuples.

    Args:
      channels: Number of image channels to yield.
      shuffle_train: Boolean for whether or not to shuffle the training
        set.
      fake_data: Boolean for whether or not to yield synthetic data.

    Raises:
      ValueError: If the number of training or testing examples is
        incorrect, or if there is overlap betweem the two datasets.
    """
    super(SpritesDataset, self).__init__()
    self.frame_size = FRAME_SIZE
    self.channels = channels
    self.length = 8
    num_train = 1000
    num_test = 296
    characters = [(skin, hair, top, pants)
                  for skin in sorted(SKIN_COLORS)
                  for hair in sorted(HAIRSTYLES)
                  for top in sorted(TOPS)
                  for pants in sorted(PANTS)]
    random.seed(42)
    random.shuffle(characters)
    train_chars = characters[:num_train]
    test_chars = characters[num_train:]
    num_train_actual = len(set(train_chars))
    num_test_actual = len(set(test_chars))
    num_train_test_overlap = len(set(train_chars) & set(test_chars))
    if num_train_actual != num_train:
      raise ValueError(
          "Unexpected number of training examples: {}.".format(
              num_train_actual))
    if num_test_actual != num_test:
      raise ValueError(
          "Unexpected number of testing examples: {}.".format(
              num_test_actual))
    if num_train_test_overlap > 0:  # pylint: disable=g-explicit-length-test
      raise ValueError(
          "Overlap between train and test datasets detected: {}.".format(
              num_train_test_overlap))

    self.train = create_sprites_dataset(
        train_chars, ACTIONS, DIRECTIONS, self.channels, self.length,
        shuffle=shuffle_train, fake_data=fake_data)
    self.test = create_sprites_dataset(
        test_chars, ACTIONS, DIRECTIONS, self.channels, self.length,
        shuffle=False, fake_data=fake_data)


# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""The Blockwise distribution."""

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

import functools

import tensorflow.compat.v2 as tf

from tensorflow_probability.python.distributions import distribution
from tensorflow_probability.python.distributions import kullback_leibler
from tensorflow_probability.python.distributions import seed_stream
from tensorflow_probability.python.internal import assert_util
from tensorflow_probability.python.internal import dtype_util
from tensorflow_probability.python.internal import reparameterization
from tensorflow_probability.python.internal import tensorshape_util

class Blockwise(distribution.Distribution):
  """Blockwise distribution.

  This distribution enables combining different distribution families as one.
  """
  # TODO(b/126733380): Add documentation.

  def __init__(self,
               distributions,
               dtype_override=None,
               validate_args=False,
               allow_nan_stats=False,
               name='Blockwise'):
    """Construct the `Blockwise` distribution.

    Args:
      distributions: Python `list` of `tfp.distributions.Distribution`
        instances. All distribution instances must have the same `batch_shape`
        and all must have `event_ndims==1`, i.e., be vector-variate
        distributions.
      dtype_override: samples of `distributions` will be cast to this `dtype`.
        If unspecified, all `distributions` must have the same `dtype`.
        Default value: `None` (i.e., do not cast).
      validate_args: Python `bool`, default `False`. When `True` distribution
        parameters are checked for validity despite possibly degrading runtime
        performance. When `False` invalid inputs may silently render incorrect
        outputs.
      allow_nan_stats: Python `bool`, default `True`. When `True`, statistics
        (e.g., mean, mode, variance) use the value "`NaN`" to indicate the
        result is undefined. When `False`, an exception is raised if one or
        more of the statistic's batch members are undefined.
      name: Python `str` name prefixed to Ops created by this class.
    """
    parameters = dict(locals())
    with tf.name_scope(name) as name:
      self._assertions = _maybe_validate_distributions(
          distributions, dtype_override, validate_args)

      if dtype_override is not None:
        dtype = dtype_override
      else:
        dtype = set(
            dtype_util.base_dtype(d.dtype)
            for d in distributions
            if d.dtype is not None)
        if len(dtype) == 0:  # pylint: disable=g-explicit-length-test
          dtype = tf.float32
        elif len(dtype) == 1:
          dtype = dtype.pop()
        else:
          # Shouldn't be here: we already threw an exception in
          # `_maybe_validate_distributions`.
          raise ValueError('Internal Error: unable to resolve `dtype`.')

      reparameterization_type = set(d.reparameterization_type
                                    for d in distributions)
      reparameterization_type = (reparameterization_type.pop()
                                 if len(reparameterization_type) == 1
                                 else reparameterization.NOT_REPARAMETERIZED)

      self._distributions = distributions
      super(Blockwise, self).__init__(
          dtype=dtype,
          validate_args=validate_args,
          allow_nan_stats=allow_nan_stats,
          reparameterization_type=reparameterization_type,
          parameters=parameters,
          graph_parents=_flatten(d._graph_parents for d in distributions),  # pylint: disable=protected-access
          name=name)

  @property
  def distributions(self):
    return self._distributions

  def _batch_shape(self):
    return functools.reduce(
        lambda b, d: tensorshape_util.merge_with(b, d.batch_shape),
        self.distributions, tf.TensorShape(None))

  def _batch_shape_tensor(self):
    with tf.control_dependencies(self._assertions):
      # We could get partial static-ness by swapping in values from
      # `self.batch_shape`, however this would require multiple graph ops.
      return self.distributions[0].batch_shape_tensor()

  def _event_shape(self):
    event_size = [
        tensorshape_util.num_elements(d.event_shape) for d in self.distributions
    ]
    if any(r is None for r in event_size):
      return tf.TensorShape([None])
    return tf.TensorShape([sum(event_size)])

  def _event_shape_tensor(self):
    with tf.control_dependencies(self._assertions):
      event_sizes = [
          tf.reduce_prod(input_tensor=d.event_shape_tensor())  # pylint: disable=g-complex-comprehension
          if tensorshape_util.num_elements(d.event_shape) is None else
          tensorshape_util.num_elements(d.event_shape)
          for d in self._distributions
      ]
      return tf.reduce_sum(input_tensor=event_sizes)[tf.newaxis]

  def _sample_n(self, n, seed=None):
    with tf.control_dependencies(self._assertions):
      seed = seed_stream.SeedStream(seed=seed, salt='BlockwiseDistribution')
      xs = [tf.cast(d.sample(n, seed=seed()), self.dtype)
            for d in self.distributions]
      return tf.concat(xs, axis=-1)

  def _log_prob(self, x):
    additional_assertions = []
    message = 'Input must have at least one dimension.'
    if tensorshape_util.rank(x.shape) is not None:
      if tensorshape_util.rank(x.shape) == 0:
        raise ValueError(message)
    elif self.validate_args:
      additional_assertions.append(
          assert_util.assert_rank_at_least(x, 1, message=message))
    with tf.control_dependencies(self._assertions + additional_assertions):
      event_sizes = [d.event_shape_tensor()[0] for d in self.distributions]
      xs = tf.split(x, event_sizes, axis=-1)
      return sum(tf.cast(d.log_prob(tf.cast(x, d.dtype)), self.dtype)
                 for d, x in zip(self.distributions, xs))

  def _mean(self):
    with tf.control_dependencies(self._assertions):
      means = [tf.cast(d.mean(), self.dtype) for d in self._distributions]
      return tf.concat(means, axis=-1)

def _flatten(list_of_lists):
  return [item for sublist in list_of_lists for item in sublist]  # pylint: disable=g-complex-comprehension

def _is_iterable(x):
  try:
    _ = iter(x)
  except TypeError:
    return False
  return True

def _maybe_validate_distributions(distributions, dtype_override, validate_args):
  """Checks that `distributions` satisfies all assumptions."""
  assertions = []

  if not _is_iterable(distributions) or not distributions:
    raise ValueError('`distributions` must be a list of one or more '
                     'distributions.')

  if dtype_override is None:
    dts = [
        dtype_util.base_dtype(d.dtype)
        for d in distributions
        if d.dtype is not None
    ]
    if dts[1:] != dts[:-1]:
      raise TypeError('Distributions must have same dtype; found: {}.'.format(
          set(dtype_util.name(dt) for dt in dts)))

  # Validate event_ndims.
  for d in distributions:
    if tensorshape_util.rank(d.event_shape) is not None:
      if tensorshape_util.rank(d.event_shape) != 1:
        raise ValueError('`Distribution` must be vector variate, '
                         'found event nimds: {}.'.format(
                             tensorshape_util.rank(d.event_shape)))
    elif validate_args:
      assertions.append(
          assert_util.assert_equal(
              1, tf.size(input=d.event_shape_tensor()),
              message='`Distribution` must be vector variate.'))

  batch_shapes = [d.batch_shape for d in distributions]
  if all(tensorshape_util.is_fully_defined(b) for b in batch_shapes):
    if batch_shapes[1:] != batch_shapes[:-1]:
      raise ValueError('Distributions must have the same `batch_shape`; '
                       'found: {}.'.format(batch_shapes))
  elif validate_args:
    batch_shapes = [
        tensorshape_util.as_list(d.batch_shape)  # pylint: disable=g-complex-comprehension
        if tensorshape_util.is_fully_defined(d.batch_shape) else
        d.batch_shape_tensor() for d in distributions
    ]
    assertions.extend(
        assert_util.assert_equal(  # pylint: disable=g-complex-comprehension
            b1, b2,
            message='Distribution `batch_shape`s must be identical.')
        for b1, b2 in zip(batch_shapes[1:], batch_shapes[:-1]))

  return assertions

@kullback_leibler.RegisterKL(Blockwise, Blockwise)
def _kl_blockwise_blockwise(b0, b1, name=None):
  """Calculate the batched KL divergence KL(b0 || b1) with b0 and b1 Blockwise distributions.

  Args:
    b0: instance of a Blockwise distribution object.
    b1: instance of a Blockwise distribution object.
    name: (optional) Name to use for created operations. Default is
      "kl_blockwise_blockwise".

  Returns:
    kl_blockwise_blockwise: `Tensor`. The batchwise KL(b0 || b1).
  """
  if len(b0.distributions) != len(b1.distributions):
    raise ValueError(
        'Can only compute KL divergence between Blockwise distributions with '
        'the same number of component distributions.')

  # We also need to check that the event shapes match for each one.
  b0_event_sizes = [_event_size(d) for d in b0.distributions]
  b1_event_sizes = [_event_size(d) for d in b1.distributions]

  assertions = []
  message = ('Can only compute KL divergence between Blockwise distributions '
             'with the same pairwise event shapes.')

  if (all(isinstance(event_size, int) for event_size in b0_event_sizes) and
      all(isinstance(event_size, int) for event_size in b1_event_sizes)):
    if b0_event_sizes != b1_event_sizes:
      raise ValueError(message)
  else:
    if b0.validate_args or b1.validate_args:
      assertions.extend(
          assert_util.assert_equal(  # pylint: disable=g-complex-comprehension
              e1, e2, message=message)
          for e1, e2 in zip(b0_event_sizes, b1_event_sizes))

  with tf.name_scope(name or 'kl_blockwise_blockwise'):
    with tf.control_dependencies(assertions):
      return sum([
          kullback_leibler.kl_divergence(d1, d2) for d1, d2 in zip(
              b0.distributions, b1.distributions)])

def _event_size(d):
  if tensorshape_util.num_elements(d.event_shape) is not None:
    return tensorshape_util.num_elements(d.event_shape)
  return tf.reduce_prod(input_tensor=d.event_shape_tensor())


# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""The Half Normal distribution class."""

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

# Dependency imports
import numpy as np
import tensorflow.compat.v2 as tf

from tensorflow_probability.python.distributions import distribution
from tensorflow_probability.python.distributions import kullback_leibler
from tensorflow_probability.python.internal import assert_util
from tensorflow_probability.python.internal import dtype_util
from tensorflow_probability.python.internal import reparameterization
from tensorflow_probability.python.internal import special_math

__all__ = [
    "HalfNormal",
]

class HalfNormal(distribution.Distribution):
  """The Half Normal distribution with scale `scale`.

  #### Mathematical details

  The half normal is a transformation of a centered normal distribution.
  If some random variable `X` has normal distribution,
  ```none
  X ~ Normal(0.0, scale)
  Y = |X|
  ```
  Then `Y` will have half normal distribution. The probability density
  function (pdf) is:

  ```none
  pdf(x; scale, x > 0) = sqrt(2) / (scale * sqrt(pi)) *
    exp(- 1/2 * (x / scale) ** 2)
  )
  ```
  Where `scale = sigma` is the standard deviation of the underlying normal
  distribution.

  #### Examples

  Examples of initialization of one or a batch of distributions.

  ```python
  # Define a single scalar HalfNormal distribution.
  dist = tfp.distributions.HalfNormal(scale=3.0)

  # Evaluate the cdf at 1, returning a scalar.
  dist.cdf(1.)

  # Define a batch of two scalar valued HalfNormals.
  # The first has scale 11.0, the second 22.0
  dist = tfp.distributions.HalfNormal(scale=[11.0, 22.0])

  # Evaluate the pdf of the first distribution on 1.0, and the second on 1.5,
  # returning a length two tensor.
  dist.prob([1.0, 1.5])

  # Get 3 samples, returning a 3 x 2 tensor.
  dist.sample([3])
  ```

  """

  def __init__(self,
               scale,
               validate_args=False,
               allow_nan_stats=True,
               name="HalfNormal"):
    """Construct HalfNormals with scale `scale`.

    Args:
      scale: Floating point tensor; the scales of the distribution(s).
        Must contain only positive values.
      validate_args: Python `bool`, default `False`. When `True` distribution
        parameters are checked for validity despite possibly degrading runtime
        performance. When `False` invalid inputs may silently render incorrect
        outputs.
      allow_nan_stats: Python `bool`, default `True`. When `True`,
        statistics (e.g., mean, mode, variance) use the value "`NaN`" to
        indicate the result is undefined. When `False`, an exception is raised
        if one or more of the statistic's batch members are undefined.
      name: Python `str` name prefixed to Ops created by this class.
    """
    parameters = dict(locals())
    with tf.name_scope(name) as name:
      scale = tf.convert_to_tensor(
          value=scale,
          name="scale",
          dtype=dtype_util.common_dtype([scale], preferred_dtype=tf.float32))
      with tf.control_dependencies(
          [assert_util.assert_positive(scale)] if validate_args else []):
        self._scale = tf.identity(scale, name="scale")
    super(HalfNormal, self).__init__(
        dtype=self._scale.dtype,
        reparameterization_type=reparameterization.FULLY_REPARAMETERIZED,
        validate_args=validate_args,
        allow_nan_stats=allow_nan_stats,
        parameters=parameters,
        graph_parents=[self._scale],
        name=name)

  @staticmethod
  def _param_shapes(sample_shape):
    return {"scale": tf.convert_to_tensor(value=sample_shape, dtype=tf.int32)}

  @classmethod
  def _params_event_ndims(cls):
    return dict(scale=0)

  @property
  def scale(self):
    """Distribution parameter for the scale."""
    return self._scale

  def _batch_shape_tensor(self):
    return tf.shape(input=self.scale)

  def _batch_shape(self):
    return self.scale.shape

  def _event_shape_tensor(self):
    return tf.constant([], dtype=tf.int32)

  def _event_shape(self):
    return tf.TensorShape([])

  def _sample_n(self, n, seed=None):
    shape = tf.concat([[n], self.batch_shape_tensor()], 0)
    sampled = tf.random.normal(
        shape=shape, mean=0., stddev=1., dtype=self.dtype, seed=seed)
    return tf.abs(sampled * self.scale)

  def _prob(self, x):
    coeff = np.sqrt(2) / self.scale / np.sqrt(np.pi)
    pdf = coeff * tf.exp(-0.5 * (x / self.scale)**2)
    return pdf * tf.cast(x >= 0, self.dtype)

  def _cdf(self, x):
    truncated_x = tf.nn.relu(x)
    return tf.math.erf(truncated_x / self.scale / np.sqrt(2.0))

  def _entropy(self):
    return 0.5 * tf.math.log(np.pi * self.scale**2.0 / 2.0) + 0.5

  def _mean(self):
    return self.scale * np.sqrt(2.0) / np.sqrt(np.pi)

  def _quantile(self, p):
    return np.sqrt(2.0) * self.scale * special_math.erfinv(p)

  def _mode(self):
    return tf.zeros(self.batch_shape_tensor())

  def _variance(self):
    return self.scale ** 2.0 * (1.0 - 2.0 / np.pi)

@kullback_leibler.RegisterKL(HalfNormal, HalfNormal)
def _kl_half_normal_half_normal(a, b, name=None):
  """Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`.

  Args:
    a: Instance of a `HalfNormal` distribution object.
    b: Instance of a `HalfNormal` distribution object.
    name: (optional) Name to use for created operations.
      default is "kl_half_normal_half_normal".

  Returns:
    Batchwise KL(a || b)
  """
  with tf.name_scope(name or "kl_half_normal_half_normal"):
    # Consistent with
    # http://www.mast.queensu.ca/~communications/Papers/gil-msc11.pdf, page 119
    return (tf.math.log(b.scale) - tf.math.log(a.scale) +
            (a.scale**2 - b.scale**2) / (2 * b.scale**2))


# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""PositiveSemidefiniteKernel base."""

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

import abc
import contextlib
import functools
import operator
import six
import tensorflow as tf

from tensorflow_probability.python.positive_semidefinite_kernels.internal import util

__all__ = [
    'PositiveSemidefiniteKernel',
]

@six.add_metaclass(abc.ABCMeta)
class PositiveSemidefiniteKernel(object):
  """Abstract base class for positive semi-definite kernel functions.

  #### Background

  For any set `S`, a real- (or complex-valued) function `k` on the Cartesian
  product `S x S` is called positive semi-definite if we have

  ```none
  sum_i sum_j (c[i]*) c[j] k(x[i], x[j]) >= 0
  ```

  for any finite collections `{x[1], ..., x[N]}` in S and `{c[1], ..., c[N]}` in
  the reals (or the complex plane). '*' denotes the complex conjugate, in the
  complex case.

  Some examples:
    - `S` is R, and `k(s, t) = (s - a) (t - b)`, where a, b are in R. This
      corresponds to a linear kernel.
    - `S` is R^+ U {0}, and `k(s, t) = min(s, t)`. This corresponds to a kernel
      for a Wiener process.
    - `S` is the set of strings over an alphabet `A = {c1, ... cC}`, and
      `k(s, t)` is defined via some similarity metric over strings.

  We model positive semi-definite functions (*kernels*, in common machine
  learning parlance) as classes implementing 2 primary public methods:
  `matrix` and `apply`.

  `matrix` computes the value of the kernel *pairwise* on two (batches of)
  collections of inputs. When the collections are both the same set of inputs,
  the result is the Gram (or Gramian) matrix
  (https://en.wikipedia.org/wiki/Gramian_matrix).

  `apply` computes the value of the kernel function at a pair of (batches of)
  input locations. It is the more low-level operation and must be implemented in
  each concrete base class of PositiveSemidefiniteKernel.

  #### Kernel Parameter Shape Semantics

  PositiveSemidefiniteKernel implementations support batching of kernel
  parameters. This allows, for example, creating a single kernel object which
  acts like a collection of kernels with different parameters. This might be
  useful for, e.g., for exploring multiple random initializations in parallel
  during a kernel parameter optimization procedure.

  The interaction between kernel parameter shapes and input shapes (see below)
  is somewhat subtle. The semantics are designed to make the most common use
  cases easy, while not ruling out more intricate control. The overarching
  principle is that kernel parameter batch shapes must be broadcastable with
  input batch shapes (see below). Examples are provided in the method-level
  documentation.

  #### Input Shape Semantics

  `apply` and `matrix` each support a notion of batching inputs; see the
  method-level documentation for full details; here we describe the overall
  semantics of input shapes. Inputs to PositiveSemidefiniteKernel methods
  partition into 3 pieces:

  ```none
  [b1, ..., bB, e, f1, ..., fF]
  '----------'  |  '---------'
       |        |       '-- Feature dimensions
       |        '-- Example dimension (`matrix`-only)
       '-- Batch dimensions
  ```

  - Feature dimensions correspond to the space over which the kernel is defined;
    in typical applications inputs are vectors and this part of the shape is
    rank-1. For example, if our kernel is defined over R^2 x R^2, each input is
    a 2-D vector (a rank-1 tensor of shape `[2,]`) so that
    `F = 1, [f1, ..., fF] = [2]`. If we defined a kernel over DxD matrices, its
    domain would be R^(DxD) x R^(DxD), we would have `F = 2` and
    `[f1, ..., fF] = [D, D]`. Feature shapes of inputs should be the same, but
    no exception will be raised unless they are broadcast-incompatible.
  - Example dimensions are relevant only for `matrix` calls. Given inputs `x`
    and `y` with feature dimensions [f1, ..., fF] and example dimensions `e1`
    and `e2`, a to `matrix` will yield an `e1 x e2` matrix. If batch dimensions
    are present, it will return a batch of `e1 x e2` matrices.
  - Batch dimensions are supported for inputs to `apply` or `matrix`; the only
    requirement is that batch dimensions of inputs `x` and `y` be broadcastable
    with each other and with the kernel's parameter batch shapes (see above).
  """

  def __init__(self, feature_ndims, dtype=None, name=None):
    """Construct a PositiveSemidefiniteKernel (subclass) instance.

    Args:
      feature_ndims: Python `integer` indicating the number of dims (the rank)
        of the feature space this kernel acts on.
      dtype: `DType` on which this kernel operates.
      name: Python `str` name prefixed to Ops created by this class. Default:
        subclass name.

    Raises:
      ValueError: if `feature_ndims` is not an integer greater than 0
    Inputs to PositiveSemidefiniteKernel methods partition into 3 pieces:

    ```none
    [b1, ..., bB, e, f1, ..., fF]
    '----------'  |  '---------'
         |        |       '-- Feature dimensions
         |        '-- Example dimension (`matrix`-only)
         '-- Batch dimensions
    ```

    The `feature_ndims` argument declares how many of the right-most shape
    dimensions belong to the feature dimensions. This enables us to predict
    which shape dimensions will be 'reduced' away during kernel computation.
    """
    if not (isinstance(feature_ndims, int) and feature_ndims > 0):
      raise ValueError(
          '`feature_ndims` must be a Python `integer` greater than zero. ' +
          'Got: {}'.format(feature_ndims))
    self._feature_ndims = feature_ndims
    self._dtype = dtype
    if not name or name[-1] != '/':  # `name` is not a name scope
      name = tf.compat.v1.name_scope(name or type(self).__name__).name
    self._name = name

  @property
  def feature_ndims(self):
    """The number of feature dimensions.

    Kernel functions generally act on pairs of inputs from some space like

    ```none
    R^(d1 x ... x  dD)
    ```

    or, in words: rank-`D` real-valued tensors of shape `[d1, ..., dD]`. Inputs
    can be vectors in some `R^N`, but are not restricted to be. Indeed, one
    might consider kernels over matrices, tensors, or even more general spaces,
    like strings or graphs.

    Returns:
      The number of feature dimensions (feature rank) of this kernel.
    """
    return self._feature_ndims

  @property
  def dtype(self):
    """DType over which the kernel operates."""
    return self._dtype

  @property
  def name(self):
    """Name prepended to all ops created by this class."""
    return self._name

  @property
  def batch_shape(self):
    """The batch_shape property of a PositiveSemidefiniteKernel.

    This property describes the fully broadcast shape of all kernel parameters.
    For example, consider an ExponentiatedQuadratic kernel, which is
    parameterized by an amplitude and length_scale:

    ```none
    exp_quad(x, x') := amplitude * exp(||x - x'||**2 / length_scale**2)
    ```

    The batch_shape of such a kernel is derived from broadcasting the shapes of
    `amplitude` and `length_scale`. E.g., if their shapes were

    ```python
    amplitude.shape = [2, 1, 1]
    length_scale.shape = [1, 4, 3]
    ```

    then `exp_quad`'s batch_shape would be `[2, 4, 3]`.

    Note that this property defers to the private _batch_shape method, which
    concrete implementation sub-classes are obliged to provide.

    Returns:
        `TensorShape` instance describing the fully broadcast shape of all
        kernel parameters.
    """
    return self._batch_shape()

  def batch_shape_tensor(self):
    """The batch_shape property of a PositiveSemidefiniteKernel as a `Tensor`.

    Returns:
        `Tensor` which evaluates to a vector of integers which are the
        fully-broadcast shapes of the kernel parameters.
    """
    with tf.compat.v1.name_scope(self._name):
      if self.batch_shape.is_fully_defined():
        return tf.convert_to_tensor(
            value=self.batch_shape.as_list(),
            dtype=tf.int32,
            name='batch_shape')
      with tf.compat.v1.name_scope('batch_shape_tensor'):
        return self._batch_shape_tensor()

  @contextlib.contextmanager
  def _name_scope(self, name=None, values=None):
    """Helper function to standardize op scope."""
    with tf.compat.v1.name_scope(self.name):
      values = [] if values is None else values
      with tf.compat.v1.name_scope(name, values=values) as scope:
        yield scope

  def apply(self, x1, x2):
    """Apply the kernel function to a pair of (batches of) inputs.

    Args:
      x1: `Tensor` input to the first positional parameter of the kernel, of
        shape `[b1, ..., bB, f1, ..., fF]`, where `B` may be zero (ie, no
        batching) and `F` (number of feature dimensions) must equal the kernel's
        `feature_ndims` property. Batch shape must broadcast with the batch
        shape of `x2` and with the kernel's parameters.
      x2: `Tensor` input to the second positional parameter of the kernel,
        shape `[c1, ..., cC, f1, ..., fF]`, where `C` may be zero (ie, no
        batching) and `F` (number of feature dimensions) must equal the kernel's
        `feature_ndims` property. Batch shape must broadcast with the batch
        shape of `x1` and with the kernel's parameters.

    Returns:
      `Tensor` containing the (batch of) results of applying the kernel function
      to inputs `x1` and `x2`. If the kernel parameters' batch shape is
      `[k1, ..., kK]` then the shape of the `Tensor` resulting from this method
      call is `broadcast([b1, ..., bB], [c1, ..., cC], [k1, ..., kK])`.

    Given an index set `S`, a kernel function is mathematically defined as a
    real- or complex-valued function on `S` satisfying the
    positive semi-definiteness constraint:

    ```none
    sum_i sum_j (c[i]*) c[j] k(x[i], x[j]) >= 0
    ```

    for any finite collections `{x[1], ..., x[N]}` in `S` and
    `{c[1], ..., c[N]}` in the reals (or the complex plane). '*' is the complex
    conjugate, in the complex case.

    This method most closely resembles the function described in the
    mathematical definition of a kernel. Given a PositiveSemidefiniteKernel `k`
    with scalar parameters and inputs `x` and `y` in `S`, `apply(x, y)` yields a
    single scalar value. Given the same kernel and, say, batched inputs of shape
    `[b1, ..., bB, f1, ..., fF]`, it will yield a batch of scalars of shape
    `[b1, ..., bB]`.

    #### Examples

    ```python
    import tensorflow_probability as tfp

    # Suppose `SomeKernel` acts on vectors (rank-1 tensors)
    scalar_kernel = tfp.positive_semidefinite_kernels.SomeKernel(param=.5)
    scalar_kernel.batch_shape
    # ==> []

    # `x` and `y` are batches of five 3-D vectors:
    x = np.ones([5, 3], np.float32)
    y = np.ones([5, 3], np.float32)
    scalar_kernel.apply(x, y).shape
    # ==> [5]
    ```

    The above output is the result of vectorized computation of the five values

    ```none
    [k(x[0], y[0]), k(x[1], y[1]), ..., k(x[4], y[4])]
    ```

    Now we can consider a kernel with batched parameters:

    ```python
    batch_kernel = tfp.positive_semidefinite_kernels.SomeKernel(param=[.2, .5])
    batch_kernel.batch_shape
    # ==> [2]
    batch_kernel.apply(x, y).shape
    # ==> Error! [2] and [5] can't broadcast.
    ```

    The parameter batch shape of `[2]` and the input batch shape of `[5]` can't
    be broadcast together. We can fix this by giving the parameter a shape of
    `[2, 1]` which will correctly broadcast with `[5]` to yield `[2, 5]`:

    ```python
    batch_kernel = tfp.positive_semidefinite_kernels.SomeKernel(
        param=[[.2], [.5]])
    batch_kernel.batch_shape
    # ==> [2, 1]
    batch_kernel.apply(x, y).shape
    # ==> [2, 5]
    ```

    """
    with self._name_scope(self._name, values=[x1, x2]):
      x1 = tf.convert_to_tensor(value=x1, name='x1')
      x2 = tf.convert_to_tensor(value=x2, name='x2')
      return self._apply(x1, x2)

  def _apply(self, x1, x2, param_expansion_ndims=0):
    """Apply the kernel function to a pair of (batches of) inputs.

    Args:
      x1: `Tensor` input to the first positional parameter of the kernel, of
        shape `[b1, ..., bB, f1, ..., fF]`, where `B` may be zero (no batching)
        and `F` (number of feature dimensions) must equal the kernel's
        `feature_ndims` property. Batch shape must broadcast with the batch
        shape of `x2` and with the kernel's parameters *after* parameter
        expansion (see `param_expansion_ndims` argument).
      x2: `Tensor` input to the second positional parameter of the kernel,
        shape `[c1, ..., cC, f1, ..., fF]`, where `C` may be zero (no batching)
        and `F` (number of feature dimensions) must equal the kernel's
        `feature_ndims` property. Batch shape must broadcast with the batch
        shape of `x1` and with the kernel's parameters *after* parameter
        expansion (see `param_expansion_ndims` argument).
      param_expansion_ndims: Python `integer` enabling reshaping of kernel
        parameters by concatenating a list of 1's to the param shapes. This
        allows the caller to control how the parameters broadcast across the
        inputs.

    Returns:
      `Tensor` containing the (batch of) results of applying the kernel function
      to inputs `x1` and `x2`. If the kernel parameters' batch shape *after*
      parameter expansion (ie, concatenating `param_expansion_ndims` 1's onto
      the parameters' shapes) is `[k1, ..., kK, 1, ..., 1]` then the shape of
      the `Tensor` resulting from this method call is
      `broadcast([b1, ..., bB], [c1, ..., cC], [k1, ..., kK, 1, ..., 1])`.
    """
    raise NotImplementedError(
        'Subclasses must provide `_apply` implementation.')

  def matrix(self, x1, x2):
    """Construct (batched) matrices from (batches of) collections of inputs.

    Args:
      x1: `Tensor` input to the first positional parameter of the kernel, of
        shape `[b1, ..., bB, e1, f1, ..., fF]`, where `B` may be zero (ie, no
        batching), e1 is an integer greater than zero, and `F` (number of
        feature dimensions) must equal the kernel's `feature_ndims` property.
        Batch shape must broadcast with the batch shape of `x2` and with the
        kernel's parameters *after* parameter expansion (see
        `param_expansion_ndims` argument).
      x2: `Tensor` input to the second positional parameter of the kernel,
        shape `[c1, ..., cC, e2, f1, ..., fF]`, where `C` may be zero (ie, no
        batching), e2 is an integer greater than zero,  and `F` (number of
        feature dimensions) must equal the kernel's `feature_ndims` property.
        Batch shape must broadcast with the batch shape of `x1` and with the
        kernel's parameters *after* parameter expansion (see
        `param_expansion_ndims` argument).

    Returns:
      `Tensor containing (batch of) matrices of kernel applications to pairs
      from inputs `x1` and `x2`. If the kernel parameters' batch shape is
      `[k1, ..., kK]`, then the shape of the resulting `Tensor` is
      `broadcast([b1, ..., bB], [c1, ..., cC], [k1, ..., kK]) + [e1, e2]`.

    Given inputs `x1` and `x2` of shapes

    ```none
    [b1, ..., bB, e1, f1, ..., fF]
    ```

    and

    ```none
    [c1, ..., cC, e2, f1, ..., fF]
    ```

    This method computes the batch of `e1 x e2` matrices resulting from applying
    the kernel function to all pairs of inputs from `x1` and `x2`. The shape
    of the batch of matrices is the result of broadcasting the batch shapes of
    `x1`, `x2`, and the kernel parameters (see examples below). As such, it's
    required that these shapes all be broadcast compatible. However, the kernel
    parameter batch shapes need not broadcast against the 'example shapes' (`e1`
    and `e2` above).

    When the two inputs are the (batches of) identical collections, the
    resulting matrix is the so-called Gram (or Gramian) matrix
    (https://en.wikipedia.org/wiki/Gramian_matrix).

    N.B., this method can only be used to compute the pairwise application of
    the kernel function on rank-1 collections. E.g., it *does* support inputs of
    shape `[e1, f]` and `[e2, f]`, yielding a matrix of shape `[e1, e2]`. It
    *does not* support inputs of shape `[e1, e2, f]` and `[e3, e4, f]`, yielding
    a `Tensor` of shape `[e1, e2, e3, e4]`. To do this, one should instead
    reshape the inputs and pass them to `apply`, e.g.:

    ```python
    k = tfpk.SomeKernel()
    t1 = tf.placeholder([4, 4, 3], tf.float32)
    t2 = tf.placeholder([5, 5, 3], tf.float32)
    k.apply(
        tf.reshape(t1, [4, 4, 1, 1, 3]),
        tf.reshape(t2, [1, 1, 5, 5, 3])).shape
    # ==> [4, 4, 5, 5, 3]
    ```

    `matrix` is a special case of the above, where there is only one example
    dimension; indeed, its implementation looks almost exactly like the above
    (reshaped inputs passed to the private version of `_apply`).

    #### Examples

    First, consider a kernel with a single scalar parameter.

    ```python
    import tensorflow_probability as tfp

    scalar_kernel = tfp.positive_semidefinite_kernels.SomeKernel(param=.5)
    scalar_kernel.batch_shape
    # ==> []

    # Our inputs are two lists of 3-D vectors
    x = np.ones([5, 3], np.float32)
    y = np.ones([4, 3], np.float32)
    scalar_kernel.matrix(x, y).shape
    # ==> [5, 4]
    ```

    The result comes from applying the kernel to the entries in `x` and `y`
    pairwise, across all pairs:

      ```none
      | k(x[0], y[0])    k(x[0], y[1])  ...  k(x[0], y[3]) |
      | k(x[1], y[0])    k(x[1], y[1])  ...  k(x[1], y[3]) |
      |      ...              ...                 ...      |
      | k(x[4], y[0])    k(x[4], y[1])  ...  k(x[4], y[3]) |
      ```

    Now consider a kernel with batched parameters with the same inputs

    ```python
    batch_kernel = tfp.positive_semidefinite_kernels.SomeKernel(param=[1., .5])
    batch_kernel.batch_shape
    # ==> [2]

    batch_kernel.matrix(x, y).shape
    # ==> [2, 5, 4]
    ```

    This results in a batch of 2 matrices, one computed from the kernel with
    `param = 1.` and the other with `param = .5`.

    We also support batching of the inputs. First, let's look at that with
    the scalar kernel again.

    ```python
    # Batch of 10 lists of 5 vectors of dimension 3
    x = np.ones([10, 5, 3], np.float32)

    # Batch of 10 lists of 4 vectors of dimension 3
    y = np.ones([10, 4, 3], np.float32)

    scalar_kernel.matrix(x, y).shape
    # ==> [10, 5, 4]
    ```

    The result is a batch of 10 matrices built from the batch of 10 lists of
    input vectors. These batch shapes have to be broadcastable. The following
    will *not* work:

    ```python
    x = np.ones([10, 5, 3], np.float32)
    y = np.ones([20, 4, 3], np.float32)
    scalar_kernel.matrix(x, y).shape
    # ==> Error! [10] and [20] can't broadcast.
    ```

    Now let's consider batches of inputs in conjunction with batches of kernel
    parameters. We require that the input batch shapes be broadcastable with
    the kernel parameter batch shapes, otherwise we get an error:

    ```python
    x = np.ones([10, 5, 3], np.float32)
    y = np.ones([10, 4, 3], np.float32)

    batch_kernel = tfp.positive_semidefinite_kernels.SomeKernel(params=[1., .5])
    batch_kernel.batch_shape
    # ==> [2]
    batch_kernel.matrix(x, y).shape
    # ==> Error! [2] and [10] can't broadcast.
    ```

    The fix is to make the kernel parameter shape broadcastable with `[10]` (or
    reshape the inputs to be broadcastable!):

    ```python
    x = np.ones([10, 5, 3], np.float32)
    y = np.ones([10, 4, 3], np.float32)

    batch_kernel = tfp.positive_semidefinite_kernels.SomeKernel(
        params=[[1.], [.5]])
    batch_kernel.batch_shape
    # ==> [2, 1]
    batch_kernel.matrix(x, y).shape
    # ==> [2, 10, 5, 4]

    # Or, make the inputs broadcastable:
    x = np.ones([10, 1, 5, 3], np.float32)
    y = np.ones([10, 1, 4, 3], np.float32)

    batch_kernel = tfp.positive_semidefinite_kernels.SomeKernel(
        params=[1., .5])
    batch_kernel.batch_shape
    # ==> [2]
    batch_kernel.matrix(x, y).shape
    # ==> [10, 2, 5, 4]

    ```

    Here, we have the result of applying the kernel, with 2 different
    parameters, to each of a batch of 10 pairs of input lists.

    """
    with self._name_scope(self._name, values=[x1, x2]):
      x1 = tf.convert_to_tensor(value=x1, name='x1')
      x2 = tf.convert_to_tensor(value=x2, name='x2')
      x1 = tf.expand_dims(x1, -(self.feature_ndims + 1))
      x2 = tf.expand_dims(x2, -(self.feature_ndims + 2))
      return self._apply(x1, x2, param_expansion_ndims=2)

  def _batch_shape(self):
    raise NotImplementedError('Subclasses must provide batch_shape property.')

  def _batch_shape_tensor(self):
    raise NotImplementedError(
        'Subclasses must provide batch_shape_tensor implementation')

  def __add__(self, k):
    if not isinstance(k, PositiveSemidefiniteKernel):
      raise ValueError(
          "Can't add non-kernel (of type '%s') to kernel" % type(k))
    return _SumKernel([self, k])

  def __iadd__(self, k):
    return self.__add__(k)

  def __mul__(self, k):
    if not isinstance(k, PositiveSemidefiniteKernel):
      raise ValueError(
          "Can't multiply by non-kernel (of type '%s') to kernel" % type(k))
    return _ProductKernel([self, k])

  def __imul__(self, k):
    return self.__mul__(k)

  def __str__(self):
    return ('tfp.positive_semidefinite_kernels.{type_name}('
            '"{self_name}"'
            '{maybe_batch_shape}'
            ', feature_ndims={feature_ndims}'
            ', dtype={dtype})'.format(
                type_name=type(self).__name__,
                self_name=self.name,
                maybe_batch_shape=(', batch_shape={}'.format(self.batch_shape)
                                   if self.batch_shape.ndims is not None
                                   else ''),
                feature_ndims=self.feature_ndims,
                dtype=None if self.dtype is None else self.dtype.name))

  def __repr__(self):
    return ('<tfp.positive_semidefinite_kernels.{type_name} '
            '\'{self_name}\''
            ' batch_shape={batch_shape}'
            ' feature_ndims={feature_ndims}'
            ' dtype={dtype}>'.format(
                type_name=type(self).__name__,
                self_name=self.name,
                batch_shape=self.batch_shape,
                feature_ndims=self.feature_ndims,
                dtype=None if self.dtype is None else self.dtype.name))

def _flatten_summand_list(kernels):
  """Flatten a list of kernels which may contain _SumKernel instances.

  Args:
    kernels: Python list of `PositiveSemidefiniteKernel` instances

  Returns:
    Python list containing the elements of kernels, with any _SumKernel
    instances replaced by their `kernels` property contents.
  """
  flattened = []
  for k in kernels:
    if isinstance(k, _SumKernel):
      flattened += k.kernels
    else:
      flattened.append(k)
  return flattened

def _flatten_multiplicand_list(kernels):
  """Flatten a list of kernels which may contain _ProductKernel instances.

  Args:
    kernels: Python list of `PositiveSemidefiniteKernel` instances

  Returns:
    Python list containing the elements of kernels, with any _ProductKernel
    instances replaced by their `kernels` property contents.
  """
  flattened = []
  for k in kernels:
    if isinstance(k, _ProductKernel):
      flattened += k.kernels
    else:
      flattened.append(k)
  return flattened

class _SumKernel(PositiveSemidefiniteKernel):
  """Kernel class representing summation over a list of kernels.

  Mathematically this class represents the pointwise sum of several kernels.
  Given two kernels, `k1` and `k2`, and `kp = _SumKernel([k1, k2])`, we have

    ```none
    kp.apply(x, y) = k1(x, y) + k2(x, y)
    ```

  for any `x`, `y` in the feature space (this presumes that the constituent
  kernels all act on the same feature space).

  That the sum is positive semi-definite follows simply from the definition of
  positive semi-definiteness of functions. If we have

    ```none
    sum_i sum_j (c[i]*) c[j] k1(x[i], x[j]) >= 0
    ```
  and

    ```none
    sum_i sum_j (c[i]*) c[j] k2(x[i], x[j]) >= 0
    ```

  for any finite collections `{x[1], ..., x[N]}` in S and `{c[1], ..., c[N]}` in
  the reals (or the complex plane), then we clearly also have the same for the
  sum of `k1` and `k2`.
  """

  def __init__(self, kernels, name=None):
    """Create a kernel which is the sum of `kernels`.

    The input list is 'flattened' in the sense that any entries which are also
    of type `_SumKernel` will have their list of kernels appended to this
    instance's list of kernels. This will reduce the stack depth when actually
    evaluating the sum over kernel applications.

    Args:
      kernels: Python `list` of `PositiveSemidefiniteKernel` instances.
      name: Python `str` name prefixed to Ops created by this class.
    Raises:
      ValueError: `kernels` is an empty list, or `kernels` don't all have the
      same `feature_ndims`.
    """
    if not kernels:
      raise ValueError("Can't create _SumKernel over empty list.")
    if len(set([k.feature_ndims for k in kernels])) > 1:
      raise ValueError(
          "Can't sum kernels with different feature_ndims. Got:\n%s" %
          str([k.feature_ndims for k in kernels]))
    self._kernels = _flatten_summand_list(kernels)
    if name is None:
      name = 'SumKernel'
    # We have ensured the list is non-empty and all feature_ndims are the same.
    super(_SumKernel, self).__init__(
        feature_ndims=kernels[0].feature_ndims,
        dtype=util.maybe_get_common_dtype(
            [None if k.dtype is None else k for k in kernels]),
        name=name)

  @property
  def kernels(self):
    """The list of kernels this _SumKernel sums over."""
    return self._kernels

  def _apply(self, x1, x2, param_expansion_ndims=0):
    return sum([k._apply(x1, x2, param_expansion_ndims) for k in self.kernels])  # pylint: disable=protected-access

  def _batch_shape(self):
    return functools.reduce(tf.broadcast_static_shape,
                            [k.batch_shape for k in self.kernels])

  def _batch_shape_tensor(self):
    return functools.reduce(tf.broadcast_dynamic_shape,
                            [k.batch_shape_tensor() for k in self.kernels])

class _ProductKernel(PositiveSemidefiniteKernel):
  """Kernel class representing the product over a list of kernels.

  Mathematically this class represents the pointwise product of several kernels.
  Given two kernels, `k1` and `k2`, and `kp = _ProductKernel([k1, k2])`, we have

    ```none
    kp.apply(x, y) = k1(x, y) * k2(x, y)
    ```

  for any x, y in the feature space (this presumes that the constituent kernels
  all act on the same feature space).

  The fact that this product is still positive semi-definite can be shown in a
  variety of ways, many deep and all fascinating, but follows readily from the
  [Schur product theorem](https://en.wikipedia.org/wiki/Schur_product_theorem),
  which states that the Hadamard (element-wise) product of two PSD matrices is
  also PSD.
  """

  def __init__(self, kernels, name=None):
    """Create a kernel which is the product of `kernels`.

    The input list is 'flattened' in the sense that any entries which are also
    of type `_ProductKernel` will have their list of kernels appended to this
    instance's list of kernels. This will reduce the stack depth when actually
    evaluating the product over kernel applications.

    Args:
      kernels: Python `list` of `PositiveSemidefiniteKernel` instances.
      name: Python `str` name prefixed to Ops created by this class.
    Raises:
      ValueError: `kernels` is an empty list, or `kernels` don't all have the
      same `feature_ndims`.
    """
    if not kernels:
      raise ValueError("Can't create _ProductKernel over empty list.")
    if len(set([k.feature_ndims for k in kernels])) > 1:
      raise ValueError(
          "Can't multiply kernels with different feature_ndims. Got:\n%s" %
          str([k.feature_ndims for k in kernels]))
    self._kernels = _flatten_multiplicand_list(kernels)
    if name is None:
      name = 'ProductKernel'
    # We have ensured the list is non-empty and all feature_ndims are the same.
    super(_ProductKernel, self).__init__(
        feature_ndims=kernels[0].feature_ndims,
        dtype=util.maybe_get_common_dtype(
            [None if k.dtype is None else k for k in kernels]),
        name=name)

  @property
  def kernels(self):
    """The list of kernels this _ProductKernel multiplies over."""
    return self._kernels

  def _apply(self, x1, x2, param_expansion_ndims=0):
    return functools.reduce(
        operator.mul,
        [k._apply(x1, x2, param_expansion_ndims) for k in self.kernels])  # pylint: disable=protected-access

  def _batch_shape(self):
    return functools.reduce(tf.broadcast_static_shape,
                            [k.batch_shape for k in self.kernels])

  def _batch_shape_tensor(self):
    return functools.reduce(tf.broadcast_dynamic_shape,
                            [k.batch_shape_tensor() for k in self.kernels])


# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Trains a Bayesian neural network to classify CIFAR-10 images.

The architecture can be either ResNet [1] or VGG [2].

To run with default arguments:

  ```
  bazel run tensorflow_probability/examples:cifar10_bnn
  ```

#### References

[1]: He, Kaiming, Xiangyu Zhang, Shaoqing Ren, and Jian Sun.
     "Deep residual learning for image recognition."
     _Proceedings of the IEEE_, 2016.
     https://arxiv.org/abs/1512.03385
[2]: Simonyan, Karen, and Andrew Zisserman.
     "Very deep convolutional networks for large-scale image recognition."
     arXiv preprint arXiv:1409.1556 (2014).
     https://arxiv.org/pdf/1409.1556.pdf
"""

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

import os
import warnings

# Dependency imports
from absl import flags
import matplotlib
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp

from tensorflow_probability.examples.models.bayesian_resnet import bayesian_resnet
from tensorflow_probability.examples.models.bayesian_vgg import bayesian_vgg

matplotlib.use("Agg")
warnings.simplefilter(action="ignore")
tfd = tfp.distributions

IMAGE_SHAPE = [32, 32, 3]

flags.DEFINE_float("learning_rate",
                   default=0.0001,
                   help="Initial learning rate.")
flags.DEFINE_integer("epochs",
                     default=700,
                     help="Number of epochs to train for.")
flags.DEFINE_integer("batch_size",
                     default=128,
                     help="Batch size.")
flags.DEFINE_string("data_dir",
                    default=os.path.join(os.getenv("TEST_TMPDIR", "/tmp"),
                                         "bayesian_neural_network/data"),
                    help="Directory where data is stored (if using real data).")
flags.DEFINE_string(
    "model_dir",
    default=os.path.join(os.getenv("TEST_TMPDIR", "/tmp"),
                         "bayesian_neural_network/"),
    help="Directory to put the model's fit.")
flags.DEFINE_integer("eval_freq",
                     default=400,
                     help="Frequency at which to validate the model.")
flags.DEFINE_integer("num_monte_carlo",
                     default=50,
                     help="Network draws to compute predictive probabilities.")
flags.DEFINE_string("architecture",
                    default="resnet",
                    help="Network architecture to use.")
flags.DEFINE_float(
    "kernel_posterior_scale_mean",
    default=-9.0,
    help="Initial kernel posterior mean of the scale (log var) for q(w)")
flags.DEFINE_float(
    "kernel_posterior_scale_constraint",
    default=0.2,
    help="Posterior kernel constraint for the scale (log var) of q(w).")
flags.DEFINE_integer("kl_annealing",
                     default=50,
                     help="Epochs to anneal the KL term (anneals from 0 to 1)")
flags.DEFINE_boolean("subtract_pixel_mean",
                     default=True,
                     help="Boolean for normalizing the images")
flags.DEFINE_bool("fake_data",
                  default=None,
                  help="If true, uses fake data. Defaults to real data.")

FLAGS = flags.FLAGS

def build_input_pipeline(x_train, x_test, y_train, y_test,
                         batch_size, valid_size):
  """Build an Iterator switching between train and heldout data."""

  x_train = x_train.astype("float32")
  x_test = x_test.astype("float32")

  x_train /= 255
  x_test /= 255

  y_train = y_train.flatten()
  y_test = y_test.flatten()

  if FLAGS.subtract_pixel_mean:
    x_train_mean = np.mean(x_train, axis=0)
    x_train -= x_train_mean
    x_test -= x_train_mean

  print("x_train shape:" + str(x_train.shape))
  print(str(x_train.shape[0]) + " train samples")
  print(str(x_test.shape[0]) + " test samples")

  # Build an iterator over training batches.
  training_dataset = tf.data.Dataset.from_tensor_slices(
      (x_train, np.int32(y_train)))
  training_batches = training_dataset.shuffle(
      50000, reshuffle_each_iteration=True).repeat().batch(batch_size)
  training_iterator = tf.compat.v1.data.make_one_shot_iterator(training_batches)

  # Build a iterator over the heldout set with batch_size=heldout_size,
  # i.e., return the entire heldout set as a constant.
  heldout_dataset = tf.data.Dataset.from_tensor_slices(
      (x_test, np.int32(y_test)))
  heldout_batches = heldout_dataset.repeat().batch(valid_size)
  heldout_iterator = tf.compat.v1.data.make_one_shot_iterator(heldout_batches)

  # Combine these into a feedable iterator that can switch between training
  # and validation inputs.
  handle = tf.compat.v1.placeholder(tf.string, shape=[])
  feedable_iterator = tf.compat.v1.data.Iterator.from_string_handle(
      handle, training_batches.output_types, training_batches.output_shapes)
  images, labels = feedable_iterator.get_next()

  return images, labels, handle, training_iterator, heldout_iterator

def build_fake_data():
  """Build fake CIFAR10-style data for unit testing."""
  num_examples = 10
  x_train = np.random.rand(num_examples, *IMAGE_SHAPE).astype(np.float32)
  y_train = np.random.permutation(np.arange(num_examples)).astype(np.int32)
  x_test = np.random.rand(num_examples, *IMAGE_SHAPE).astype(np.float32)
  y_test = np.random.permutation(np.arange(num_examples)).astype(np.int32)
  return (x_train, y_train), (x_test, y_test)

def main(argv):
  del argv  # unused
  if tf.io.gfile.exists(FLAGS.model_dir):
    tf.compat.v1.logging.warning(
        "Warning: deleting old log directory at {}".format(FLAGS.model_dir))
    tf.io.gfile.rmtree(FLAGS.model_dir)
  tf.io.gfile.makedirs(FLAGS.model_dir)

  if FLAGS.fake_data:
    (x_train, y_train), (x_test, y_test) = build_fake_data()
  else:
    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()

  (images, labels, handle,
   training_iterator,
   heldout_iterator) = build_input_pipeline(x_train, x_test, y_train, y_test,
                                            FLAGS.batch_size, 500)

  if FLAGS.architecture == "resnet":
    model_fn = bayesian_resnet
  else:
    model_fn = bayesian_vgg

  model = model_fn(
      IMAGE_SHAPE,
      num_classes=10,
      kernel_posterior_scale_mean=FLAGS.kernel_posterior_scale_mean,
      kernel_posterior_scale_constraint=FLAGS.kernel_posterior_scale_constraint)
  logits = model(images)
  labels_distribution = tfd.Categorical(logits=logits)

  # Perform KL annealing. The optimal number of annealing steps
  # depends on the dataset and architecture.
  t = tf.compat.v2.Variable(0.0)
  kl_regularizer = t / (FLAGS.kl_annealing * len(x_train) / FLAGS.batch_size)

  # Compute the -ELBO as the loss. The kl term is annealed from 0 to 1 over
  # the epochs specified by the kl_annealing flag.
  log_likelihood = labels_distribution.log_prob(labels)
  neg_log_likelihood = -tf.reduce_mean(input_tensor=log_likelihood)
  kl = sum(model.losses) / len(x_train) * tf.minimum(1.0, kl_regularizer)
  loss = neg_log_likelihood + kl

  # Build metrics for evaluation. Predictions are formed from a single forward
  # pass of the probabilistic layers. They are cheap but noisy
  # predictions.
  predictions = tf.argmax(input=logits, axis=1)
  with tf.compat.v1.name_scope("train"):
    train_accuracy, train_accuracy_update_op = tf.compat.v1.metrics.accuracy(
        labels=labels, predictions=predictions)
    opt = tf.compat.v1.train.AdamOptimizer(FLAGS.learning_rate)
    train_op = opt.minimize(loss)
    update_step_op = tf.compat.v1.assign(t, t + 1)

  with tf.compat.v1.name_scope("valid"):
    valid_accuracy, valid_accuracy_update_op = tf.compat.v1.metrics.accuracy(
        labels=labels, predictions=predictions)

  init_op = tf.group(tf.compat.v1.global_variables_initializer(),
                     tf.compat.v1.local_variables_initializer())

  stream_vars_valid = [
      v for v in tf.compat.v1.local_variables() if "valid/" in v.name
  ]
  reset_valid_op = tf.compat.v1.variables_initializer(stream_vars_valid)

  with tf.compat.v1.Session() as sess:
    sess.run(init_op)

    # Run the training loop
    train_handle = sess.run(training_iterator.string_handle())
    heldout_handle = sess.run(heldout_iterator.string_handle())
    training_steps = int(
        round(FLAGS.epochs * (len(x_train) / FLAGS.batch_size)))
    for step in range(training_steps):
      _ = sess.run([train_op,
                    train_accuracy_update_op,
                    update_step_op],
                   feed_dict={handle: train_handle})

      # Manually print the frequency
      if step % 100 == 0:
        loss_value, accuracy_value, kl_value = sess.run(
            [loss, train_accuracy, kl], feed_dict={handle: train_handle})
        print(
            "Step: {:>3d} Loss: {:.3f} Accuracy: {:.3f} KL: {:.3f}".format(
                step, loss_value, accuracy_value, kl_value))

      if (step + 1) % FLAGS.eval_freq == 0:
        # Compute log prob of heldout set by averaging draws from the model:
        # p(heldout | train) = int_model p(heldout|model) p(model|train)
        #                   ~= 1/n * sum_{i=1}^n p(heldout | model_i)
        # where model_i is a draw from the posterior
        # p(model|train).
        probs = np.asarray([sess.run((labels_distribution.probs),
                                     feed_dict={handle: heldout_handle})
                            for _ in range(FLAGS.num_monte_carlo)])
        mean_probs = np.mean(probs, axis=0)

        _, label_vals = sess.run(
            (images, labels), feed_dict={handle: heldout_handle})
        heldout_lp = np.mean(np.log(mean_probs[np.arange(mean_probs.shape[0]),
                                               label_vals.flatten()]))
        print(" ... Held-out nats: {:.3f}".format(heldout_lp))

        # Calculate validation accuracy
        for _ in range(20):
          sess.run(
              valid_accuracy_update_op, feed_dict={handle: heldout_handle})
        valid_value = sess.run(
            valid_accuracy, feed_dict={handle: heldout_handle})

        print(
            " ... Validation Accuracy: {:.3f}".format(valid_value))

        sess.run(reset_valid_op)

if __name__ == "__main__":
  tf.compat.v1.app.run()