# Copyright (c) 2021 Horizon Robotics. 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.

from enum import Enum
import functools
import numpy as np
from typing import Callable

import torch
import torch.nn as nn
import torch.distributions as td

import alf
from alf.algorithms.config import TrainerConfig
from alf.algorithms.off_policy_algorithm import OffPolicyAlgorithm
from alf.algorithms.sac_algorithm import _set_target_entropy
from alf.data_structures import LossInfo, namedtuple, TimeStep
from alf.data_structures import AlgStep, StepType
from alf.nest import nest
import alf.nest.utils as nest_utils
from alf.networks import ActorDistributionNetwork, CriticNetwork
from alf.networks.preprocessors import EmbeddingPreprocessor
from alf.tensor_specs import TensorSpec, BoundedTensorSpec
from alf.utils import common, dist_utils, losses, math_ops, tensor_utils
from alf.utils.conditional_ops import conditional_update
from alf.utils.summary_utils import safe_mean_hist_summary

Tau = namedtuple(
    "Tau",
    [
        "a",  # The current action value
        "v",  # The current first derivative of action (not used by action repetition)
        "u"  # The current second derivative of action (not used by action repetition)
    ],
    default_value=())

TaacState = namedtuple("TaacState", ["tau", "repeats"], default_value=())

TaacCriticInfo = namedtuple(
    "TaacCriticInfo", ["critics", "target_critic", "value_loss"],
    default_value=())

TaacActorInfo = namedtuple(
    "TaacActorInfo",
    ["actor_loss", "b1_a_entropy", "beta_entropy", "adv", "value_loss"],
    default_value=())

TaacInfo = namedtuple(
    "TaacInfo", [
        "reward", "step_type", "tau", "prev_tau", "discount",
        "action_distribution", "rollout_b", "b", "actor", "critic", "alpha",
        "repeats"
    ],
    default_value=())

TaacLossInfo = namedtuple('TaacLossInfo', ('actor', 'critic', 'alpha'))

Distributions = namedtuple("Distributions", ["beta_dist", "b1_a_dist"])

ActPredOutput = namedtuple(
    "ActPredOutput", ["dists", "b", "actor_a", "taus", "q_values2"],
    default_value=())

Mode = Enum('AlgorithmMode', ('predict', 'rollout', 'train'))

def _discounted_return(rewards, values, is_lasts, discounts):
    """Computes discounted return for the first T-1 steps.

    Same with ``tf_agents.utils.value_ops``, this function returns accumulated
    discounted reward for steps that are StepType.LAST.

    Args:
        rewards (Tensor): shape is ``[T,B]`` (or ``[T]``) representing rewards.
        values (Tensor): shape is ``[T,B]`` (or ``[T]``) representing values.
        is_lasts (Tensor): shape is ``[T,B]`` (or ``[T]``) representing last steps.
        discounts (Tensor): shape is ``[T,B]`` (or ``[T]``) representing discounts.

    Returns:
        Tensor: A tensor with shape ``[T-1,B]`` (or ``[T-1]``) representing the
        discounted returns.
    """
    assert values.shape[0] >= 2, ("The sequence length needs to be "
                                  "at least 2. Got {s}".format(
                                      s=values.shape[0]))

    is_lasts = is_lasts.to(dtype=torch.float32)
    is_lasts = common.expand_dims_as(is_lasts, values)
    discounts = common.expand_dims_as(discounts, values)

    rets = torch.zeros_like(values)
    rets[-1] = values[-1]
    acc_values = rets.clone()

    with torch.no_grad():
        for t in reversed(range(rewards.shape[0] - 1)):
            rets[t] = acc_values[t + 1] * discounts[t + 1] + rewards[t + 1]
            acc_values[t] = is_lasts[t] * values[t] + (
                1 - is_lasts[t]) * rets[t]

    rets = rets[:-1]
    return rets.detach()

@alf.configurable
class TAACTDLoss(nn.Module):
    r"""This TD loss implements the compare-through multi-step Q operator
    :math:`\mathcal{T}^{\pi^{\text{ta}}}` proposed in the TAAC paper. For a sampled
    trajectory, it compares the beta action :math:`\tilde{b}_n` sampled from the
    current policy with the historical rollout beta action :math:`b_n` step by step,
    and uses the minimum :math:`n` that has :math:`\tilde{b}_n\lor b_n=1` as the
    target step for boostrapping.
    """

    def __init__(self,
                 gamma=0.99,
                 td_error_loss_fn=losses.element_wise_squared_loss,
                 debug_summaries=False,
                 name="TAACTDLoss"):
        """
        Args:
            gamma (float|list[float]): A discount factor for future rewards. For
                multi-dim reward, this can also be a list of discounts, each
                discount applies to a reward dim.
            td_errors_loss_fn (Callable): A function for computing the TD errors
                loss. This function takes as input the target and the estimated
                Q values and returns the loss for each element of the batch.
            debug_summaries (bool): True if debug summaries should be created.
            name (str): The name of this loss.
        """
        super().__init__()
        self._name = name
        self._gamma = torch.tensor(gamma)
        self._debug_summaries = debug_summaries
        self._td_error_loss_fn = td_error_loss_fn

    @property
    def gamma(self):
        """Return the :math:`\gamma` value for discounting future rewards.

        Returns:
            Tensor: a rank-0 or rank-1 (multi-dim reward) floating tensor.
        """
        return self._gamma.clone()

    def forward(self, info, value, target_value):
        r"""Calculate the TD loss. The first dimension of all the tensors is the
        time dimension and the second dimesion is the batch dimension.

        Args:
            info (TaacInfo): TaacInfo collected from train_step().
            value (torch.Tensor): the tensor for the value at each time
                step. The loss is between this and the calculated return.
            target_value (torch.Tensor): the tensor for the value at each time
                step. This is used to calculate return.

        Returns:
            LossInfo: TD loss with the ``extra`` field same as the loss.
        """
        train_b = info.b
        if info.reward.ndim == 3:
            # [T, B, D] or [T, B, 1]
            discounts = info.discount.unsqueeze(-1) * self._gamma
        else:
            # [T, B]
            discounts = info.discount * self._gamma

        rollout_b = info.rollout_b
        # td return till the first action switching
        b = (rollout_b | train_b).to(torch.bool)
        # b at step 0 doesn't affect the bootstrapping of any step
        b[0, :] = False

        # combine is_last and b
        is_lasts = (info.step_type == StepType.LAST)
        is_lasts |= b

        returns = _discounted_return(
            rewards=info.reward,
            values=target_value,
            is_lasts=is_lasts,
            discounts=discounts)

        value = value[:-1]
        loss = self._td_error_loss_fn(returns.detach(), value)
        loss = tensor_utils.tensor_extend_zero(loss)

        if loss.ndim == 3:
            # Multidimensional reward. Average over the critic loss for all
            # dimensions.
            loss = loss.mean(dim=-1)

        if self._debug_summaries and alf.summary.should_record_summaries():
            mask = info.step_type[:-1] != StepType.LAST
            with alf.summary.scope(self._name):

                def _summarize(v, r, td, suffix):
                    alf.summary.scalar(
                        "explained_variance_of_return_by_value" + suffix,
                        tensor_utils.explained_variance(v, r, mask))
                    safe_mean_hist_summary('values' + suffix, v, mask)
                    safe_mean_hist_summary('returns' + suffix, r, mask)
                    safe_mean_hist_summary("td_error" + suffix, td, mask)

                td = returns - value
                if value.ndim == 2:
                    _summarize(value, returns, td, '')
                else:
                    for i in range(value.shape[-1]):
                        suffix = '/' + str(i)
                        _summarize(value[..., i], returns[..., i], td[..., i],
                                   suffix)

        return LossInfo(loss=loss, extra=loss)

