def r_to_p(r, d, rtype='EI'):
    """
    Inverse of the p_to_r function.

    Parameters
    ----------
    r : float
        The RB error rate

    d : int
        Number of dimensions of the Hilbert space

    rtype : {'EI','AGI'}, optional
        The RB error rate rescaling convention.

    Returns
    -------
    p : float
        The RB decay constant
    """
    if rtype == 'AGI': p = 1 - d * r / (d - 1)
    elif rtype == 'EI': p = 1 - d**2 * r / (d**2 - 1)
    else:
        raise ValueError("rtype must be `EI` (for entanglement infidelity) or `AGI` (for average gate infidelity)")

    return p