import torch


def encode_boxes_to_anchors(boxes, anchors, eps=1e-8):
    """ Create anchors regression target based on anchors
    Args:
        boxes: ground truth boxes.
        anchors: anchor boxes on all feature levels.
        eps: small number for stability
    Returns:
        outputs: anchors w.r.t. ground truth
    """

    def corner_to_center(rects):
        h, w = rects[:, 2] - rects[:, 0], rects[:, 3] - rects[:, 1]
        y_ctr, x_ctr = rects[:, 0] + 0.5 * h, rects[:, 1] + 0.5 * w
        return y_ctr, x_ctr, h, w

    ycenter_a, xcenter_a, ha, wa = corner_to_center(anchors)
    ycenter, xcenter, h, w = corner_to_center(boxes)
    ha, wa, h, w = ha + eps, wa + eps, h + eps, w + eps
    dy = (ycenter - ycenter_a) / ha
    dx = (xcenter - xcenter_a) / wa
    dh = torch.log(h / ha)
    dw = torch.log(w / wa)
    outputs = torch.stack([dy, dx, dh, dw]).T

    return outputs