# Copyright 2019 The FastEstimator Authors. 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.
# ==============================================================================
import tensorflow as tf
from tensorflow.python.keras.losses import Loss as tfLoss

from fastestimator.op.tensorop.loss import Loss


class MixUpLoss(Loss):
    """This class should be used in conjunction with MixUpBatch to perform mix-up training, which helps to reduce
    over-fitting, stabilize GAN training, and harden against adversarial attacks (https://arxiv.org/abs/1710.09412)

    Args:
        loss (func): A loss object (tf.losses) which can be invoked like "loss(true, pred)". It's reduction method
        will be overridden to 'none'
        lam: The key of the lambda value generated by MixUpBatch
        y_true: ground truth label key
        y_pred: prediction label key
        inputs: A tuple or list like: [<lam>, <y_true>, <y_pred>]
        outputs: Where to store the computed loss value (not required under normal use cases)
        mode: 'train', 'eval', 'test', or None
    """
    def __init__(self, loss, lam=None, y_true=None, y_pred=None, inputs=None, outputs=None, mode=None):

        assert isinstance(loss, tfLoss), "MixUpLoss requires a TensorFlow loss function"
        loss_config = loss.get_config()
        loss_config['reduction'] = 'none'
        inputs = self.validate_loss_inputs(inputs, lam, y_true, y_pred)
        super().__init__(inputs=inputs, outputs=outputs, mode=mode)
        self.loss_obj = loss.from_config(loss_config)

    def forward(self, data, state):
        lam, true, pred = data
        loss1 = self.loss_obj(true, pred)
        loss2 = self.loss_obj(tf.roll(true, shift=1, axis=0), pred)
        return lam * loss1 + (1.0 - lam) * loss2
