import torch


def get_rois_target_levels(levels, base_scale, rois):
    """
    Assign proposals to different level feature map to roi pooling

    Arguments:
        rois (FloatTensor): [R, 5] (batch_ix, x1, y1, x2, y2)
        levels (list of int): [L], levels. e.g.[2, 3, 4, 5, 6]
        base_scale: scale of the minimum level
    """
    w = rois[:, 3] - rois[:, 1] + 1
    h = rois[:, 4] - rois[:, 2] + 1
    scale = (w * h)**0.5
    eps = 1e-6
    target_levels = (scale / base_scale + eps).log2().floor()
    target_levels = target_levels.to(dtype=torch.int64)
    min_level, max_level = min(levels), max(levels)
    return torch.clamp(target_levels, min=min_level, max=max_level)