@alf.configurable
class TaacAlgorithmBase(OffPolicyAlgorithm):
    r"""Temporally abstract actor-critic algorithm.

    In a nutsell, for inference TAAC adds a second stage that chooses between a
    candidate trajectory :math:`\hat{\tau}` output by an SAC actor and the previous
    trajectory :math:`\tau^-`. For policy evaluation, TAAC uses a compare-through Q
    operator for TD backup by re-using state-action sequences that have shared
    actions between rollout and training. For policy improvement, the
    new actor gradient is approximated by multiplying a scaling factor to the
    :math:`\frac{\partial Q}{\partial a}` term in the original SAC’s actor
    gradient, where the scaling factor is the optimal probability of choosing
    the :math:`\hat{\tau}` in the second stage.

    Different sub-algorithms implement different forms of the 'trajectory' concept,
    for example, it can be a constant function representing the same action, or
    a quadratic function.
    """

    def __init__(self,
                 observation_spec,
                 action_spec: BoundedTensorSpec,
                 reward_spec=TensorSpec(()),
                 actor_network_cls=ActorDistributionNetwork,
                 critic_network_cls=CriticNetwork,
                 reward_weights=None,
                 num_critic_replicas=2,
                 epsilon_greedy=None,
                 env=None,
                 config: TrainerConfig = None,
                 target_update_tau=0.05,
                 target_update_period=1,
                 critic_loss_ctor=None,
                 actor_optimizer=None,
                 critic_optimizer=None,
                 alpha_optimizer=None,
                 debug_summaries=False,
                 randomize_first_state_tau=False,
                 b1_advantage_clipping=None,
                 max_repeat_steps=None,
                 target_entropy=None,
                 name="TaacAlgorithmBase"):
        r"""
        Args:
            observation_spec (nested TensorSpec): representing the observations.
            action_spec (BoundedTensorSpec): representing the continuous action.
            reward_spec (TensorSpec): a rank-1 or rank-0 tensor spec representing
                the reward(s).
            actor_network_cls (Callable): is used to construct the actor network.
                The constructed actor network will be called to sample continuous
                actions.
            critic_network_cls (Callable): is used to construct critic network.
                for estimating ``Q(s,a)`` given that the action is continuous.
            reward_weights (None|list[float]): this is only used when the reward is
                multidimensional. In that case, the weighted sum of the q values
                is used for training the actor if reward_weights is not None.
                Otherwise, the sum of the q values is used.
            num_critic_replicas (int): number of critics to be used. Default is 2.
            epsilon_greedy (float): a floating value in [0,1], representing the
                chance of action sampling instead of taking argmax. This can
                help prevent a dead loop in some deterministic environment like
                Breakout. Only used for evaluation. If None, its value is taken
                from ``alf.get_config_value(TrainerConfig.epsilon_greedy)``
            env (Environment): The environment to interact with. ``env`` is a
                batched environment, which means that it runs multiple simulations
                simultateously. ``env` only needs to be provided to the root
                algorithm.
            config (TrainerConfig): config for training. It only needs to be
                provided to the algorithm which performs ``train_iter()`` by
                itself.
            target_update_tau (float): Factor for soft update of the target
                networks.
            target_update_period (int): Period for soft update of the target
                networks.
            critic_loss_ctor (None|OneStepTDLoss|MultiStepLoss): a critic loss
                constructor. If ``None``, a default ``TAACTDLoss`` will be used.
            actor_optimizer (torch.optim.optimizer): The optimizer for actor.
            critic_optimizer (torch.optim.optimizer): The optimizer for critic.
            alpha_optimizer (torch.optim.optimizer): The optimizer for alpha.
            debug_summaries (bool): True if debug summaries should be created.
            randomize_first_state_tau (bool): whether to randomize ``state.tau``
                at the beginning of an episode during rollout and training.
                Potentially this helps exploration. This was turned off in
                Yu et al. 2021.
            b1_advantage_clipping (None|tuple[float]): option for clipping the
                advantage (defined as :math:`Q(s,\hat{\tau}) - Q(s,\tau^-)`) when
                computing :math:`\beta_1`. If not ``None``, it should be a pair
                of numbers ``[min_adv, max_adv]``.
            max_repeat_steps (None|int): the max number of steps to repeat during
                rollout and evaluation. This value doesn't impact the switch
                during training.
            target_entropy (Callable|tuple[Callable]|None): If a
                callable function, then it will be called on the action spec to
                calculate a target entropy. If ``None``, a default entropy will
                be calculated. To set separate entropy targets for the two
                stage policies, this argument can be a tuple of two callables.
            name (str): name of the algorithm
        """
        assert len(
            nest.flatten(action_spec)) == 1 and action_spec.is_continuous, (
                "Only support a single continuous action!")

        self._num_critic_replicas = num_critic_replicas
        if epsilon_greedy is None:
            epsilon_greedy = alf.get_config_value(
                'TrainerConfig.epsilon_greedy')
        self._epsilon_greedy = epsilon_greedy

        self._tau_spec, critic_networks, actor_network = self._make_networks(
            observation_spec, action_spec, reward_spec, actor_network_cls,
            critic_network_cls)

        log_alpha = (nn.Parameter(torch.zeros(())),
                     nn.Parameter(torch.zeros(())))

        train_state_spec = TaacState(
            tau=self._tau_spec,
            repeats=TensorSpec(shape=(), dtype=torch.int64))
        super().__init__(
            observation_spec,
            action_spec,
            reward_spec=reward_spec,
            train_state_spec=train_state_spec,
            reward_weights=reward_weights,
            env=env,
            config=config,
            debug_summaries=debug_summaries,
            name=name)

        if actor_optimizer is not None:
            self.add_optimizer(actor_optimizer, [actor_network])
        if critic_optimizer is not None:
            self.add_optimizer(critic_optimizer, [critic_networks])
        if alpha_optimizer is not None:
            self.add_optimizer(alpha_optimizer, list(log_alpha))

        self._log_alpha = log_alpha
        self._log_alpha_paralist = nn.ParameterList(list(log_alpha))
        self._actor_network = actor_network
        self._critic_networks = critic_networks
        self._target_critic_networks = self._critic_networks.copy(
            name='target_critic_networks')

        if critic_loss_ctor is None:
            critic_loss_ctor = TAACTDLoss
        critic_loss_ctor = functools.partial(
            critic_loss_ctor, debug_summaries=debug_summaries)
        # Have different names to separate their summary curves
        self._critic_losses = []
        for i in range(num_critic_replicas):
            self._critic_losses.append(
                critic_loss_ctor(name="critic_loss%d" % (i + 1)))
        self._gamma = self._critic_losses[0]._gamma

        self._b_spec = BoundedTensorSpec(shape=(), dtype='int64', maximum=1)

        # separate target entropies for discrete and continuous actions
        if not isinstance(target_entropy, tuple):
            target_entropy = (target_entropy, ) * 2
        self._target_entropy = nest.map_structure(
            lambda spec, t: _set_target_entropy(self.name, t, [spec]),
            (self._b_spec, action_spec), target_entropy)

        self._b1_advantage_clipping = b1_advantage_clipping
        self._max_repeat_steps = max_repeat_steps
        self._randomize_first_state_tau = randomize_first_state_tau

        # Create as a buffer so that training from a checkpoint will have
        # the correct flag.
        self.register_buffer("_training_started",
                             torch.zeros((), dtype=torch.bool))

        self._update_target = common.get_target_updater(
            models=[self._critic_networks],
            target_models=[self._target_critic_networks],
            tau=target_update_tau,
            period=target_update_period)

    def _make_networks(self, observation_spec, action_spec, reward_spec,
                       actor_network_cls, critic_network_cls):
        raise NotImplementedError()

    def _update_tau(self, tau):
        """Update the current trajectory ``tau`` by moving one step ahead."""
        raise NotImplementedError()

    def _action2tau(self, a, tau):
        """Compute a new trajectory given a new action and the current trajectory
        ``tau``."""
        raise NotImplementedError()

    def _make_networks_impl(self, observation_spec, action_spec, reward_spec,
                            actor_network_cls, critic_network_cls, tau_mask):
        def _make_parallel(net):
            return net.make_parallel(
                self._num_critic_replicas * reward_spec.numel)

        tau_spec = nest.map_structure(lambda m: action_spec if m else (),
                                      tau_mask)
        tau_embedding = nest.map_structure(
            lambda _: torch.nn.Sequential(
                alf.layers.FC(action_spec.numel, observation_spec.numel)),
            tau_spec)

        actor_network = actor_network_cls(
            input_tensor_spec=(observation_spec, tau_spec),
            input_preprocessors=(alf.layers.Detach(), tau_embedding),
            preprocessing_combiner=nest_utils.NestConcat(),
            action_spec=action_spec)
        critic_network = critic_network_cls(
            input_tensor_spec=(observation_spec, tau_spec),
            action_preprocessing_combiner=nest_utils.NestConcat())
        critic_networks = _make_parallel(critic_network)

        return tau_spec, critic_networks, actor_network

    def _randomize_first_tau(self, time_step_or_exp, state, rollout_tau=None):
        """Randomize the first ``tau`` (by default always 0) for better
        exploration if ``b=0`` is selected.

        If a ``rollout_tau`` is already provided, then directly use it (during
        training).
        """

        def _randomize(tau):
            return alf.nest.map_structure(
                lambda spec: spec.sample(outer_dims=tau.a.shape[:1]),
                self._tau_spec)

        if rollout_tau is None:
            kwargs = dict(tau=state.tau)
            randomize = _randomize
        else:
            kwargs = dict(r_tau=rollout_tau)
            randomize = lambda r_tau: r_tau

        tau = conditional_update(
            target=state.tau,
            cond=(time_step_or_exp.step_type == StepType.FIRST),
            func=randomize,
            **kwargs)
        return state._replace(tau=tau)

    def _predict_action(self,
                        time_step,
                        state,
                        epsilon_greedy=None,
                        mode=Mode.rollout):

        observation = time_step.observation

        ap_out = self._compute_beta_and_tau(observation, state, epsilon_greedy,
                                            mode)

        if not common.is_eval() and not self._training_started:
            b = self._b_spec.sample(observation.shape[:1])
            b1_a = self._action_spec.sample(observation.shape[:1])
            b1_tau = self._action2tau(b1_a, state.tau)
            ap_out = ap_out._replace(b=b, taus=(ap_out.taus[0], b1_tau))

        b0_tau, b1_tau = ap_out.taus
        new_state = state._replace(tau=b0_tau)

        def _b1_action(b1_tau, new_state):
            new_state = new_state._replace(
                repeats=torch.zeros_like(new_state.repeats), tau=b1_tau)
            return new_state

        condition = ap_out.b.to(torch.bool)
        if self._max_repeat_steps is not None and mode != Mode.train:
            condition |= (state.repeats >= self._max_repeat_steps)

        # selectively update with new actions
        new_state = conditional_update(
            target=new_state,
            cond=condition,
            func=_b1_action,
            b1_tau=b1_tau,
            new_state=new_state)

        new_state = new_state._replace(repeats=new_state.repeats + 1)
        return ap_out, new_state

    def _compute_critics(self,
                         critic_net,
                         observation,
                         tau,
                         replica_min=True,
                         apply_reward_weights=True):
        """Compute Q(s,a)"""
        observation = (observation, tau)
        critics, _ = critic_net(observation)  # [B, replicas * reward_dim]
        critics = critics.reshape(  # [B, replicas, reward_dim]
            -1, self._num_critic_replicas, *self._reward_spec.shape)
        if replica_min:
            if self.has_multidim_reward():
                sign = self.reward_weights.sign()
                critics = (critics * sign).min(dim=1)[0] * sign
            else:
                critics = critics.min(dim=1)[0]

        if apply_reward_weights and self.has_multidim_reward():
            critics = critics * self.reward_weights
            critics = critics.sum(dim=-1)
        return critics

    def _alpha_train_step(self, beta_entropy, action_entropy):
        alpha_loss = (self._log_alpha[1] *
                      (action_entropy - self._target_entropy[1]).detach())
        alpha_loss += (self._log_alpha[0] *
                       (beta_entropy - self._target_entropy[0]).detach())
        return alpha_loss

    def _calc_critic_loss(self, info: TaacInfo):
        critic_info = info.critic
        critic_losses = []
        for i, l in enumerate(self._critic_losses):
            kwargs = dict(
                info=info,
                value=critic_info.critics[:, :, i, ...],
                target_value=critic_info.target_critic)
            critic_losses.append(l(**kwargs).loss)

        critic_loss = math_ops.add_n(critic_losses)
        return LossInfo(
            loss=critic_loss,
            extra=critic_loss / float(self._num_critic_replicas))

    def _trainable_attributes_to_ignore(self):
        return ['_target_critic_networks']

    def _build_beta_dist(self, q_values2):
        def _safe_categorical(logits, alpha):
            r"""A numerically stable implementation of categorical distribution
            :math:`exp(\frac{Q}{\alpha})`.
            """
            logits = logits / torch.clamp(alpha, min=1e-10)
            # logits are equivalent after subtracting a common number
            logits = logits - torch.max(logits, dim=-1, keepdim=True)[0]
            return td.Categorical(logits=logits)

        # compute beta dist *conditioned* on ``action``
        with torch.no_grad():
            beta_alpha = self._log_alpha[0].exp().detach()
            if self._b1_advantage_clipping is None:
                beta_dist = _safe_categorical(q_values2, beta_alpha)
            else:
                clip_min, clip_max = self._b1_advantage_clipping
                # The first dim [..., 0] is always 0
                q_values2 = q_values2 - q_values2[..., :1]
                q_values2[..., 1] = q_values2[..., 1].clamp(
                    min=clip_min, max=clip_max)
                beta_dist = _safe_categorical(q_values2, beta_alpha)

        return beta_dist

    def _compute_beta_and_tau(self, observation, state, epsilon_greedy, mode):
        # compute resampling action dist
        b1_a_dist, _ = self._actor_network((observation, state.tau))
        # resample a new attempting action
        if mode == Mode.predict:
            b1_a = dist_utils.epsilon_greedy_sample(b1_a_dist, epsilon_greedy)
        else:
            b1_a = dist_utils.rsample_action_distribution(b1_a_dist)

        b0_tau = self._update_tau(state.tau)
        # This should be a deterministic function converting b1_a to b1_tau
        b1_tau = self._action2tau(b1_a, state.tau)

        # compute Q(s, tau^-) and Q(s, \hat{tau})
        with torch.no_grad():
            q_0 = self._compute_critics(self._critic_networks, observation,
                                        b0_tau)
        q_1 = self._compute_critics(self._critic_networks, observation, b1_tau)

        q_values2 = torch.stack([q_0, q_1], dim=-1)
        beta_dist = self._build_beta_dist(q_values2)

        if mode == Mode.predict:
            b = dist_utils.epsilon_greedy_sample(beta_dist, epsilon_greedy)
        else:
            b = dist_utils.sample_action_distribution(beta_dist)

        dists = Distributions(beta_dist=beta_dist, b1_a_dist=b1_a_dist)
        return ActPredOutput(
            dists=dists,
            b=b,
            actor_a=b1_a,
            taus=(b0_tau, b1_tau),
            q_values2=q_values2)

    def _actor_train_step(self, a, b1_a_entropy, beta_dist, beta_entropy,
                          q_values2):
        alpha = self._log_alpha[1].exp().detach()
        q_a = beta_dist.probs[:, 1].detach() * q_values2[:, 1]

        dqda = nest_utils.grad(a, q_a.sum())

        def actor_loss_fn(dqda, action):
            loss = 0.5 * losses.element_wise_squared_loss(
                (dqda + action).detach(), action)
            return loss.sum(list(range(1, loss.ndim)))

        actor_loss = nest.map_structure(actor_loss_fn, dqda, a)
        actor_loss = math_ops.add_n(nest.flatten(actor_loss))
        actor_loss -= alpha * b1_a_entropy

        return LossInfo(
            loss=actor_loss,
            extra=TaacActorInfo(
                actor_loss=actor_loss,
                adv=q_values2[:, 1] - q_values2[:, 0],
                b1_a_entropy=b1_a_entropy,
                beta_entropy=beta_entropy))

    def _critic_train_step(self, inputs: TimeStep, rollout_tau, b0_tau, b1_tau,
                           beta_dist):

        with torch.no_grad():
            target_q_0 = self._compute_critics(
                self._target_critic_networks,
                inputs.observation,
                b0_tau,
                apply_reward_weights=False)
            target_q_1 = self._compute_critics(
                self._target_critic_networks,
                inputs.observation,
                b1_tau,
                apply_reward_weights=False)

            beta_probs = beta_dist.probs
            if self.has_multidim_reward():
                beta_probs = beta_probs.unsqueeze(1)

            target_critic = (beta_probs[..., 0] * target_q_0 +
                             beta_probs[..., 1] * target_q_1)

        critics = self._compute_critics(
            self._critic_networks,
            inputs.observation,
            rollout_tau,
            replica_min=False,
            apply_reward_weights=False)
        return TaacCriticInfo(critics=critics, target_critic=target_critic)

    def predict_step(self, inputs: TimeStep, state):
        ap_out, new_state = self._predict_action(
            inputs,
            state,
            epsilon_greedy=self._epsilon_greedy,
            mode=Mode.predict)
        return AlgStep(
            output=new_state.tau.a,
            state=new_state,
            info=TaacInfo(action_distribution=ap_out.dists, b=ap_out.b))

    def rollout_step(self, inputs: TimeStep, state):
        if self._randomize_first_state_tau:
            state = self._randomize_first_tau(inputs, state)
        ap_out, new_state = self._predict_action(
            inputs, state, mode=Mode.rollout)
        return AlgStep(
            output=new_state.tau.a,
            state=new_state,
            info=TaacInfo(
                action_distribution=ap_out.dists,
                prev_tau=state.tau,  # for getting randomized tau in training
                tau=new_state.tau,  # for critic training
                b=ap_out.b,
                repeats=state.repeats))

    def summarize_rollout(self, experience):
        repeats = experience.rollout_info.repeats.reshape(-1)
        if self._debug_summaries:
            with alf.summary.scope(self._name):
                # if rollout batch size=1, hist won't show
                alf.summary.histogram("rollout_repeats/value", repeats)
                alf.summary.scalar("rollout_repeats/mean",
                                   torch.mean(repeats.to(torch.float32)))

    def train_step(self, inputs: TimeStep, state, rollout_info: TaacInfo):
        self._training_started.fill_(True)

        if self._randomize_first_state_tau:
            # Because we called ``self._randomize_first_tau`` in rollout_step()
            # while the random ``tau`` was not stored in the replay buffer, the
            # first step's ``tau`` here is not accurate. So we need to use the
            # rollout ``tau``.
            state = self._randomize_first_tau(inputs, state,
                                              rollout_info.prev_tau)

        ap_out, new_state = self._predict_action(
            inputs, state=state, mode=Mode.train)

        beta_dist = ap_out.dists.beta_dist
        b1_a_dist = ap_out.dists.b1_a_dist
        b0_tau, b1_tau = ap_out.taus
        q_values2 = ap_out.q_values2

        b1_a_entropy = -dist_utils.compute_log_probability(
            b1_a_dist, ap_out.actor_a)
        beta_entropy = beta_dist.entropy()

        actor_loss = self._actor_train_step(ap_out.actor_a, b1_a_entropy,
                                            beta_dist, beta_entropy, q_values2)
        critic_info = self._critic_train_step(inputs, rollout_info.tau, b0_tau,
                                              b1_tau, beta_dist)
        alpha_loss = self._alpha_train_step(beta_entropy, b1_a_entropy)

        info = TaacInfo(
            reward=inputs.reward,
            step_type=inputs.step_type,
            discount=inputs.discount,
            rollout_b=rollout_info.b,
            action_distribution=ap_out.dists,
            actor=actor_loss,
            critic=critic_info,
            b=ap_out.b,
            alpha=alpha_loss,
            repeats=state.repeats)
        return AlgStep(output=new_state.tau.a, state=new_state, info=info)

    def after_update(self, root_inputs, info: TaacInfo):
        self._update_target()

    def calc_loss(self, info: TaacInfo):
        critic_loss = self._calc_critic_loss(info)
        alpha_loss = info.alpha
        actor_loss = info.actor
        if self._debug_summaries:
            with alf.summary.scope(self._name):
                alf.summary.scalar("alpha/beta", self._log_alpha[0].exp())
                alf.summary.scalar("alpha/action", self._log_alpha[1].exp())
                alf.summary.scalar("resample_advantage",
                                   torch.mean(actor_loss.extra.adv))
                p_beta0 = info.action_distribution[0].probs[..., 0]
                alf.summary.histogram("P_beta_0/value", p_beta0)
                alf.summary.scalar("P_beta_0/mean", p_beta0.mean())
                alf.summary.scalar("P_beta_0/std", p_beta0.std())
                repeats = info.repeats
                alf.summary.scalar("train_repeats/mean",
                                   torch.mean(repeats.to(torch.float32)))
                alf.summary.histogram("train_repeats/value",
                                      repeats.to(torch.float32))

        return LossInfo(
            loss=actor_loss.loss + alpha_loss + critic_loss.loss,
            extra=TaacLossInfo(
                actor=actor_loss.extra,
                critic=critic_loss.extra,
                alpha=alpha_loss))

