import torch


def anchors_plane(anchor_ref, feat_h, feat_w, stride):
    """Builds the anchors plane for the given feature map shape.

    Based on an anchor reference, reproduces it at every point of the feature
    map, according to the specified stride. `anchor_ref` is set in real-image
    coordinates, so we must know what the stride for the current feature map
    is.

    Parameters
    ----------
    anchor_ref : torch.Tensor of size (A, 4)
        Coordinates for each of the `A` anchors, centered at the origin.
    feat_h : int
        Height of the feature map.
    feat_w : int
        Width of the feature map.
    stride : int
        Number of pixels every which to apply the anchor reference.

    Returns
    -------
    torch.Tensor of size (feat_h * feat_w * A, 4)
        The dtype and device of the returned tensor is based on `anchor_ref`.

    """
    device = anchor_ref.device
    dtype = anchor_ref.dtype

    shift_y, shift_x = torch.meshgrid(
        torch.arange(feat_h, dtype=dtype, device=device) * stride,
        torch.arange(feat_w, dtype=dtype, device=device) * stride,
    )

    shift_x = shift_x.reshape(-1)
    shift_y = shift_y.reshape(-1)

    shifts = torch.stack([
        shift_x, shift_y, shift_x, shift_y,
    ], dim=-1)

    anchors = (
        anchor_ref[None, ...] + shifts[:, None, :]
    ).reshape(-1, 4)

    return anchors