from nose.tools import eq_, assert_less, assert_greater, assert_almost_equal

import numpy

numpy.random.seed(0)

import logging
logging.getLogger('tensorflow').disabled = True

import keras.backend as K

from mhcflurry.custom_loss import CUSTOM_LOSSES


def evaluate_loss(loss, y_true, y_pred):
    session = K.get_session()
    y_true_var = K.constant(y_true, name="y_true")
    y_pred_var = K.constant(y_pred, name="y_pred")
    result = loss(y_true_var, y_pred_var)
    return result.eval(session=session)


def test_mse_with_inequalities():

    loss_obj = CUSTOM_LOSSES['mse_with_inequalities']

    y_values = [0.0, 0.5, 0.8, 1.0]

    adjusted_y = loss_obj.encode_y(y_values)
    loss0 = evaluate_loss(loss_obj.loss, adjusted_y, y_values)
    eq_(loss0, 0.0)

    adjusted_y = loss_obj.encode_y(y_values, [">", ">", ">", ">"])
    loss0 = evaluate_loss(loss_obj.loss, adjusted_y, y_values)
    eq_(loss0, 0.0)

    adjusted_y = loss_obj.encode_y(y_values, ["<", "<", "<", "<"])
    loss0 = evaluate_loss(loss_obj.loss, adjusted_y, y_values)
    eq_(loss0, 0.0)

    adjusted_y = loss_obj.encode_y(y_values, ["=", "<", "=", ">"])
    loss0 = evaluate_loss(loss_obj.loss, adjusted_y, y_values)
    eq_(loss0, 0.0)

    adjusted_y = loss_obj.encode_y(y_values, ["=", "<", "=", ">"])
    loss0 = evaluate_loss(loss_obj.loss, adjusted_y, [0.0, 0.4, 0.8, 1.0])
    eq_(loss0, 0.0)

    adjusted_y = loss_obj.encode_y(y_values, [">", "<", ">", ">"])
    loss0 = evaluate_loss(loss_obj.loss, adjusted_y, [0.1, 0.4, 0.9, 1.0])
    eq_(loss0, 0.0)

    adjusted_y = loss_obj.encode_y(y_values, [">", "<", ">", ">"])
    loss0 = evaluate_loss(loss_obj.loss, adjusted_y, [0.1, 0.6, 0.9, 1.0])
    assert_greater(loss0, 0.0)

    adjusted_y = loss_obj.encode_y(y_values, ["=", "<", ">", ">"])
    loss0 = evaluate_loss(loss_obj.loss, adjusted_y, [0.1, 0.6, 0.9, 1.0])
    assert_almost_equal(loss0, 0.02)

    adjusted_y = loss_obj.encode_y(y_values, ["=", "<", "=", ">"])
    loss0 = evaluate_loss(loss_obj.loss, adjusted_y, [0.1, 0.6, 0.9, 1.0])
    assert_almost_equal(loss0, 0.03)


@@ -289,16 +289,56 @@
 _pred):%0A
+    if K.backend() == %22tensorflow%22:%0A    
     sess
@@ -359,16 +359,20 @@
 ssion()%0A
+    
     y_tr
@@ -414,16 +414,20 @@
 _true%22)%0A
+    
     y_pr
@@ -469,16 +469,20 @@
 _pred%22)%0A
+    
     resu
@@ -519,16 +519,20 @@
 ar)%0A    
+   
+ 
 return r
@@ -559,16 +559,311 @@
 ession)%0A
+    elif K.backend() == %22theano%22:%0A        y_true_var = K.constant(y_true, name=%22y_true%22)%0A        y_pred_var = K.constant(y_pred, name=%22y_pred%22)%0A        result = loss(y_true_var, y_pred_var)%0A        return result.eval()%0A    else:%0A        raise ValueError(%22Unsupported backend: %25s%22 %25 K.backend())%0A
 %0A%0Adef te

fix test for theano