def _clamp(f, lower, upper, k=100, m=None):
    """Clamps the value of f such that the result is lower if f < lower, and
    upper if f > upper, or f otherwise.

    Parameters
    ----------
    f : gekko variable or intermediate
    lower : gekko variable or intermediate or number
    upper : gekko variable or intermediate or number
    k : int >= 1, default = 100
        The quality of the switch approximation. Larger is better.
    m : GEKKO

    returns
    -------
    fx : gekko intermediate
        An approximation of the clamp function.
    """
    if m is None:
        raise Exception('Missing GEKKO model definition.')

    fup = m.switch(f, upper, f, upper)
    return m.switch(lower, fup, fup, lower)