@alf.configurable
class TaacAlgorithm(TaacAlgorithmBase):
    r"""Model temporal abstraction by action repetition. See

        "TAAC: Temporally Abstract Actor-Critic for Continuous Control",
        Yu et al., arXiv 2021.

    for algorithm details.
    """

    def __init__(self, name="TaacAlgorithm", *args, **kwargs):
        """See ``TaacAlgorithmBase`` for argument description.
        """
        super().__init__(*args, name=name, **kwargs)

    def _make_networks(self, *args):
        tau_mask = Tau(a=True, v=False, u=False)
        args = args + (tau_mask, )
        return self._make_networks_impl(*args)

    def _update_tau(self, tau):
        """Return a constant trajectory."""
        return tau

    def _action2tau(self, a, tau):
        """Return a constant trajectory."""
        return Tau(a=a)

@alf.configurable
class TaacLAlgorithm(TaacAlgorithmBase):
    r"""TaacL: Piecewise linear trajectory policy for continuous control.

    For a linear trajectory, let :math:`a` be the action and :math:`v` the
    first derivative. Its dynamics is:

    .. math::

        \begin{array}{ll}
            v_{t+1} &\leftarrow v_t\\
            a_{t+1} &\leftarrow v_{t+1} + a_t\\
        \end{array}

    TaacL's trajectory is piece-wise linear. Each time the policy decides whether
    to repeat the previous linear traj or generate a new one. Importantly,
    to generate a new one the policy doesn't directly generate the entire set of
    two parameters :math:`(a,v)` because this will result in bad exploration
    in the action space. Instead,

    .. math::

        \begin{array}{ll}
            a_{t+1} &\sim \pi\\
            v_{t+1} &\leftarrow a_{t+1} - a_t\\
        \end{array}

    For :math:`a\in[0,1]` and :math:`v\in[0,1]`, the actual dynamics is
    :math:`a_{t+1}\leftarrow \max(\min(a_t+2v_{t+1},1),-1)`.
    """

    def __init__(self,
                 name="TaacLAlgorithm",
                 inverse_mode=True,
                 *args,
                 **kwargs):
        """See ``TaacAlgorithmBase`` for other argument description.

        Args:
            inverse_mode (bool): this argument decides how the new traj is computed when
                ``b=1``. If it's False, then the new action is treated as the
                new first derivative ``v``; otherwise the new action is treated
                as the new action ``a``, and ``v`` is inversely inferred.
        """
        super().__init__(*args, name=name, **kwargs)

        assert (
            np.all(self._action_spec.minimum == -1)
            and np.all(self._action_spec.maximum == 1)
        ), ("Only support actions in [-1, 1]! Consider using env wrappers to "
            "scale your action space first.")

        self._inverse_mode = inverse_mode

    def _make_networks(self, *args):
        tau_mask = Tau(a=True, v=True, u=False)
        args = args + (tau_mask, )
        return self._make_networks_impl(*args)

    def _update_tau(self, tau):
        """Compute next action on a linear trajectory specified by a pair of
        ('action', 'action derivative').
        """
        a = torch.clamp(tau.a + 2. * tau.v, min=-1., max=1.)
        return tau._replace(a=a)

    def _action2tau(self, a, tau):
        if self._inverse_mode:
            # Given a new action at the next step and the current traj ``tau``,
            # infer the new traj's first derivative.
            v = (a - tau.a) / 2.
            return Tau(a=a, v=v)
        else:
            # Given a new first derivative and the current traj ``tau``, compute
            # the new traj's action
            tau = Tau(a=tau.a, v=a)
            return self._update_tau(tau)

