import tensorflow as tf


def sigmoid_ce_with_logits(logits, labels):
    return tf.nn.sigmoid_cross_entropy_with_logits(labels=labels, logits=logits)

def sigmoid_kl_with_logits(logits, targets):
    assert isinstance(targets, float)
    if targets in [0., 1.]:
        entropy = 0.
    else:
        entropy = - targets*tf.log(targets) - (1. - targets)*tf.log(1. - targets)
    return sigmoid_ce_with_logits(logits, tf.ones_like(logits)*targets) - entropy

def gradient_difference_loss(x, y):
    x_h_diff = x[:, 1:] - x[:, :-1]
    x_w_diff = x[:, :, 1:] - x[:, :, :-1]
    y_h_diff = y[:, 1:] - y[:, :-1]
    y_w_diff = y[:, :, 1:] - y[:, :, :-1]
    h_diff = tf.abs(tf.abs(x_h_diff) - tf.abs(y_h_diff))
