# Copyright 2022 DeepMind Technologies Limited
#
# 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.

"""RNN model."""

from typing import Callable, List, Union, Optional

import haiku as hk
import jax.numpy as jnp


class RNNModel(hk.RNNCore):
  """RNN model."""

  def __init__(self,
               layers: List[Union[hk.Module, Callable[[jnp.ndarray],
                                                      jnp.ndarray]]],
               name: Optional[str] = 'RNN'):
    super().__init__(name=name)
    self._layers = layers

  def __call__(self, inputs, prev_state):
    x = inputs
    curr_state = [None] * len(prev_state)
    for k, layer in enumerate(self._layers):
      if isinstance(layer, hk.RNNCore):
        x, curr_state[k] = layer(x, prev_state[k])
      else:
        x = layer(x)
    return x, tuple(curr_state)

  def initial_state(self, batch_size: Optional[int]):
    layerwise_init_state = []
    for layer in self._layers:
      if isinstance(layer, hk.RNNCore):
        layerwise_init_state.append(layer.initial_state(batch_size))
      else:
        layerwise_init_state.append(None)
    return tuple(layerwise_init_state)
