# coding=utf-8
# Copyright 2022 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.

# Lint as: python3
"""Tests for supcon.losses."""
from absl.testing import parameterized
import numpy as np
import tensorflow.compat.v2 as tf

from supcon import enums
from supcon import losses


class LossesTest(tf.test.TestCase, parameterized.TestCase):

  def testKerasImplementation(self):
    features = np.random.uniform(0., 1., (12, 2, 20))
    labels = np.eye(12, 15, dtype=np.int32)
    loss = losses.ContrastiveLoss()(labels, features)
    self.assertEqual(loss.shape, ())
    self.assertFalse(np.isnan(loss.numpy()))

  def testKerasLossVsNonKerasLoss(self):
    features = np.random.uniform(0., 1., size=(12, 2, 20))
    labels = np.eye(12, 15, dtype=np.int32)
    loss_keras = losses.ContrastiveLoss()(labels, features)
    loss_direct = tf.reduce_mean(
        losses.contrastive_loss(features, labels=labels))
    self.assertFalse(np.isnan(loss_direct.numpy()))
    self.assertFalse(np.isnan(loss_keras.numpy()))
    self.assertEqual(loss_direct.numpy(), loss_keras.numpy())

  def testIncorrectFeaturesRank(self):
    features = np.zeros([1, 1])
    with self.assertRaisesRegex(ValueError, 'Invalid features rank'):
      losses.contrastive_loss(features)

  def testUnknownBatchSizeDimension(self):
    features = tf.keras.layers.Input(
        dtype=tf.float32, batch_size=None, shape=(2, 20))
    with self.assertRaisesRegex(ValueError, 'features has unknown batch_size'):
      losses.contrastive_loss(features)

  def testUnknownNumViewsDimension(self):
    features = tf.keras.layers.Input(
        dtype=tf.float32, batch_size=1, shape=(None, 20))
    with self.assertRaisesRegex(ValueError, 'features has unknown num_views'):
      losses.contrastive_loss(features)

  def testIncorrectLabelsShape(self):
    features = np.random.uniform(0., 1., size=(10, 3, 20))
    labels = np.random.randint(1, size=(5))
    with self.assertRaisesRegex(ValueError, 'Invalid labels shape'):
      losses.contrastive_loss(features, labels=labels)

  def testIncorrectLabelsRank(self):
    features = np.random.uniform(0., 1., size=(10, 3, 20))
    labels = np.random.randint(5, size=(4, 4))
    with self.assertRaisesRegex(ValueError, 'Invalid labels shape'):
      losses.contrastive_loss(features, labels=labels)

  def testUnknownContrastMode(self):
    features = np.random.uniform(size=(10, 3, 20))
    labels = np.eye(10, dtype=np.int32)
    with self.assertRaisesRegex(ValueError, 'Invalid contrast_mode'):
      losses.contrastive_loss(features, labels, contrast_mode='invalid')

  def testUnknownSummationLocation(self):
    features = np.random.uniform(size=(10, 3, 20))
    labels = np.eye(10, dtype=np.int32)