@alf.configurable
class TaacQAlgorithm(TaacLAlgorithm):
    r"""TaacQ: Piecewise quadratic trajectory policy for continuous control.

    For a quadratic trajectory, let :math:`a` be the action, :math:`u` be the
    second derivative, and :math:`v` be the first derivative. Its dynamics is:

    .. math::

        \begin{array}{ll}
            u_{t+1} &\leftarrow u_t\\
            v_{t+1} &\leftarrow u_{t+1} + v_t\\
            a_{t+1} &\leftarrow v_{t+1} + a_t\\
        \end{array}

    TaacQ's trajectory is piece-wise quadratic. Each time the policy decides whether
    to repeat the previous quadratic traj or generate a new one. Importantly,
    to generate a new one the policy doesn't directly generate the entire set of
    three parameters :math:`(a,v,u)` because this will result in bad exploration
    in the action space. Instead,

    .. math::

        \begin{array}{ll}
            a_{t+1} &\sim \pi\\
            v_{t+1} &\leftarrow a_{t+1} - a_t\\
            u_{t+1} &\leftarrow v_{t+1}\\
        \end{array}

    where the last two steps assume resetting :math:`v_t` to zero.

    For :math:`a\in[0,1]`, :math:`v\in[0,1]`, and :math:`u\in[0,1]`, the actual
    dynamics is :math:`v_{t+1}\leftarrow \max(\min(v_t+2u_{t+1},1),-1)` and
    :math:`a_{t+1}\leftarrow \max(\min(a_t+2v_{t+1},1),-1)`.
    """

    def __init__(self,
                 name="TaacQAlgorithm",
                 inverse_mode=True,
                 *args,
                 **kwargs):
        """See ``TaacAlgorithmBase`` for other argument description.

        Args:
            inverse_mode (bool): this argument decides how the new traj is computed
                when ``b=1``. If it's False, then the new action is treated as the
                new second derivative ``u``; otherwise the new action is treated
                as the new action ``a``, and ``u`` is inversely inferred. In either
                case, the current ``v`` is first set to 0, and then a new ``v`` is
                computed.
        """
        super().__init__(*args, name=name, inverse_mode=inverse_mode, **kwargs)

    def _make_networks(self, *args):
        tau_mask = Tau(a=True, v=True, u=True)
        args = args + (tau_mask, )
        return self._make_networks_impl(*args)

    def _update_tau(self, tau):
        """Compute next action on a quadratic trajectory specified by a triplet
        of ('action', 'action derivative', and 'action second derivative').
        """
        v = torch.clamp(tau.v + tau.u * 2., min=-1., max=1.)
        a = torch.clamp(tau.a + v * 2., min=-1., max=1.)
        return Tau(a=a, v=v, u=tau.u)

    def _action2tau(self, a, tau):
        if self._inverse_mode:
            # Given a new action at the next step and the current traj ``tau``,
            # infer the new traj, assuming resetting ``tau.v`` to 0 first.
            v = (a - tau.a) / 2.
            u = v / 2.
            return Tau(a=a, v=v, u=u)
        else:
            # Given a new second derivative at the next step and the current traj
            # ``tau``, compute the new traj, assuming resetting ``tau.v`` to 0 first.
            tau = Tau(a=tau.a, v=0, u=a)
            return self._update_tau(tau)


# The batman package: fast computation of exoplanet transit light curves
# Copyright (C) 2015 Laura Kreidberg
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import numpy as np
from . import _nonlinear_ld
from . import _quadratic_ld
from . import _uniform_ld
from . import _logarithmic_ld
from . import _exponential_ld
from . import _power2_ld
from . import _custom_ld
from . import _rsky
from . import _eclipse
from math import pi
import multiprocessing
from . import openmp

__all__ = ['TransitModel', 'TransitParams']

def wrapper(func, *args, **kwargs):
    def wrapped():
        return func(*args, **kwargs)
    return wrapped

