import torch


def iou_loss_tblr(pred, target, eps=1e-6):
    """
    calculate the iou loss when both the prediction and targets are encoded in TBLR format
    Args:
        pred: shape (num_anchor, 4)
        target: shape (num_anchor, 4)
        eps: the minimum iou threshold

    Returns:
        loss: shape (num_anchor), IoU loss

    """
    xt, xb, xl, xr = torch.split(pred, 1, dim=-1)

    # the ground truth position
    gt, gb, gl, gr = torch.split(target, 1, dim=-1)

    # compute the bounding box size
    X = (xt + xb) * (xl + xr)  # AreaX
    G = (gt + gb) * (gl + gr)  # AreaG

    # compute the IOU
    Ih = torch.min(xt, gt) + torch.min(xb, gb)
    Iw = torch.min(xl, gl) + torch.min(xr, gr)

    I = Ih * Iw
    U = (X + G - I).clamp(min=1)  # minimum area should be 1

    IoU = I / U
    IoU = IoU.squeeze()
    ious = IoU.clamp(min=eps)
    loss = -ious.log()
    return loss