import torch


def warp_homography(sources, homography):
    """Warp features given a homography

    Parameters
    ----------
    sources: torch.tensor (1,H,W,2)
        Keypoint vector.
    homography: torch.Tensor (3,3)
        Homography.

    Returns
    -------
    warped_sources: torch.tensor (1,H,W,2)
        Warped feature vector.
    """
    _, H, W, _ = sources.shape
    warped_sources = sources.clone().squeeze()
    warped_sources = warped_sources.view(-1,2)
    warped_sources = torch.addmm(homography[:,2], warped_sources, homography[:,:2].t())
    warped_sources.mul_(1/warped_sources[:,2].unsqueeze(1))
    warped_sources = warped_sources[:,:2].contiguous().view(1,H,W,2)
    return warped_sources