import torch


def h_inverse(x, epsilon=1.0):
    """Inverse if the above h-function, described in the paper [1].

    If x > 0.0:
    h-1(x) = [2eps * x + (2eps + 1) - sqrt(4eps x + (2eps + 1)^2)] /
        (2 * eps^2)

    If x < 0.0:
    h-1(x) = [2eps * x + (2eps + 1) + sqrt(-4eps x + (2eps + 1)^2)] /
        (2 * eps^2)
    """
    two_epsilon = epsilon * 2
    if_x_pos = (
        two_epsilon * x
        + (two_epsilon + 1.0)
        - torch.sqrt(4.0 * epsilon * x + (two_epsilon + 1.0) ** 2)
    ) / (2.0 * epsilon ** 2)
    if_x_neg = (
        two_epsilon * x
        - (two_epsilon + 1.0)
        + torch.sqrt(-4.0 * epsilon * x + (two_epsilon + 1.0) ** 2)
    ) / (2.0 * epsilon ** 2)
    return torch.where(x < 0.0, if_x_neg, if_x_pos)