# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Distribution abstract base class."""

import abc
import collections.abc
import contextlib
import functools
import operator
import typing

from typing import Any, Generic, Iterable, Mapping, Sequence, Tuple, TypeVar, Union

import chex
from distrax._src.utils import jittable
import jax
import jax.numpy as jnp
import numpy as np
from tensorflow_probability.substrates import jax as tfp


tfd = tfp.distributions

Array = chex.Array
PRNGKey = chex.PRNGKey
IntLike = Union[int, np.int16, np.int32, np.int64]
# Generic type.
T = TypeVar('T')
# Generic nested type.
NestedT = Union[T, Iterable['NestedT'], Mapping[Any, 'NestedT']]  # pylint: disable=invalid-name
# Nested types.
EventT = TypeVar('EventT', bound=NestedT[Array])
ShapeT = TypeVar('ShapeT', bound=NestedT[Tuple[int, ...]])
DTypeT = TypeVar('DTypeT', bound=NestedT[jnp.dtype])


class Distribution(
    jittable.Jittable, Generic[EventT, ShapeT, DTypeT], metaclass=abc.ABCMeta):
  """Jittable abstract base class for all Distrax distributions."""

  @abc.abstractmethod
  def _sample_n(self, key: PRNGKey, n: int) -> EventT:
    """Returns `n` samples."""

  def _sample_n_and_log_prob(
      self,
      key: PRNGKey,
      n: int,
  ) -> Tuple[EventT, Array]:
    """Returns `n` samples and their log probs.

    By default, it just calls `log_prob` on the generated samples. However, for
    many distributions it's more efficient to compute the log prob of samples
    than of arbitrary events (for example, there's no need to check that a
    sample is within the distribution's domain). If that's the case, a subclass
    may override this method with a more efficient implementation.

    Args:
      key: PRNG key.
      n: Number of samples to generate.

    Returns:
      A tuple of `n` samples and their log probs.
    """
    samples = self._sample_n(key, n)
    log_prob = self.log_prob(samples)
    return samples, log_prob

  @abc.abstractmethod
  def log_prob(self, value: EventT) -> Array:
    """Calculates the log probability of an event.

    Args:
      value: An event.

    Returns:
      The log probability log P(value).
    """

  def prob(self, value: EventT) -> Array:
    """Calculates the probability of an event.

    Args:
      value: An event.

    Returns:
      The probability P(value).
    """
    return jnp.exp(self.log_prob(value))

  @property
  @abc.abstractmethod
  def event_shape(self) -> ShapeT:
    """Shape of event of distribution samples."""

  @property
  def batch_shape(self) -> Tuple[int, ...]:
    """Shape of batch of distribution samples."""
    sample_spec = jax.eval_shape(
        self.sample, seed=jax.random.PRNGKey(0), sample_shape=())

    if not self.event_shape:
      batch_shapes = jax.tree_util.tree_map(lambda x: x.shape, sample_spec)
    else:
      batch_shapes = jax.tree_util.tree_map(
          lambda s, e: s.shape[:s.ndim - len(e)], sample_spec, self.event_shape)

    # Get flat batch shapes.
    batch_shapes = jax.tree_util.tree_structure(sample_spec).flatten_up_to(
        batch_shapes)
    if not batch_shapes:
      return ()

    # Ensure batch shapes are consistent.
    batch_shape = batch_shapes[0]
    for i in range(1, len(batch_shapes)):
      np.testing.assert_equal(batch_shape, batch_shapes[i])
    return batch_shape

  @property
  def name(self) -> str:
    """Distribution name."""
    return type(self).__name__

  @property
  def dtype(self) -> DTypeT:
    """The data type of the samples generated by the distribution."""
    sample_spec = jax.eval_shape(
        self.sample, seed=jax.random.PRNGKey(0), sample_shape=())
    return jax.tree_util.tree_map(lambda x: x.dtype, sample_spec)

  def sample(self,
             *,
             seed: Union[IntLike, PRNGKey],
             sample_shape: Union[IntLike, Sequence[IntLike]] = ()) -> EventT:
    """Samples an event.

    Args:
      seed: PRNG key or integer seed.
      sample_shape: Additional leading dimensions for sample.

    Returns:
      A sample of shape `sample_shape + self.batch_shape + self.event_shape`.
    """
    rng, sample_shape = convert_seed_and_sample_shape(seed, sample_shape)
    num_samples = functools.reduce(operator.mul, sample_shape, 1)  # product

    samples = self._sample_n(rng, num_samples)
    return jax.tree_util.tree_map(
        lambda t: t.reshape(sample_shape + t.shape[1:]), samples)

  def sample_and_log_prob(
      self,
      *,
      seed: Union[IntLike, PRNGKey],
      sample_shape: Union[IntLike, Sequence[IntLike]] = ()
  ) -> Tuple[EventT, Array]:
    """Returns a sample and associated log probability. See `sample`."""
    rng, sample_shape = convert_seed_and_sample_shape(seed, sample_shape)
    num_samples = functools.reduce(operator.mul, sample_shape, 1)  # product

    samples, log_prob = self._sample_n_and_log_prob(rng, num_samples)
    samples, log_prob = jax.tree_util.tree_map(
        lambda t: t.reshape(sample_shape + t.shape[1:]), (samples, log_prob))
    return samples, log_prob

  def kl_divergence(self, other_dist, **kwargs) -> Array:
    """Calculates the KL divergence to another distribution.

    Args:
      other_dist: A compatible Distax or TFP Distribution.
      **kwargs: Additional kwargs.

    Returns:
      The KL divergence `KL(self || other_dist)`.
    """
    return tfd.kullback_leibler.kl_divergence(self, other_dist, **kwargs)

  def entropy(self) -> Array:
    """Calculates the Shannon entropy (in nats)."""
    raise NotImplementedError(
        f'Distribution `{self.name}` does not implement `entropy`.')

  def log_cdf(self, value: EventT) -> Array:
    """Evaluates the log cumulative distribution function at `value`.

    Args:
      value: An event.

    Returns:
      The log CDF evaluated at value, i.e. log P[X <= value].
    """
    raise NotImplementedError(
        f'Distribution `{self.name}` does not implement `log_cdf`.')

  def cdf(self, value: EventT) -> Array:
    """Evaluates the cumulative distribution function at `value`.

    Args:
      value: An event.

    Returns:
      The CDF evaluated at value, i.e. P[X <= value].
    """
    return jnp.exp(self.log_cdf(value))

  def survival_function(self, value: EventT) -> Array:
    """Evaluates the survival function at `value`.

    Note that by default we use a numerically not necessarily stable definition
    of the survival function in terms of the CDF.
    More stable definitions should be implemented in subclasses for
    distributions for which they exist.

    Args:
      value: An event.

    Returns:
      The survival function evaluated at `value`, i.e. P[X > value]
    """
    if not self.event_shape:
      # Defined for univariate distributions only.
      return 1. - self.cdf(value)
    else:
      raise NotImplementedError('`survival_function` is not defined for '
                                f'distribution `{self.name}`.')

  def log_survival_function(self, value: EventT) -> Array:
    """Evaluates the log of the survival function at `value`.

    Note that by default we use a numerically not necessarily stable definition
    of the log of the survival function in terms of the CDF.
    More stable definitions should be implemented in subclasses for
    distributions for which they exist.

    Args:
      value: An event.

    Returns:
      The log of the survival function evaluated at `value`, i.e.
      log P[X > value]
    """
    if not self.event_shape:
      # Defined for univariate distributions only.
      return jnp.log1p(-self.cdf(value))
    else:
      raise NotImplementedError('`log_survival_function` is not defined for '
                                f'distribution `{self.name}`.')

  def mean(self) -> EventT:
    """Calculates the mean."""
    raise NotImplementedError(
        f'Distribution `{self.name}` does not implement `mean`.')

  def median(self) -> EventT:
    """Calculates the median."""
    raise NotImplementedError(
        f'Distribution `{self.name}` does not implement `median`.')

  def variance(self) -> EventT:
    """Calculates the variance."""
    raise NotImplementedError(
        f'Distribution `{self.name}` does not implement `variance`.')

  def stddev(self) -> EventT:
    """Calculates the standard deviation."""
    return jnp.sqrt(self.variance())

  def mode(self) -> EventT:
    """Calculates the mode."""
    raise NotImplementedError(
        f'Distribution `{self.name}` does not implement `mode`.')

  def cross_entropy(self, other_dist, **kwargs) -> Array:
    """Calculates the cross entropy to another distribution.

    Args:
      other_dist: A compatible Distax or TFP Distribution.
      **kwargs: Additional kwargs.

    Returns:
      The cross entropy `H(self || other_dist)`.
    """
    return self.kl_divergence(other_dist, **kwargs) + self.entropy()

  @contextlib.contextmanager
  def _name_and_control_scope(self, *unused_a, **unused_k):
    yield

  def __getitem__(self, index) -> 'Distribution':
    """Returns a matching distribution obtained by indexing the batch shape.

    Args:
      index: An object, typically int or slice (or a tuple thereof), used for
        indexing the distribution.
    """
    raise NotImplementedError(f'Indexing not implemented for `{self.name}`.')


