import torch


def linear_interpolation_weights(x, n_points, zero_falloff=False):
    """
    Compute linear interpolation weights
    to points at x from regularly interspersed points.
    :param x: coordinates of points to interpolate to, in range [0, 1].
    :param n_points: number of regularly interspersed points.
    :param zero_falloff: if set to True, the interpolated function falls to 0 at x = 1.
    """
    assert(x.dim() == 1)
    if zero_falloff:
        n_points += 1
    x = x * (n_points - 1)
    x0 = torch.floor(x).long()
    x1 = x0 + 1

    x0 = torch.clamp(x0, 0, n_points - 2)
    x1 = torch.clamp(x1, 1, n_points - 1)
    
    w0 = x1.float() - x
    w1 = x - x0.float()

    weights = torch.zeros((x.size(0), n_points), device=x.device)
    weights[torch.arange(x.size(0)), x0] = w0
    weights[torch.arange(x.size(0)), x1] = w1

    if zero_falloff:
        weights = weights[:, :-1]

    return weights