class TransitModel(object):
	"""
	Class for generating model transit light curves.

	:param params: A :attr:`TransitParams` object containing the physical parameters of the transit
	:type params: a `TransitParams` instance

	:param t: Array of times at which to calculate the model.
	:type t: ndarray

	:param max_err: Error tolerance (in parts per million) for the model.
	:type max_err: float, optional

	:param nthreads: Number of threads to use for parallelization.
	:type nthreads: int, optional

	:param fac: Scale factor for integration step size
	:type fac: float, optional

	:param transittype: Type of transit ("primary" or "secondary")
	:type transittype: string, optional

	:param supersample_factor:	Number of points subdividing exposure
	:type supersample_factor: integer, optional

	:param exp_time: Exposure time (in same units as `t`)
	:type exp_time: double, optional

	:Example:

	>>> m = batman.TransitModel(params, max_err = 0.5, nthreads=4)
	"""

	def __init__(self, params, t, max_err=1.0, nthreads = 1, fac = None, transittype = "primary", supersample_factor = 1, exp_time = 0.):
		#checking for invalid input
		if  (params.limb_dark == "uniform" and len(params.u) != 0) or (params.limb_dark == "linear" and len(params.u) != 1) or \
		    (params.limb_dark == "quadratic" and len(params.u) != 2) or (params.limb_dark == "logarithmic" and len(params.u) != 2) or \
		    (params.limb_dark == "exponential" and len(params.u) != 2) or (params.limb_dark == "squareroot" and len(params.u) != 2) or \
		    (params.limb_dark == "power2" and len(params.u) != 2) or \
		    (params.limb_dark == "nonlinear" and len(params.u) != 4):
			raise Exception("Incorrect number of coefficients for " +params.limb_dark + " limb darkening; u should have the form:\n \
			 u = [] for uniform LD\n \
			 u = [u1] for linear LD\n \
  			 u = [u1, u2] for quadratic, logarithmic, exponential, squareroot, and power2 LD\n \
			 u = [u1, u2, u3, u4] for nonlinear LD, or\n \
		         u = [u1, ..., un] for custom LD")
		if params.limb_dark not in ["uniform", "linear", "quadratic", "logarithmic", "exponential", "squareroot", "nonlinear", "power2", "custom"]:
			raise Exception("\""+params.limb_dark+"\""+" limb darkening not supported; allowed options are:\n \
				uniform, linear, quadratic, logarithmic, exponential, squareroot, nonlinear, power2, custom")
		if max_err < 0.001: raise Exception("The lowest allowed value for max_err is 0.001. For more accurate calculation, set the integration step size explicitly with the fac parameter.")
		if transittype not in ["primary", "secondary"]: raise Exception("Allowed transit types are \"primary\" and \"secondary\".")
		if (supersample_factor > 1 and exp_time <= 0.): raise Exception("Please enter a valid exposure time (exp_time must be greater than 0 to calculate super-sampled light curves).")
		if (not isinstance(t, np.ndarray)): raise Exception("Times t must be a numpy array (not a list).")

		#initializes model parameters
		self.t = t
		self.t0 = params.t0
		self.per = params.per
		self.rp = params.rp
		self.a = params.a
		self.inc = params.inc
		self.ecc = params.ecc
		self.w = params.w
		self.u = params.u
		self.limb_dark = params.limb_dark
		self.fp = params.fp
		self.t_secondary = params.t_secondary
		self.max_err = max_err
		self.supersample_factor = supersample_factor
		self.exp_time = exp_time
		self.inverse = False

		#handles the case of inverse transits (rp < 0)
		if self.rp < 0.:
			self.rp = -1.*self.rp
			params.rp = -1.*params.rp
			self.inverse = True

		if self.supersample_factor > 1:  # IJMC: now do it quicker, with no loops:
			t_offsets = np.linspace(-self.exp_time/2., self.exp_time/2., self.supersample_factor)
			self.t_supersample = (t_offsets + self.t.reshape(self.t.size, 1)).flatten()
		else: self.t_supersample = self.t

		if transittype == "primary": self.transittype = 1
		else:
			self.transittype = 2
			params.t0 = self.get_t_conjunction(params)

		if fac != None: self.fac = fac
		else: self.fac = self._get_fac()

		if nthreads==None or nthreads == 1: self.nthreads=1
		else:
			if nthreads <= multiprocessing.cpu_count()and nthreads >1 and openmp.detect(): self.nthreads = nthreads
			else:
				if nthreads > multiprocessing.cpu_count(): raise Exception("Maximum number of threads is "+'{0:d}'.format(multiprocessing.cpu_count()))
				elif nthreads <= 1: raise Exception("Number of threads must be between 2 and {0:d}".format(multiprocessing.cpu_count()))
				else: raise Exception("OpenMP not enabled: do not set the nthreads parameter")
		self.ds = _rsky._rsky(self.t_supersample, params.t0, params.per, params.a, params.inc*pi/180., params.ecc, params.w*pi/180., self.transittype, self.nthreads)

	def calc_err(self, plot = False):
		"""

		Calculate maximum error for transit light curve calculation.

		:param plot: If ``True``, plots the error in the light curve model as a function of separation of centers.
		:type plot: bool

		:return: Truncation error (parts per million)
		:rtype: float

		"""
		if self.limb_dark in ["logarithmic", "exponential", "nonlinear", "squareroot", "power2", "custom"]:
			ds = np.linspace(0., 1.1, 500)
			fac_lo = 5.0e-4
			if self.limb_dark == "nonlinear":
				f0 = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], fac_lo, self.nthreads)
				f = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], self.fac, self.nthreads)
			elif self.limb_dark == "squareroot":
				f0 = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[1], self.u[0], 0., 0., fac_lo, self.nthreads)
				f = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[1], self.u[0], 0., 0., self.fac, self.nthreads)
			elif self.limb_dark == "exponential":
				f0 = _exponential_ld._exponential_ld(ds, self.rp, self.u[0], self.u[1], fac_lo, self.nthreads)
				f = _exponential_ld._exponential_ld(ds, self.rp, self.u[0], self.u[1], self.fac, self.nthreads)
			elif self.limb_dark == "logarithmic":
				f0 = _logarithmic_ld._logarithmic_ld(ds, self.rp, self.u[0], self.u[1], fac_lo, self.nthreads)
				f = _logarithmic_ld._logarithmic_ld(ds, self.rp, self.u[0], self.u[1], self.fac, self.nthreads)
			elif self.limb_dark == "power2":
				f0 = _power2_ld._power2_ld(ds, self.rp, self.u[0], self.u[1], fac_lo, self.nthreads)
				f = _power2_ld._power2_ld(ds, self.rp, self.u[0], self.u[1], self.fac, self.nthreads)
			else:
				f0 = _custom_ld._custom_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], self.u[4], self.u[5], fac_lo, self.nthreads)
				f =  _custom_ld._custom_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], self.u[4], self.u[5], self.fac, self.nthreads)

			err = np.max(np.abs(f-f0))*1.0e6
			if plot == True:
				import matplotlib.pyplot as plt
				plt.plot(ds, 1.0e6*(f-f0), color='k')
				plt.xlabel("d (separation of centers)")
				plt.ylabel("Error (ppm)")
				plt.show()

			return err
		else: raise Exception("Function calc_err not valid for " + self.limb_dark + " limb darkening")

	def _get_fac(self):
		if self.limb_dark in ["logarithmic", "exponential", "squareroot", "nonlinear", "power2", "custom"]:
			nthreads = 1
			fac_lo, fac_hi = 5.0e-4, 1.
			ds = np.linspace(0., 1.+self.rp, 1000)
			if self.limb_dark == "nonlinear": f0 = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], fac_lo, nthreads)
			elif self.limb_dark == "squareroot": f0 = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[1], self.u[0], 0., 0., fac_lo, nthreads)
			elif self.limb_dark == "exponential": f0 = _exponential_ld._exponential_ld(ds, self.rp, self.u[0], self.u[1], fac_lo, nthreads)
			elif self.limb_dark == "logarithmic": f0 = _logarithmic_ld._logarithmic_ld(ds, self.rp, self.u[0], self.u[1], fac_lo, nthreads)
			elif self.limb_dark == "power2": f0 = _power2_ld._power2_ld(ds, self.rp, self.u[0], self.u[1], fac_lo, nthreads)
			else: f0 = _custom_ld._custom_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], self.u[4], self.u[5], fac_lo, nthreads)

			n = 0
			err = 0.
			while(err > self.max_err or err < 0.99*self.max_err):
				fac = (fac_lo + fac_hi)/2.
				if self.limb_dark == "nonlinear": f = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], fac, nthreads)
				elif self.limb_dark == "squareroot": f = _nonlinear_ld._nonlinear_ld(ds, self.rp, self.u[1], self.u[0], 0., 0., fac, nthreads)
				elif self.limb_dark == "exponential": f = _exponential_ld._exponential_ld(ds, self.rp, self.u[0], self.u[1], fac, nthreads)
				elif self.limb_dark == "logarithmic": f = _logarithmic_ld._logarithmic_ld(ds, self.rp, self.u[0], self.u[1], fac, nthreads)
				elif self.limb_dark == "power2": f = _power2_ld._power2_ld(ds, self.rp, self.u[0], self.u[1], fac, nthreads)
				else: f = _custom_ld._custom_ld(ds, self.rp, self.u[0], self.u[1], self.u[2], self.u[3], self.u[4], self.u[5], fac, nthreads)

				err = np.max(np.abs(f-f0))*1.0e6

				if err > self.max_err: fac_hi = fac
				else: fac_lo = fac
				n += 1
				if n > 1e3: raise Exception("Convergence failure in calculation of scale factor for integration step size")
			return fac
		else: return None

	def light_curve(self, params):
		"""
		Calculate a model light curve.

		:param params: Transit parameters
		:type params: A `TransitParams` instance

		:return: Relative flux
		:rtype: ndarray

		:Example:

		>>> flux = m.light_curve(params)
		"""
		#recalculates rsky and fac if necessary
		if params.t0 != self.t0 or params.per != self.per or params.a != self.a or params.inc != self.inc or params.ecc != self.ecc or params.w != self.w or params.t_secondary != self.t_secondary:
			if self.transittype == 2 and params.t_secondary != self.t_secondary:
				params.t0 = self.get_t_conjunction(params)
			self.ds= _rsky._rsky(self.t_supersample, params.t0, params.per, params.a, params.inc*pi/180., params.ecc, params.w*pi/180., self.transittype, self.nthreads)
		if params.limb_dark != self.limb_dark: self.fac = self._get_fac()

		#updates transit params
		self.t0 = params.t0
		self.per = params.per
		self.rp = params.rp
		self.a = params.a
		self.inc = params.inc
		self.ecc = params.ecc
		self.w = params.w
		self.u = params.u
		self.limb_dark = params.limb_dark
		self.fp = params.fp
		self.t_secondary = params.t_secondary
		self.inverse = False

		#handles the case of inverse transits (rp < 0)
		if self.rp < 0.:
			self.rp = -1.*self.rp
			params.rp = -1.*params.rp
			self.inverse = True

		if self.transittype == 1:
			if params.limb_dark != self.limb_dark: raise Exception("Need to reinitialize model in order to change limb darkening option")
			if self.limb_dark == "quadratic": lc = _quadratic_ld._quadratic_ld(self.ds, params.rp, params.u[0], params.u[1], self.nthreads)
			elif self.limb_dark == "linear": lc = _quadratic_ld._quadratic_ld(self.ds, params.rp, params.u[0], 0., self.nthreads)
			elif self.limb_dark == "nonlinear": lc = _nonlinear_ld._nonlinear_ld(self.ds, params.rp, params.u[0], params.u[1], params.u[2], params.u[3], self.fac, self.nthreads)
			elif self.limb_dark == "squareroot": lc = _nonlinear_ld._nonlinear_ld(self.ds, params.rp, params.u[1], params.u[0], 0., 0., self.fac, self.nthreads)
			elif self.limb_dark == "uniform": lc = _uniform_ld._uniform_ld(self.ds, params.rp, self.nthreads)
			elif self.limb_dark == "logarithmic": lc = _logarithmic_ld._logarithmic_ld(self.ds, params.rp, params.u[0], params.u[1], self.fac, self.nthreads)
			elif self.limb_dark == "exponential": lc = _exponential_ld._exponential_ld(self.ds, params.rp, params.u[0], params.u[1], self.fac, self.nthreads)
			elif self.limb_dark == "power2": lc = _power2_ld._power2_ld(self.ds, params.rp, params.u[0], params.u[1], self.fac, self.nthreads)
			elif self.limb_dark == "custom": lc = _custom_ld._custom_ld(self.ds, params.rp, params.u[0], params.u[1], params.u[2], params.u[3], params.u[4], params.u[5], self.fac, self.nthreads)
			else: raise Exception("Invalid limb darkening option")

			if self.inverse == True: lc = 2. - lc

		else: lc = _eclipse._eclipse(self.ds, params.rp, params.fp, self.nthreads)
		if self.supersample_factor == 1: return lc
		else: return np.mean(lc.reshape(-1, self.supersample_factor), axis=1)

	def _get_phase(self, params, position):
		if position == "periastron": TA = 0.
		elif position == "primary": TA = pi/2. - params.w*pi/180.
		elif position == "secondary": TA = 3.*pi/2. - params.w*pi/180.

		E = 2.*np.arctan(np.sqrt((1. - params.ecc)/(1. + params.ecc))*np.tan(TA/2.))
		M = E - params.ecc*np.sin(E)
		return M/2./pi

	def get_t_periastron(self, params):
		"""
		Return the time of periastron passage (calculated using `params.t0`).
		"""
		phase = self._get_phase(params, "primary")
		return params.t0 - params.per*phase

	def get_t_secondary(self, params):
		"""
		Return the time of secondary eclipse center (calculated using `params.t0`).
		"""
		phase = self._get_phase(params, "primary")
		phase2 = self._get_phase(params, "secondary")
		return params.t0 + params.per*(phase2-phase)

	def get_t_conjunction(self, params):
		"""
		Return the time of primary transit center (calculated using `params.t_secondary`).
		"""
		phase = self._get_phase(params, "primary")
		phase2 = self._get_phase(params, "secondary")
		return params.t_secondary + params.per*(phase-phase2)

	def get_true_anomaly(self):
		"""
		Return the true anomaly at each time
		"""
		self.f = _rsky._getf(self.t_supersample, self.t0, self.per, self.a,
							  self.inc*pi/180., self.ecc, self.w*pi/180.,
							  self.transittype, self.nthreads)
		return self.f

class TransitParams(object):
	"""
	Object to store the physical parameters of the transit.

	:param t0: Time of inferior conjunction.
	:type t0: float, optional

	:param t_secondary: Time of secondary eclipse center.
	:type t_secondary: float, optional

	:param per: Orbital period.
	:type per: float

	:param rp: Planet radius [in stellar radii].
	:type rp: float

	:param a: Semi-major axis [in stellar radii].
	:type a: float

	:param inc: Orbital inclination [in degrees].
	:type inc: float

	:param ecc: Orbital eccentricity.
	:type ecc: float

	:param w: Argument of periapse [in degrees]
	:type w: float

	:param u: List of limb darkening coefficients.
	:type u: array_like

	:param limb_dark: Limb darkening model (choice of "nonlinear", "quadratic", "exponential", "logarithmic", "squareroot", "linear", "uniform", "power2", or "custom").
	:type limb_dark: str

	:param fp: Planet-to-star flux ratio (for secondary eclipse models).
	:type fp: float, optional

	.. note::
		- Units for the orbital period and ephemeris can be anything as long as they are consistent (e.g. both in days).
		- The orbital path is calculated based on `t0` for primary transits and `t_secondary` for secondary eclipses.

	:Example:

	>>> import batman
	>>> params = batman.TransitParams()
	>>> params.t0 = 0. 				#time of inferior conjunction
	>>> params.per = 1.				#orbital period
	>>> params.rp = 0.1				#planet radius (in units of stellar radii)
	>>> params.a = 15.				#semi-major axis (in units of stellar radii)
	>>> params.inc = 87.				#orbital inclination (in degrees)
	>>> params.ecc = 0.				#eccentricity
	>>> params.w = 90.				#longitude of periastron (in degrees)
	>>> params.u = [0.1, 0.3] 	      	        #limb darkening coefficients
	>>> params.limb_dark = "quadratic"          	#limb darkening model
	"""
	def __init__(self):
		self.t0 = None
		self.per = None
		self.rp = None
		self.a = None
		self.inc = None
		self.ecc = None
		self.w = None
		self.u = None
		self.limb_dark = None
		self.fp = None
		self.t_secondary = None


#!/usr/bin/env python -u
'''
pDMET: Density Matrix Embedding theory for Periodic Systems
Copyright (C) 2018 Hung Q. Pham. All Rights Reserved.
A few functions in pDMET are modifed from QC-DMET Copyright (C) 2015 Sebastian Wouters

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.

Email: Hung Q. Pham <pqh3.14@gmail.com>
'''

import os, datetime
import numpy as np

