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

"""All functions related to loss computation and optimization.
"""

import flax
import jax
import jax.numpy as jnp
import jax.random as random
from models import utils as mutils
from sde_lib import VESDE, VPSDE, I2SBSDE, RFSDE, EDMSDE
from utils import batch_mul
import optax
import numpy as np

from flax.traverse_util import flatten_dict

def get_optimizer(config):
  """Returns a flax optimizer object based on `config`."""
  if config.optim.optimizer == 'Adam':
    warmup = config.optim.warmup
    if warmup > 0:
      warmup_schedule = optax.warmup_cosine_decay_schedule(init_value=0.0,
                                                           peak_value=config.optim.lr,
                                                           warmup_steps=warmup,
                                                           decay_steps=config.training.n_iters,
                                                           end_value=config.optim.lr)                                                 
      optimizer = optax.adamw(learning_rate=warmup_schedule, b1=config.optim.beta1, eps=config.optim.eps, weight_decay=config.optim.weight_decay)
    else:
      warmup_schedule = config.optim.lr
      optimizer = optax.adamw(learning_rate=warmup_schedule)
  else:
    raise NotImplementedError(
      f'Optimizer {config.optim.optimizer} not supported yet!')

  return optimizer


def optimization_manager(config):
  """Returns an optimize_fn based on `config`."""

  def optimize_fn(state,
                  grad,
                  grad_clip=config.optim.grad_clip):
    """Optimizes with warmup and gradient clipping (disabled if negative)."""
    # Fast parameter update
    if grad_clip >= 0:
      # Compute global gradient norm
      grad_norm = jnp.sqrt(
        sum([jnp.sum(jnp.square(x)) for x in jax.tree_util.tree_leaves(grad)]))
      # Clip gradient
      clipped_grad = jax.tree_map(
        lambda x: x * grad_clip / jnp.maximum(grad_norm, grad_clip), grad)
    else:  # disabling gradient clipping if grad_clip < 0
      clipped_grad = grad
    state = state.apply_gradients(grads=clipped_grad) # variables['params'] updated.

    # Delayed parameter (EMA) update
    initial_count = 0
    if config.model.variable_ema_rate:
      ema_decay = jnp.minimum(config.model.ema_rate, (1 + (initial_count + state.step)) / (10 + (initial_count + state.step)))
    else:
      ema_decay = config.model.ema_rate
    updates, new_opt_state_ema = state.tx_ema.update(
      state.params, state.opt_state_ema, ema_decay
    )
    state = state.replace(opt_state_ema=new_opt_state_ema)

    return state

  return optimize_fn


def get_rf_loss_fn(sde, state, train, dense_fn, reduce_mean=True, eps=1e-5, aug_dim=0, lambda1=1, lambda2=1):
  """
    Create a loss function for training RFs. (rectified flow)
    
    sde: An `sde_lib.SDE` object that represents the forward SDE.
    model: A `flax.linen.Module` object that represents the architecture of the score-based model.
    train: `True` for training loss and `False` for evaluation loss.
    reduce_mean: If `True`, average the loss across data dimensions. Otherwise sum the loss across data dimensions.
    continuous: `True` indicates that the model is defined to take continuous time steps. Otherwise it requires
      ad-hoc interpolation to take continuous time steps.
    likelihood_weighting: If `True`, weight the mixture of score matching losses
      according to https://arxiv.org/abs/2101.09258; otherwise use the weighting recommended in our paper.
    eps: A `float` number. The smallest time step to sample from.
  """
  reduce_op = jnp.mean if reduce_mean else lambda *args, **kwargs: 0.5 * jnp.sum(*args, **kwargs)

  def loss_fn(rng, params, batch):
    score_fn = mutils.get_score_fn(sde, state, params, train=train, eps=eps)
    x0, x1 = batch

    # preprocessing w.r.t auxiliary dimension
    rng, step_rng = jax.random.split(rng)
    if aug_dim > 0:
      y0 = random.normal(step_rng, x0.shape[:-1] + (aug_dim,))
      y1 = lambda1 * y0 + lambda2 * dense_fn(x0 + x1)
      x0, x1 = jnp.concatenate([x0, y0], axis=-1), jnp.concatenate([x1, y1], axis=-1)

    # loss
    rng, step_rng = jax.random.split(rng)
    t = random.uniform(step_rng, (x0.shape[0],), minval=0.0, maxval=1)
    perturbed_data = batch_mul(x0, 1 - t) + batch_mul(x1, t)
    score = score_fn(perturbed_data, t, rng)
    score_ref = x1 - x0
    losses = jnp.square(score_ref - score)
    losses = reduce_op(losses.reshape((losses.shape[0], -1)), axis=-1)
    loss = jnp.mean(losses)
    return loss

  return loss_fn


