import torch
import torch.nn.functional as F
import math

def soft_clamp(x: torch.Tensor, min_val: float = 1e-12, softness: float = 1e12) -> torch.Tensor:
    """
    Implements C^2 Continuous 'Soft Clamping'.
    Smoothly transitions to min_val without a 'kink'.
    y = min + softplus((x - min) * softness) / softness
    
    NOTE: Softness must be high enough to not distort values of interest.
    Softness=100 puts knee at 1e-2, destroying signal.
    Softness=1e12 puts knee at 1e-12.
    """
    if softness <= 0:
        raise ValueError(f"Softness must be positive, got {softness}")
    return min_val + F.softplus((x - min_val) * softness) / softness

def robust_inv_softplus(x):
    """Helper to safely initialize softplus parameters"""
    return math.log(math.expm1(x))