BOHR = 0.52917721092
def make_imp_orbs(cell, w90, impCluster, threshold=0.5, rm_list=None, add_list=None):
    '''Attribute:
            cell            : PySCF cell object
            w90             : the w90 object for MLWFs
            impCluster      : a list of the atom labels starting from 1
       Return:
            impOrbs         : list of the MWLFs that belong to the impCluster

    '''
    impCluster = np.asarray(impCluster)

    def put_atoms_in_unitcell(frac_coors):
        coors = frac_coors.flatten()
        coors[coors < 0.0] = coors[coors < 0.0] + 1.0
        coors[coors > 1.0] = coors[coors > 1.0] - 1.0
        return coors.reshape(-1,3)

    assert impCluster.max() <= cell.natm, \
            "Check the impCluster. There are {0} atoms in the unit cell".format(cell.natm)

    # Make sure all the atoms inside the unit cell
    lattice = cell.lattice_vectors() * BOHR
    inv_lattice = np.linalg.inv(lattice)
    abs_coors = cell.atom_coords() * BOHR
    frac_coors = abs_coors @ inv_lattice
    abs_coors = put_atoms_in_unitcell(frac_coors) @ lattice
    impAtoms = abs_coors[impCluster - 1]

    # Make sure all the MLWFs inside the unit cell
    num_wann = w90.wann_centres.shape[0]
    MLWFs_coors = w90.wann_centres
    MLWFs_frac_coors = MLWFs_coors @ inv_lattice
    MLWFs_coors = put_atoms_in_unitcell(MLWFs_frac_coors) @ lattice

    # Check the distance between MLWFs and the imp atoms
    tmp = np.repeat(MLWFs_coors[:,np.newaxis,:], impAtoms.shape[0], axis=1)
    distance = np.sqrt(np.sum((tmp - impAtoms)**2, axis=2))
    min_distance = distance.min(axis=1)
    min_distance_idx = np.argmin(distance, axis=1)

    # Set the minimum distance of the undesired orbitals to 100.0, hence they get removed
    if rm_list is not None:
        min_distance[rm_list] = 100.0
    if add_list is not None:
        min_distance[add_list] = 0.01

    # Label by 1 only the impurity orbitals
    impOrbs = np.zeros(num_wann, dtype=int)
    impOrbs[min_distance < threshold] = 1

    # Group the impurity orbitals by their corresponding atoms
    Norbs = MLWFs_coors.shape[0]
    impOrbs_idx = np.arange(Norbs)[impOrbs == 1]
    atom_idx = min_distance_idx[min_distance < threshold]
    impAtms = []
    for i, atm in enumerate(impCluster):
        impAtms.append(impOrbs_idx[atom_idx == i])

    return impOrbs, impAtms


import os
import time
import torch
import imageio
import numpy as np
import torch.nn.functional as F

from run_nerf_helpers import *
from utils.flow_utils import flow_to_image

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def batchify_rays(t, chain_5frames,
                rays_flat, chunk=1024*16, **kwargs):
    """Render rays in smaller minibatches to avoid OOM.
    """
    all_ret = {}
    for i in range(0, rays_flat.shape[0], chunk):
        ret = render_rays(t, chain_5frames, rays_flat[i:i+chunk], **kwargs)
        for k in ret:
            if k not in all_ret:
                all_ret[k] = []
            all_ret[k].append(ret[k])

    all_ret = {k: torch.cat(all_ret[k], 0) for k in all_ret}
    return all_ret

def render(t, chain_5frames,
           H, W, focal, focal_render=None,
           chunk=1024*16, rays=None, c2w=None, ndc=True,
           near=0., far=1.,
           use_viewdirs=False, c2w_staticcam=None,
           **kwargs):
    """Render rays
    Args:
      H: int. Height of image in pixels.
      W: int. Width of image in pixels.
      focal: float. Focal length of pinhole camera.
      chunk: int. Maximum number of rays to process simultaneously. Used to
        control maximum memory usage. Does not affect final results.
      rays: array of shape [2, batch_size, 3]. Ray origin and direction for
        each example in batch.
      c2w: array of shape [3, 4]. Camera-to-world transformation matrix.
      ndc: bool. If True, represent ray origin, direction in NDC coordinates.
      near: float or array of shape [batch_size]. Nearest distance for a ray.
      far: float or array of shape [batch_size]. Farthest distance for a ray.
      use_viewdirs: bool. If True, use viewing direction of a point in space in model.
      c2w_staticcam: array of shape [3, 4]. If not None, use this transformation matrix for
       camera while using other c2w argument for viewing directions.
    Returns:
      rgb_map: [batch_size, 3]. Predicted RGB values for rays.
      disp_map: [batch_size]. Disparity map. Inverse of depth.
      acc_map: [batch_size]. Accumulated opacity (alpha) along a ray.
      extras: dict with everything returned by render_rays().
    """

    if c2w is not None:
        # special case to render full image
        if focal_render is not None:
            # Render full image using different focal length for dolly zoom. Inference only.
            rays_o, rays_d = get_rays(H, W, focal_render, c2w)
        else:
            rays_o, rays_d = get_rays(H, W, focal, c2w)
    else:
        # use provided ray batch
        rays_o, rays_d = rays

    if use_viewdirs:
        # provide ray directions as input
        viewdirs = rays_d
        if c2w_staticcam is not None:
            raise NotImplementedError
        # Make all directions unit magnitude.
        # shape: [batch_size, 3]
        viewdirs = viewdirs / torch.norm(viewdirs, dim=-1, keepdim=True)
        viewdirs = torch.reshape(viewdirs, [-1, 3]).float()

    sh = rays_d.shape # [..., 3]
    if ndc:
        # for forward facing scenes
        rays_o, rays_d = ndc_rays(H, W, focal, 1., rays_o, rays_d)

    # Create ray batch
    rays_o = torch.reshape(rays_o, [-1, 3]).float()
    rays_d = torch.reshape(rays_d, [-1, 3]).float()
    near, far = near * \
        torch.ones_like(rays_d[..., :1]), far * torch.ones_like(rays_d[..., :1])

    # (ray origin, ray direction, min dist, max dist) for each ray
    rays = torch.cat([rays_o, rays_d, near, far], -1)
    if use_viewdirs:
        rays = torch.cat([rays, viewdirs], -1)

    # Render and reshape
    all_ret = batchify_rays(t, chain_5frames,
                        rays, chunk, **kwargs)
    for k in all_ret:
        k_sh = list(sh[:-1]) + list(all_ret[k].shape[1:])
        all_ret[k] = torch.reshape(all_ret[k], k_sh)

    return all_ret

def render_path_batch(render_poses, time2render,
                    hwf, chunk, render_kwargs, savedir=None, focal2render=None):
    """Render frames using batch.

    Args:
      render_poses: array of shape [num_frame, 3, 4]. Camera-to-world transformation matrix of each frame.
      time2render: array of shape [num_frame]. Time of each frame.
      hwf: list. [Height of image in pixels, Width of image in pixels, Focal length of pinhole camera]
      chunk: int. Maximum number of rays to process simultaneously. Used to
        control maximum memory usage. Does not affect final results.
      render_kwargs: dictionary. args for the render function.
      savedir: string. Directory to save results.
      focal2render: list. Only used to perform dolly-zoom.
    Returns:
      ret_dict: dictionary. Final and intermediate results.
    """
    H, W, focal = hwf

    ret_dict = {}
    rgbs = []
    rgbs_d = []
    rgbs_s = []
    dynamicnesses = []

    time_curr = time.time()
    for i, c2w in enumerate(render_poses):

        print(i, time.time() - time_curr)
        time_curr = time.time()

        t = time2render[i]

        if focal2render is not None:
            # Render full image using different focal length
            rays_o, rays_d = get_rays(H, W, focal2render[i], c2w)
        else:
            rays_o, rays_d = get_rays(H, W, focal, c2w)
        rays_o = torch.reshape(rays_o, (-1, 3))
        rays_d = torch.reshape(rays_d, (-1, 3))
        batch_rays = torch.stack([rays_o, rays_d], 0)
        rgb = []
        rgb_d = []
        rgb_s = []
        dynamicness = []
        for j in range(0, batch_rays.shape[1], chunk):
            # print(j, '/', batch_rays.shape[1])
            ret = render(t, False,
                         H, W, focal,
                         chunk=chunk, rays=batch_rays[:, j:j+chunk, :],
                         **render_kwargs)
            rgb.append(ret['rgb_map_full'].cpu())
            rgb_d.append(ret['rgb_map_d'].cpu())
            rgb_s.append(ret['rgb_map_s'].cpu())
            dynamicness.append(ret['dynamicness_map'].cpu())
        rgb = torch.reshape(torch.cat(rgb, 0), (H, W, 3)).numpy()
        rgb_d = torch.reshape(torch.cat(rgb_d, 0), (H, W, 3)).numpy()
        rgb_s = torch.reshape(torch.cat(rgb_s, 0), (H, W, 3)).numpy()
        dynamicness = torch.reshape(torch.cat(dynamicness, 0), (H, W)).numpy()

        # Not a good solution. Should take care of this when preparing the data.
        if W%2 == 1:
            # rgb = cv2.resize(rgb, (W - 1, H))
            rgb = rgb[:, :-1, :]
            rgb_d = rgb_d[:, :-1, :]
            rgb_s = rgb_s[:, :-1, :]
            dynamicness = dynamicness[:, :-1]
        rgbs.append(rgb)
        rgbs_d.append(rgb_d)
        rgbs_s.append(rgb_s)
        dynamicnesses.append(dynamicness)

        if savedir is not None:
            rgb8 = to8b(rgbs[-1])
            filename = os.path.join(savedir, '{:03d}.png'.format(i))
            imageio.imwrite(filename, rgb8)

    ret_dict['rgbs'] = np.stack(rgbs, 0)
    ret_dict['rgbs_d'] = np.stack(rgbs_d, 0)
    ret_dict['rgbs_s'] = np.stack(rgbs_s, 0)
    ret_dict['dynamicnesses'] = np.stack(dynamicnesses, 0)

    return ret_dict