# EGNN loss function
def get_gnn_rf_loss_fn(sde, state, train, dense_fn, reduce_mean=True, eps=1e-5, aug_dim=0, lambda1=1, lambda2=1):
  reduce_op = jnp.mean if reduce_mean else lambda *args, **kwargs: 0.5 * jnp.sum(*args, **kwargs)
  def loss_fn(rng, params, batch):
    """
    Input
      rng: jax.random.PRNGKey
      params: parameters
      batch: contains - {
          'h'        : h, # noisy h value
          'x'        : x, # noisy x value
          'edges'    : edges,
          'node_mask': node_mask,
          'edge_mask': edge_mask,
          'xh_true'  : true xh,
          'z'        : noise,
          't'        : time,
        }
    """
    flow_fn = mutils.get_egnn_flow_fn(state, params, train=train)

    # Preprocess w.r.t. auxiliary dimension
    # egnn_batch = {
    #   'h'        : h,         # h value,   shape (B * N, 6)
    #   'x'        : x,         # x value,   shape (B * N, 3)
    #   'edges'    : edges,     # edges,     shape [(B * N * N,), (B * N * N,)]
    #   'node_mask': node_mask, # node_mask, shape (B * N, 1)
    #   'edge_mask': edge_mask, # edge_mask, shape (B * N * N, 1)
    #   'noise_h'  : noise_h,   # h noise,   shape (B * N, 6)
    #   'noise_x'  : noise_x,   # x noise,   shape (B * N, 3)
    #   't'        : h_time,    # time,      shape (B * N, 1)
    # }

    x0 = jnp.concatenate([batch['noise_x'], batch['noise_h']], axis=-1)
    x1 = jnp.concatenate([batch['x'], batch['h']], axis=-1)
    rng, step_rng = jax.random.split(rng)
    y0 = random.normal(step_rng, x0.shape[:-1] + (aug_dim,))
    y1 = lambda1 * y0 + lambda2 * dense_fn(x0 + x1)
    x0, x1 = jnp.concatenate([x0, y0], axis=-1), jnp.concatenate([x1, y1], axis=-1)

    # loss
    perturbed_data = x0 * (1 - batch['t']) + x1 * batch['t']
    input_batch = {
      'x':         perturbed_data[..., :3],
      'h':         perturbed_data[..., 3:],
      'edges':     batch['edges'],
      'node_mask': batch['node_mask'],
      'edge_mask': batch['edge_mask'],
      't':         batch['t']
    }
    h_out, x_out = flow_fn(input_batch)
    flow = jnp.concatenate([x_out, h_out], axis=-1)
    flow_ref = x1 - x0
    losses = jnp.square(flow_ref - flow)
    losses = reduce_op(losses.reshape((losses.shape[0], -1)), axis=-1)
    loss = jnp.mean(losses)
    return loss

  return loss_fn

def get_step_fn(config, sde, state, train, dense_fn, optimize_fn=None, reduce_mean=False, eps=0.0):
  """Create a one-step training/evaluation function.

  Args:
    sde: An `sde_lib.SDE` object that represents the forward SDE.
    state: `flax.training.TrainState` object.
    train: `True` for training and `False` for evaluation.
    optimize_fn: An optimization function.
    reduce_mean: If `True`, average the loss across data dimensions. Otherwise sum the loss across data dimensions.
    reflow_t: number of reflow steps.

  Returns:
    A one-step function for training or evaluation.
  """
  if config.model.name != 'egnn':
    loss_fn = get_rf_loss_fn(sde, state, train, reduce_mean=reduce_mean, eps=eps,
                             aug_dim=config.model.aug_dim, lambda1=config.model.lambda1, lambda2=config.model.lambda2, dense_fn=dense_fn)
  else: # GNN case
    loss_fn = get_gnn_rf_loss_fn(sde, state, train, reduce_mean=reduce_mean, eps=eps,
                                 aug_dim=config.model.aug_dim, lambda1=config.model.lambda1, lambda2=config.model.lambda2, dense_fn=dense_fn)


  def step_fn(carry_state, batch):
    """Running one step of training or evaluation.

    This function will undergo `jax.lax.scan` so that multiple steps can be pmapped and jit-compiled together
    for faster execution.

    Args:
      carry_state: A tuple (JAX random state, `flax.training.TrainState` containing the training state).
      batch: A mini-batch of training/evaluation data.

    Returns:
      new_carry_state: The updated tuple of `carry_state`.
      loss: The average loss value of this state.
    """

    (rng, state) = carry_state
    # rng = jax.random.fold_in(rng, state.step) # New RNGsplitter.
    rng, step_rng = jax.random.split(rng)
    grad_fn = jax.value_and_grad(loss_fn, argnums=1)
    if train: # training
      loss, grad = grad_fn(step_rng, state.params, batch)
      grad = jax.lax.pmean(grad, axis_name='batch')
      state = optimize_fn(state, grad) # Optimize params with (Adam) optimizer
      state = state.replace(step=state.step + 1) # Update step
    else: # evaluation or sampling
      loss = loss_fn(step_rng, state.opt_state_ema.ema, batch)

    loss = jax.lax.pmean(loss, axis_name='batch')
    return (rng, state), loss

  return step_fn
