import math
import warnings
import torch


def trunc_normal(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0):
    """
    Fills the input tensor with`values drawn from a truncated normal distribution.
    The values are effectively drawn from the normal distribution(`N(mu, var)`) 
    with values outside(`[a, b]`) redrawn until they are within the bounds.
    The method used for generating the random values works best when `a <= mean <= b`.

    Args:
        tensor (torch.Tensor): an n-dimensional tensor
        mean (float): the mean of normal distribution
        std (float): the standard deviation of the normal distribution
        a (float): the minimum cutoff value
        b (float): the maximum cutoff value

    Returns:
        [torch.Tensor]: an n-dimensional tensor which is truncated
    """
    def norm_cdf(x):
        """Computes the standard normal cumulative distribution function"""
        return (1. + math.erf(x / math.sqrt(2.))) / 2.

    if (mean < a - 2 * std) or (mean > b + 2 * std):
        warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
                      "The distribution of values may be incorrect.",
                      stacklevel=2)

    with torch.no_grad():
        # Values are generated by using truncated uniform distribution
        # and then using the inverse CDF for the normal distribution.
        # Get upper and lower CDF values
        lower = norm_cdf((a - mean) / std)
        upper = norm_cdf((b - mean) / std)

        # Uniformly fill tensor with the values from [lower, upper]
        # and then translate to [2*lower-1, 2*upper-1].
        tensor.uniform_(2 * lower - 1, 2 * upper - 1)

        # Use inverse CDF transform for normal distribution
        # to get truncated standard normal
        tensor.erfinv_()

        # Transform to proper mean, std
        tensor.mul_(std * math.sqrt(2.))
        tensor.add_(mean)

        # Clamp to ensure it's in the proper range
        tensor.clamp_(min=a, max=b)

    return tensor