import torch


def binary_hyperplane_margin(X, Y, w, b, weight=1.0):
    """ A potential function based on margin separation according to a (given
        and fixed) hyperplane:

        v(x,y) = max(0, 1 - y(x'w - b) ), so that V(ρ) = ∫ max(0, y(x'w - b) ) dρ(x,y)

    Returns 0 if all points are at least 1 away from margin.

    Note that y is expected to be {0,1}

    Needs separation hyperplane be determined by (w, b) parameters.
    """
    Y_hat = 2*Y-1 # To map Y to {-1, 1}, required by the SVM-type margin obj we use
    margin = torch.relu(1-Y_hat*(torch.matmul(X, w) - b))
    return weight*margin.mean()