def render_path(render_poses,
                time2render,
                hwf,
                chunk,
                render_kwargs,
                savedir=None,
                flows_gt_f=None,
                flows_gt_b=None,
                focal2render=None):
    """Render frames.

    Args:
      render_poses: array of shape [num_frame, 3, 4]. Camera-to-world transformation matrix of each frame.
      time2render: array of shape [num_frame]. Time of each frame.
      hwf: list. [Height of image in pixels, Width of image in pixels, Focal length of pinhole camera]
      chunk: int. Maximum number of rays to process simultaneously. Used to
        control maximum memory usage. Does not affect final results.
      render_kwargs: dictionary. args for the render function.
      savedir: string. Directory to save results.
      focal2render: list. Only used to perform dolly-zoom.
    Returns:
      ret_dict: dictionary. Final and intermediate results.
    """
    H, W, focal = hwf

    ret_dict = {}
    rgbs = []
    rgbs_d = []
    rgbs_s = []
    depths = []
    depths_d = []
    depths_s = []
    flows_f = []
    flows_b = []
    dynamicness = []
    blending = []

    grid = np.stack(np.meshgrid(np.arange(W, dtype=np.float32),
                       np.arange(H, dtype=np.float32), indexing='xy'), -1)
    grid = torch.Tensor(grid)
    time_curr = time.time()
    for i, c2w in enumerate(render_poses):
        t = time2render[i]
        pose = c2w[:3, :4]
        print(i, time.time() - time_curr)
        time_curr = time.time()

        if focal2render is None:
            # Normal rendering.
            ret = render(t, False,
                         H, W, focal,
                         chunk=1024*32, c2w=pose,
                         **render_kwargs)
        else:
            # Render image using different focal length.
            ret = render(t, False,
                         H, W, focal, focal_render=focal2render[i],
                         chunk=1024*32, c2w=pose,
                         **render_kwargs)

        rgbs.append(ret['rgb_map_full'].cpu().numpy())
        rgbs_d.append(ret['rgb_map_d'].cpu().numpy())
        rgbs_s.append(ret['rgb_map_s'].cpu().numpy())

        depths.append(ret['depth_map_full'].cpu().numpy())
        depths_d.append(ret['depth_map_d'].cpu().numpy())
        depths_s.append(ret['depth_map_s'].cpu().numpy())

        dynamicness.append(ret['dynamicness_map'].cpu().numpy())

        if flows_gt_f is not None:
            # Reconstruction. Flow is caused by both changing camera and changing time.
            pose_f = render_poses[min(i + 1, int(len(render_poses)) - 1), :3, :4]
            pose_b = render_poses[max(i - 1, 0), :3, :4]
        else:
            # Non training view-time. Flow is caused by changing time (just for visualization).
            pose_f = render_poses[i, :3, :4]
            pose_b = render_poses[i, :3, :4]

        # Sceneflow induced optical flow
        induced_flow_f_ = induce_flow(H, W, focal, pose_f, ret['weights_d'], ret['raw_pts_f'], grid[..., :2])
        induced_flow_b_ = induce_flow(H, W, focal, pose_b, ret['weights_d'], ret['raw_pts_b'], grid[..., :2])

        if (i + 1) >= len(render_poses):
            induced_flow_f = np.zeros((H, W, 2))
        else:
            induced_flow_f = induced_flow_f_.cpu().numpy()
        if flows_gt_f is not None:
            flow_gt_f = flows_gt_f[i].cpu().numpy()
            induced_flow_f = np.concatenate((induced_flow_f, flow_gt_f), 0)
        induced_flow_f_img = flow_to_image(induced_flow_f)
        flows_f.append(induced_flow_f_img)

        if (i - 1) < 0:
            induced_flow_b = np.zeros((H, W, 2))
        else:
            induced_flow_b = induced_flow_b_.cpu().numpy()
        if flows_gt_b is not None:
            flow_gt_b = flows_gt_b[i].cpu().numpy()
            induced_flow_b = np.concatenate((induced_flow_b, flow_gt_b), 0)
        induced_flow_b_img = flow_to_image(induced_flow_b)
        flows_b.append(induced_flow_b_img)

        if i == 0:
            ret_dict['sceneflow_f_NDC'] = ret['sceneflow_f'].cpu().numpy()
            ret_dict['sceneflow_b_NDC'] = ret['sceneflow_b'].cpu().numpy()
            ret_dict['blending'] = ret['blending'].cpu().numpy()

            weights = np.concatenate((ret['weights_d'][..., None].cpu().numpy(),
                                      ret['weights_s'][..., None].cpu().numpy(),
                                      ret['blending'][..., None].cpu().numpy(),
                                      ret['weights_full'][..., None].cpu().numpy()))
            ret_dict['weights'] = np.moveaxis(weights, [0, 1, 2, 3], [1, 2, 0, 3])

        if savedir is not None:
            rgb8 = to8b(rgbs[-1])
            filename = os.path.join(savedir, '{:03d}.png'.format(i))
            imageio.imwrite(filename, rgb8)

    ret_dict['rgbs'] = np.stack(rgbs, 0)
    ret_dict['rgbs_d'] = np.stack(rgbs_d, 0)
    ret_dict['rgbs_s'] = np.stack(rgbs_s, 0)
    ret_dict['depths'] = np.stack(depths, 0)
    ret_dict['depths_d'] = np.stack(depths_d, 0)
    ret_dict['depths_s'] = np.stack(depths_s, 0)
    ret_dict['dynamicness'] = np.stack(dynamicness, 0)
    ret_dict['flows_f'] = np.stack(flows_f, 0)
    ret_dict['flows_b'] = np.stack(flows_b, 0)

    return ret_dict

def raw2outputs(raw_s,
                raw_d,
                blending,
                z_vals,
                rays_d,
                raw_noise_std):
    """Transforms model's predictions to semantically meaningful values.

    Args:
      raw_d: [num_rays, num_samples along ray, 4]. Prediction from Dynamic model.
      raw_s: [num_rays, num_samples along ray, 4]. Prediction from Static model.
      z_vals: [num_rays, num_samples along ray]. Integration time.
      rays_d: [num_rays, 3]. Direction of each ray.

    Returns:
      rgb_map: [num_rays, 3]. Estimated RGB color of a ray.
      disp_map: [num_rays]. Disparity map. Inverse of depth map.
      acc_map: [num_rays]. Sum of weights along each ray.
      weights: [num_rays, num_samples]. Weights assigned to each sampled color.
      depth_map: [num_rays]. Estimated distance to object.
    """
    # Function for computing density from model prediction. This value is
    # strictly between [0, 1].
    def raw2alpha(raw, dists, act_fn=F.relu): return 1.0 - \
        torch.exp(-act_fn(raw) * dists)

    # Compute 'distance' (in time) between each integration time along a ray.
    dists = z_vals[..., 1:] - z_vals[..., :-1]

    # The 'distance' from the last integration time is infinity.
    dists = torch.cat(
        [dists, torch.Tensor([1e10]).expand(dists[..., :1].shape)],
         -1) # [N_rays, N_samples]

    # Multiply each distance by the norm of its corresponding direction ray
    # to convert to real world distance (accounts for non-unit directions).
    dists = dists * torch.norm(rays_d[..., None, :], dim=-1)

    # Extract RGB of each sample position along each ray.
    rgb_d = torch.sigmoid(raw_d[..., :3])  # [N_rays, N_samples, 3]
    rgb_s = torch.sigmoid(raw_s[..., :3])  # [N_rays, N_samples, 3]

    # Add noise to model's predictions for density. Can be used to
    # regularize network during training (prevents floater artifacts).
    noise = 0.
    if raw_noise_std > 0.:
        noise = torch.randn(raw_d[..., 3].shape) * raw_noise_std

    # Predict density of each sample along each ray. Higher values imply
    # higher likelihood of being absorbed at this point.
    alpha_d = raw2alpha(raw_d[..., 3] + noise, dists) # [N_rays, N_samples]
    alpha_s = raw2alpha(raw_s[..., 3] + noise, dists) # [N_rays, N_samples]
    alphas  = 1. - (1. - alpha_s) * (1. - alpha_d) # [N_rays, N_samples]

    T_d    = torch.cumprod(torch.cat([torch.ones((alpha_d.shape[0], 1)), 1. - alpha_d + 1e-10], -1), -1)[:, :-1]
    T_s    = torch.cumprod(torch.cat([torch.ones((alpha_s.shape[0], 1)), 1. - alpha_s + 1e-10], -1), -1)[:, :-1]
    T_full = torch.cumprod(torch.cat([torch.ones((alpha_d.shape[0], 1)), (1. - alpha_d * blending) * (1. - alpha_s * (1. - blending)) + 1e-10], -1), -1)[:, :-1]
    # T_full = torch.cumprod(torch.cat([torch.ones((alpha_d.shape[0], 1)), torch.pow(1. - alpha_d + 1e-10, blending) * torch.pow(1. - alpha_s + 1e-10, 1. - blending)], -1), -1)[:, :-1]
    # T_full = torch.cumprod(torch.cat([torch.ones((alpha_d.shape[0], 1)), (1. - alpha_d) * (1. - alpha_s) + 1e-10], -1), -1)[:, :-1]

    # Compute weight for RGB of each sample along each ray.  A cumprod() is
    # used to express the idea of the ray not having reflected up to this
    # sample yet.
    weights_d = alpha_d * T_d
    weights_s = alpha_s * T_s
    weights_full = (alpha_d * blending + alpha_s * (1. - blending)) * T_full
    # weights_full = alphas * T_full

    # Computed weighted color of each sample along each ray.
    rgb_map_d = torch.sum(weights_d[..., None] * rgb_d, -2)
    rgb_map_s = torch.sum(weights_s[..., None] * rgb_s, -2)
    rgb_map_full = torch.sum(
        (T_full * alpha_d * blending)[..., None] * rgb_d + \
        (T_full * alpha_s * (1. - blending))[..., None] * rgb_s, -2)

    # Estimated depth map is expected distance.
    depth_map_d = torch.sum(weights_d * z_vals, -1)
    depth_map_s = torch.sum(weights_s * z_vals, -1)
    depth_map_full = torch.sum(weights_full * z_vals, -1)

    # Sum of weights along each ray. This value is in [0, 1] up to numerical error.
    acc_map_d = torch.sum(weights_d, -1)
    acc_map_s = torch.sum(weights_s, -1)
    acc_map_full = torch.sum(weights_full, -1)

    # Computed dynamicness
    dynamicness_map = torch.sum(weights_full * blending, -1)
    # dynamicness_map = 1 - T_d[..., -1]

    return rgb_map_full, depth_map_full, acc_map_full, weights_full, \
           rgb_map_s, depth_map_s, acc_map_s, weights_s, \
           rgb_map_d, depth_map_d, acc_map_d, weights_d, dynamicness_map

def raw2outputs_d(raw_d,
                  z_vals,
                  rays_d,
                  raw_noise_std):

    # Function for computing density from model prediction. This value is
    # strictly between [0, 1].
    def raw2alpha(raw, dists, act_fn=F.relu): return 1.0 - \
        torch.exp(-act_fn(raw) * dists)

    # Compute 'distance' (in time) between each integration time along a ray.
    dists = z_vals[..., 1:] - z_vals[..., :-1]

    # The 'distance' from the last integration time is infinity.
    dists = torch.cat(
        [dists, torch.Tensor([1e10]).expand(dists[..., :1].shape)],
        -1)  # [N_rays, N_samples]

    # Multiply each distance by the norm of its corresponding direction ray
    # to convert to real world distance (accounts for non-unit directions).
    dists = dists * torch.norm(rays_d[..., None, :], dim=-1)

    # Extract RGB of each sample position along each ray.
    rgb_d = torch.sigmoid(raw_d[..., :3])  # [N_rays, N_samples, 3]

    # Add noise to model's predictions for density. Can be used to
    # regularize network during training (prevents floater artifacts).
    noise = 0.
    if raw_noise_std > 0.:
        noise = torch.randn(raw_d[..., 3].shape) * raw_noise_std

    # Predict density of each sample along each ray. Higher values imply
    # higher likelihood of being absorbed at this point.
    alpha_d = raw2alpha(raw_d[..., 3] + noise, dists)  # [N_rays, N_samples]

    T_d = torch.cumprod(torch.cat([torch.ones((alpha_d.shape[0], 1)), 1. - alpha_d + 1e-10], -1), -1)[:, :-1]
    # Compute weight for RGB of each sample along each ray.  A cumprod() is
    # used to express the idea of the ray not having reflected up to this
    # sample yet.
    weights_d = alpha_d * T_d

    # Computed weighted color of each sample along each ray.
    rgb_map_d = torch.sum(weights_d[..., None] * rgb_d, -2)

    return rgb_map_d, weights_d

