def snap_to()

in bayesmark/np_util.py [0:0]


def snap_to(x, fixed_val=None):
    """Snap input `x` to the `fixed_val` unless `fixed_val` is `None`, where `x` is returned.

    Parameters
    ----------
    x : :class:`numpy:numpy.ndarray`
        Array containing elements to snap.
    fixed_val : :class:`numpy:numpy.ndarray` or None
        Values to be returned if `x` is close, otherwise an error is raised. If `fixed_val` is `None`, `x` is returned.

    Returns
    -------
    fixed_val : :class:`numpy:numpy.ndarray`
        Snapped to value of `x`.
    """
    if fixed_val is None:
        return x

    # Include == for discrete types where allclose doesn't work
    if not (np.all(x == fixed_val) or np.allclose(x, fixed_val)):
        raise ValueError("Expected fixed value %s, got %s." % (repr(fixed_val), repr(x)))

    assert np.all(x == fixed_val) or np.allclose(x, fixed_val)
    fixed_val = np.broadcast_to(fixed_val, np.shape(x))
    return fixed_val