def nearest_2n_indices(x, i, n):
    """Calculates the nearest 2n indices centred at i in an array x, or as close
    as possible to i, taking into account that i might be within n indices of
    an endpoint of x.

    The function returns the limiting indices as a pair, and always returns
    an interval that contains 2n+1 indices, assuming x is long enough.

    I.e., away from endpoints, the function returns (i-n, i+n).
    If i is within n of index 0, the function returns (0, 2n).
    If i is within n of last index L, the function returns (L-2n, L).

    Remember to add one to the upper limit if using it in a slice.
    """
    assert len(x) > 2 * n, "x is not long enough"
    # ixlo = 0
    ixhi = len(x) - 1
    if i < n:
        # too close to low end
        return (0, 2 * n)
    elif i > ixhi - n:
        # too close to high end
        return (ixhi - 2 * n, ixhi)
    else:
        return (i - n, i + n)