def p_to_r(p, d, rtype='EI'):
    """
    Converts an RB decay constant (`p`) to the RB error rate (`r`).

    Here `p` is (normally) obtained from fitting data to `A + Bp^m`. There are two
    'types' of RB error rate corresponding to different rescalings of `1 - p`.
     These are the entanglement infidelity (EI) type r and the average gate
    infidelity (AGI) type `r`. The EI-type `r` is given by:

    `r =  (d^2 - 1)(1 - p)/d^2`,

    where `d` is the dimension of the system (i.e., 2^n for n qubits).
    The AGI-type `r` is given by

    `r =  (d - 1)(1 - p)/d`.

    For RB on gates whereby every gate is followed by an n-qubit
    uniform depolarizing channel (the most idealized RB scenario)
    then the EI-type (AGI-type) r corresponds to the EI (AGI) of
    the depolarizing channel to the identity channel.

    The default (EI) is the convention used in direct RB, and is perhaps
    the most well-motivated as then r corresponds to the error probablity
    of the gates (in the idealized pauli-errors scenario). AGI is
    the convention used throughout Clifford RB theory.

    Parameters
    ----------
    p : float
        Fit parameter p from P_m = A + B*p**m.

    d : int
        Number of dimensions of the Hilbert space

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

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

    return r