def convert_seed_and_sample_shape(
    seed: Union[IntLike, PRNGKey],
    sample_shape: Union[IntLike, Sequence[IntLike]]
) -> Tuple[PRNGKey, Tuple[int, ...]]:
  """Shared functionality to ensure that seeds and shapes are the right type."""

  if not isinstance(sample_shape, collections.abc.Sequence):
    sample_shape = (sample_shape,)
  sample_shape = tuple(map(int, sample_shape))

  if isinstance(seed, (int, np.signedinteger)):
    rng = jax.random.PRNGKey(seed)
  else:  # key is of type PRNGKey
    rng = seed

  return rng, sample_shape  # type: ignore[bad-return-type]


def to_batch_shape_index(
    batch_shape: Tuple[int, ...],
    index,
) -> Tuple[jnp.ndarray, ...]:
  """Utility function that transforms the index to respect the batch shape.

  When indexing a distribution we only want to index based on the batch shape.
  For example, a Categorical with logits shaped (2, 3, 4) has batch shape of
  (2, 3) and number of categoricals 4. Indexing this distribution creates a new
  distribution with indexed logits. If the index is [0], the new distribution's
  logits will be shaped (3, 4). But if the index is [..., -1] the new logits
  should be shaped (2, 4), but applying the index operation on logits directly
  will result in shape (2, 3). This function fixes such indices such that they
  are only applied on the batch shape.

  Args:
    batch_shape: Distribution's batch_shape.
    index: An object, typically int or slice (or a tuple thereof), used for
      indexing the distribution.

  Returns:
    A new index that is only applied on the batch shape.
  """
  try:
    new_index = [x[index] for x in np.indices(batch_shape)]
    return tuple(new_index)
  except IndexError as e:
    raise IndexError(f'Batch shape `{batch_shape}` not compatible with index '
                     f'`{index}`.') from e


DistributionLike = Union[Distribution, tfd.Distribution]
DistributionT = typing.TypeVar('DistributionT', bound=Distribution)
