def maybe_clamp(x, x_range, ignored_if_non_positive):
    """Clamps `x` to `x_range`."""
    x_min, x_max = x_range
    if x_min is not None and x_max is not None and x_min > x_max:
      raise ValueError('Invalid range: %s.' % str(x_range))
    if (x_min is not None) and (not ignored_if_non_positive or x_min > 0.0):
      x = tf.math.maximum(x_min, x)
    if (x_max is not None) and (not ignored_if_non_positive or x_max > 0.0):
      x = tf.math.minimum(x_max, x)
    return x