def render_rays(t,
                chain_5frames,
                ray_batch,
                network_fn_d,
                network_fn_s,
                network_query_fn_d,
                network_query_fn_s,
                N_samples,
                num_img,
                DyNeRF_blending,
                pretrain=False,
                lindisp=False,
                perturb=0.,
                N_importance=0,
                raw_noise_std=0.,
                inference=False):

    """Volumetric rendering.
    Args:
      ray_batch: array of shape [batch_size, ...]. All information necessary
        for sampling along a ray, including: ray origin, ray direction, min
        dist, max dist, and unit-magnitude viewing direction.
      network_fn_d: function. Model for predicting RGB and density at each point
        in space.
      network_query_fn_d: function used for passing queries to network_fn_d.
      N_samples: int. Number of different times to sample along each ray.
      lindisp: bool. If True, sample linearly in inverse depth rather than in depth.
      perturb: float, 0 or 1. If non-zero, each ray is sampled at stratified
        random points in time.
      N_importance: int. Number of additional times to sample along each ray.
        These samples are only passed to network_fine.
      network_fine: "fine" network with same spec as network_fn.
      raw_noise_std: ...
    Returns:
      rgb_map: [num_rays, 3]. Estimated RGB color of a ray. Comes from fine model.
      disp_map: [num_rays]. Disparity map. 1 / depth.
      acc_map: [num_rays]. Accumulated opacity along each ray. Comes from fine model.
      raw: [num_rays, num_samples, 4]. Raw predictions from model.
      rgb0: See rgb_map. Output for coarse model.
      disp0: See disp_map. Output for coarse model.
      acc0: See acc_map. Output for coarse model.
      z_std: [num_rays]. Standard deviation of distances along ray for each
        sample.
    """

    # batch size
    N_rays = ray_batch.shape[0]

    # ray_batch: [N_rays, 11]
    # rays_o:    [N_rays, 0:3]
    # rays_d:    [N_rays, 3:6]
    # near:      [N_rays, 6:7]
    # far:       [N_rays, 7:8]
    # viewdirs:  [N_rays, 8:11]

    # Extract ray origin, direction.
    rays_o, rays_d = ray_batch[:, 0:3], ray_batch[:, 3:6] # [N_rays, 3] each

    # Extract unit-normalized viewing direction.
    viewdirs = ray_batch[:, -3:] if ray_batch.shape[-1] > 8 else None

    # Extract lower, upper bound for ray distance.
    bounds = torch.reshape(ray_batch[..., 6:8], [-1, 1, 2])
    near, far = bounds[..., 0], bounds[..., 1]

    # Decide where to sample along each ray. Under the logic, all rays will be sampled at
    # the same times.
    t_vals = torch.linspace(0., 1., steps=N_samples)
    if not lindisp:
        # Space integration times linearly between 'near' and 'far'. Same
        # integration points will be used for all rays.
        z_vals = near * (1.-t_vals) + far * (t_vals)
    else:
        # Sample linearly in inverse depth (disparity).
        z_vals = 1./(1./near * (1.-t_vals) + 1./far * (t_vals))
    z_vals = z_vals.expand([N_rays, N_samples])

    # Perturb sampling time along each ray.
    if perturb > 0.:
        # get intervals between samples
        mids = .5 * (z_vals[..., 1:] + z_vals[..., :-1])
        upper = torch.cat([mids, z_vals[..., -1:]], -1)
        lower = torch.cat([z_vals[..., :1], mids], -1)
        # stratified samples in those intervals
        t_rand = torch.rand(z_vals.shape)
        z_vals = lower + (upper - lower) * t_rand

    # Points in space to evaluate model at.
    pts = rays_o[..., None, :] + rays_d[..., None, :] * \
        z_vals[..., :, None] # [N_rays, N_samples, 3]

    # Add the time dimension to xyz.
    pts_ref = torch.cat([pts, torch.ones_like(pts[..., 0:1]) * t], -1)

    # First pass: we have the staticNeRF results
    raw_s = network_query_fn_s(pts_ref[..., :3], viewdirs, network_fn_s)
    # raw_s:          [N_rays, N_samples, 5]
    # raw_s_rgb:      [N_rays, N_samples, 0:3]
    # raw_s_a:        [N_rays, N_samples, 3:4]
    # raw_s_blending: [N_rays, N_samples, 4:5]

    # Second pass: we have the DyanmicNeRF results and the blending weight
    raw_d = network_query_fn_d(pts_ref, viewdirs, network_fn_d)
    # raw_d:          [N_rays, N_samples, 11]
    # raw_d_rgb:      [N_rays, N_samples, 0:3]
    # raw_d_a:        [N_rays, N_samples, 3:4]
    # sceneflow_b:    [N_rays, N_samples, 4:7]
    # sceneflow_f:    [N_rays, N_samples, 7:10]
    # raw_d_blending: [N_rays, N_samples, 10:11]

    if pretrain:
        rgb_map_s, _ = raw2outputs_d(raw_s[..., :4],
                                     z_vals,
                                     rays_d,
                                     raw_noise_std)
        ret = {'rgb_map_s': rgb_map_s}
        return ret

    raw_s_rgba = raw_s[..., :4]
    raw_d_rgba = raw_d[..., :4]

    # We need the sceneflow from the dynamicNeRF.
    sceneflow_b = raw_d[..., 4:7]
    sceneflow_f = raw_d[..., 7:10]

    if DyNeRF_blending:
        blending = raw_d[..., 10]
    else:
        blending = raw_s[..., 4]

    # if sfmask:
    #     sceneflow_f = sceneflow_f * blending.detach()[..., None]
    #     sceneflow_b = sceneflow_b * blending.detach()[..., None]

    # Rerndering.
    rgb_map_full, depth_map_full, acc_map_full, weights_full, \
    rgb_map_s, depth_map_s, acc_map_s, weights_s, \
    rgb_map_d, depth_map_d, acc_map_d, weights_d, \
    dynamicness_map = raw2outputs(raw_s_rgba,
                                  raw_d_rgba,
                                  blending,
                                  z_vals,
                                  rays_d,
                                  raw_noise_std)

    ret = {'rgb_map_full': rgb_map_full, 'depth_map_full': depth_map_full, 'acc_map_full': acc_map_full, 'weights_full': weights_full,
           'rgb_map_s': rgb_map_s, 'depth_map_s': depth_map_s, 'acc_map_s': acc_map_s, 'weights_s': weights_s,
           'rgb_map_d': rgb_map_d, 'depth_map_d': depth_map_d, 'acc_map_d': acc_map_d, 'weights_d': weights_d,
           'dynamicness_map': dynamicness_map}

    t_interval = 1. / num_img * 2.
    pts_f = torch.cat([pts + sceneflow_f, torch.ones_like(pts[..., 0:1]) * (t + t_interval)], -1)
    pts_b = torch.cat([pts + sceneflow_b, torch.ones_like(pts[..., 0:1]) * (t - t_interval)], -1)

    ret['sceneflow_b'] = sceneflow_b
    ret['sceneflow_f'] = sceneflow_f
    ret['raw_pts'] = pts_ref[..., :3]
    ret['raw_pts_f'] = pts_f[..., :3]
    ret['raw_pts_b'] = pts_b[..., :3]
    ret['blending'] = blending

    # Third pass: we have the DyanmicNeRF results at time t - 1
    raw_d_b = network_query_fn_d(pts_b, viewdirs, network_fn_d)
    raw_d_b_rgba = raw_d_b[..., :4]
    sceneflow_b_b = raw_d_b[..., 4:7]
    sceneflow_b_f = raw_d_b[..., 7:10]

    # Rerndering t - 1
    rgb_map_d_b, weights_d_b = raw2outputs_d(raw_d_b_rgba,
                                             z_vals,
                                             rays_d,
                                             raw_noise_std)

    ret['sceneflow_b_f'] = sceneflow_b_f
    ret['rgb_map_d_b'] = rgb_map_d_b
    ret['acc_map_d_b'] = torch.abs(torch.sum(weights_d_b - weights_d, -1))

    # Fourth pass: we have the DyanmicNeRF results at time t + 1
    raw_d_f = network_query_fn_d(pts_f, viewdirs, network_fn_d)
    raw_d_f_rgba = raw_d_f[..., :4]
    sceneflow_f_b = raw_d_f[..., 4:7]
    sceneflow_f_f = raw_d_f[..., 7:10]

    rgb_map_d_f, weights_d_f = raw2outputs_d(raw_d_f_rgba,
                                             z_vals,
                                             rays_d,
                                             raw_noise_std)

    ret['sceneflow_f_b'] = sceneflow_f_b
    ret['rgb_map_d_f'] = rgb_map_d_f
    ret['acc_map_d_f'] = torch.abs(torch.sum(weights_d_f - weights_d, -1))

    if inference:
        return ret

    # Also consider time t - 2 and t + 2 (Learn from NSFF)

    # Fifth pass: we have the DyanmicNeRF results at time t - 2
    pts_b_b = torch.cat([pts_b[..., :3] + sceneflow_b_b, torch.ones_like(pts[..., 0:1]) * (t - t_interval * 2)], -1)
    ret['raw_pts_b_b'] = pts_b_b[..., :3]

    if chain_5frames:
        raw_d_b_b = network_query_fn_d(pts_b_b, viewdirs, network_fn_d)
        raw_d_b_b_rgba = raw_d_b_b[..., :4]
        rgb_map_d_b_b, _ = raw2outputs_d(raw_d_b_b_rgba,
                                      z_vals,
                                      rays_d,
                                      raw_noise_std)

        ret['rgb_map_d_b_b'] = rgb_map_d_b_b

    # Sixth pass: we have the DyanmicNeRF results at time t + 2
    pts_f_f = torch.cat([pts_f[..., :3] + sceneflow_f_f, torch.ones_like(pts[..., 0:1]) * (t + t_interval * 2)], -1)
    ret['raw_pts_f_f'] = pts_f_f[..., :3]

    if chain_5frames:
        raw_d_f_f = network_query_fn_d(pts_f_f, viewdirs, network_fn_d)
        raw_d_f_f_rgba = raw_d_f_f[..., :4]
        rgb_map_d_f_f, _ = raw2outputs_d(raw_d_f_f_rgba,
                                      z_vals,
                                      rays_d,
                                      raw_noise_std)

        ret['rgb_map_d_f_f'] = rgb_map_d_f_f

    for k in ret:
        if torch.isnan(ret[k]).any() or torch.isinf(ret[k]).any():
            print(f"! [Numerical Error] {k} contains nan or inf.")
            import ipdb; ipdb.set_trace()

    return ret